Scala使用(冒泡排序、单词计数、随机数)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41851454/article/details/79980184

冒泡排序:

用Scala编写
package Demo

object BubbleSort {

  def main(args: Array[String]): Unit = {
    val arr = Array(2,3,44,1,3,4)

    for (i <- 0 until(arr.length)){
      for (j <- 0 until(arr.length-1-i)){
        if (arr(j) > arr(j+1)){
          val a = arr(j)
          arr(j) = arr(j+1)
          arr(j+1) = a
        }
      }
    }
    for (aa <- arr){
      print(aa+ " ")
    }
  }
}

单词计数:

用Scala编写:
val array=Array(“you,jump”,“i,jump”)

单词计数:

scala> array.flatMap(_.split("#")).map( (_,1)).groupBy( t  =>  t._1).map( map =>
(map._1,map._2.length)).toList.sortBy( t => t._2).reverse
res28: List[(String, Int)] = List((jump,2), (i,1), (you,1))

随机生成100以内的5个不重复的随机数?

用java编写:
import java.util.HashSet;

public class partice3 {
    public static void main(String[] args) {
        HashSet<Integer> hs = new HashSet<>();
        while (hs.size() < 5){
            int a = (int)(Math.random() * 100);
            if (a > 0 && a <= 100){
                hs.add(a);
            }
        }
        System.out.println(hs);
    }
}
Scala编写:
import scala.collection.mutable
import scala.util.Random

object partice2 {

  def main(args: Array[String]): Unit = {

    val set = new mutable.HashSet[Int]()
    while (set.size < 5){
      val a = new Random().nextInt(100)
      set.add(a)
    }
    println(set)
  }
}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页