1.编写一段代码,将a设置为一个n个随机整数的数组,要求随机数介于0(包含)和n(不包含)之间
1 /** 2 * Created by vito on 2017/1/11. 3 */ 4 object ex1 { 5 def main(args: Array[String]): Unit = { 6 //从键盘获得输入 7 val n = readInt() 8 val array = new Array[Int](n) 9 for (i <- 0 until array.length) { 10 array(i) = (new util.Random).nextInt(n) 11 } 12 println(array.mkString(",")) 13 } 14 }
2.编写一个循环,将整数数组中相邻的元素置换。例如,Array(1,2,3,4,5)经过置换后变为Array(2,1,4,3,5)
1 /** 2 * Created by vito on 2017/1/11. 3 */ 4 object ex2 { 5 def main(args: Array[String]): Unit = { 6 val array = Array(1,2,3,4,5) 7 8 //将步进设置为2 9 for (i <- 0 until (array.length, 2)) { 10 if (i != array.length - 1) { 11 val tmp = array(i) 12 array(i) = array(i + 1) 13 array(i + 1) = tmp 14 } 15 } 16 println(array.mkString(",")) 17 } 18 }
3.重复前一个练习,不过这一次生成一个新的值交换过的数组。用for/yield。
1 /** 2 * Created by vito on 2017/1/11. 3 */ 4 object ex3 { 5 def main(args: Array[String]): Unit = { 6 val array = Array(1, 2, 3, 4, 5) 7 8 val newArray = for (i <- 0 until(array.length)) yield { 9 if (i != array.length - 1) { 10 if (i % 2 == 0) array(i + 1) else array(i - 1) 11 } else { 12 array(i) 13 } 14 15 } 16 17 println(newArray.mkString(",")) 18 } 19 }
4.如何计算Array[Double]的平均值?
1 /** 2 * Created by vito on 2017/1/11. 3 */ 4 object ex5 { 5 def main(args: Array[String]): Unit = { 6 val array = Array(1, 2, 3, 4, 5) 7 8 val avg = array.sum / array.length 9 10 println(avg) 11 } 12 }
5.创建一个二维数组,将其中一维数组的顺序逆序,并将每个一维数组中的值逆序。
1 scala> val dim = List(List(1,2,3), List(1,2,3,4), List(1,2,3,4,5)) 2 dim: List[List[Int]] = List(List(1, 2, 3), List(1, 2, 3, 4), List(1, 2, 3, 4, 5)) 3 4 scala> dim.map(_.reverse).reverse 5 res11: List[List[Int]] = List(List(5, 4, 3, 2, 1), List(4, 3, 2, 1), List(3, 2, 1))