《快学scala》习题解答-第三章-数组相关操作

《快学Scala》(英文版:《Scala for the Impatient》),代码已传github:

https://github.com/vernonzheng/scala-for-the-Impatient

书为第一版。scala为2.11.4,jdk1.7.45,操作系统Mac OS X Yosemite 10.10.1。

第三章 数组相关操作

3.1
编写一段代码,将a设置为一个n个随机整数的数组,要求随机数介于0(包含)和n(不包含)之间

答:

1
2
3
4
5
6
7
8
9
10
11
import scala.util.Random
import scala.math.random
def randomArray(n: Int) :Array[Int] = {
val array = for( i<- 0 to n) yield Random.nextInt(n)
array.toArray
}
def randomArray2(n: Int) :Array[Int] = {
val array = for( i<- 0 to n) yield (random * n).toInt
array.toArray
}

3.2
编写一个循环,将整数数组中相邻的元素置换。例如,Array(1,2,3,4,5)经过置换后变为Array(2,1,4,3,5)

答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def arrayChange(array: Array[Int]) :Array[Int] = {
if(array == null)
return null
for(i <- 0 until array.length if i % 2 ==0 && i > 0){
val tmp = array(i-1)
array(i-1) = array(i)
array(i) = tmp
}
array
}
def arrayChange2(arr: Array[Int]) :Array[Int] = {
val t = arr.toBuffer
for(i <- 0 until (t.length,2) if i + 1 < t.length){
val a = t(i)
val b = t(i + 1)
t.remove(i,2)
t.insert(i,b)
t.insert(i + 1,a)
}
t.toArray
}

3.3
重复前一个练习,不过这一次生成一个新的值交换过的数组。用for/yield

答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def arrayChange(array: Array[Int]) :Array[Int] = {
if(array == null)
return null
val length = array.length
var flag = true
val newArray = for(i <- 0 until length if flag) yield{
var item = 0
if(i+1 >= length){
flag = false
}
if(i%2 == 0){
item = array(i+1)
}else if(i%2 == 1){
item = array(i-1)
}
item
}
newArray.toArray
}

3.4
给定一个整数数组,产生一个新的数组,包含元数组中的所有正值,以原有顺序排列,之后的元素是所有零或负值,以原有顺序排列

答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def sortArray(array:Array[Int]):Array[Int] = {
val newArrayBuffer = new ArrayBuffer[Int]()
val positiveIndex = for(i <- 0 to array.length if array(i) > 0 ) yield {array(i)}
newArrayBuffer ++= positiveIndex.toBuffer
newArrayBuffer ++= (for(i <- 0 to array.length if !positiveIndex.contains(i)) yield{array(i)}).toBuffer
newArrayBuffer.toArray
}
def sortArray2(array:Array[Int]):Array[Int] = {
val a = ArrayBuffer[Int]()
val b = ArrayBuffer[Int]()
array.foreach(arg => if(arg > 0) a += arg else b += arg)
a ++= b
a.toArray
}
def sortArray3(array:Array[Int]):Array[Int] = {
val a = array.filter(_>0).map(_*1)
val b = array.filter(_<=0).map(_*1)
var c = a.toBuffer
c ++= b.toBuffer
c.toArray
}

3.5
如何计算Array[Double]的平均值

答:

1
2
3
def avgArray(array:Array[Double]):Double={
array.sum/array.length
}

3.6
如何重新组织Array[Int]的元素将他们以反序排列?对于ArrayBuffer[Int]你又会怎么做呢?

答:

1
2
3
def reverseArray(arr:Array[Int]):Array[Int]={
arr.reverse
}

3.7
编写一段代码,产出数组中的所有值,去掉重复项。(提示:查看Scaladoc)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def removeArray1(arr:Array[Int]):Array[Int]={
val t = arr.toBuffer
val idx =(for(i <- 0 until t.length if t(i) < 0) yield { i }).reverse.toBuffer
idx.trimEnd(1)
idx.foreach(arg => t.remove(arg))
t.toArray
}
def removeArray2(array:Array[Int]):Array[Int]={
val arr = array.toBuffer
var first = true
val indexes = for(i <- 0 until arr.length if first || arr(i) >= 0) yield{
if(arr(i) < 0) first = false;i
}
for(j <- 0 until indexes.length) arr(j) = arr(indexes(j))
arr.trimEnd(arr.length - indexes.length)
arr.toArray
}
def performance():Unit={
val array = Array(1,-2,3,55,3,-4,-6,-2,-1,55,-3,5)
val startTime1 = System.currentTimeMillis()
for(i <- 0 to 10000) {
removeArray1(array)
}
val endTime1 = System.currentTimeMillis()
val startTime2 = System.currentTimeMillis()
for(i <- 0 to 10000) {
val result2 = removeArray2(array)
}
val endTime2 = System.currentTimeMillis()
println("removeArray1 cost:"+(endTime1-startTime1))
println("removeArray2 cost:"+(endTime2-startTime2))
//10000次 201:81
}
/**
* scala> performance
removeArray1 cost:231
removeArray2 cost:163
scala> performance
removeArray1 cost:16
removeArray2 cost:14
scala> performance
removeArray1 cost:12
removeArray2 cost:6
scala> performance
removeArray1 cost:13
removeArray2 cost:7
scala> performance
removeArray1 cost:18
removeArray2 cost:5
*/

3.9
创建一个由java.util.TimeZone.getAvailableIDs返回ide时区集合,判断条件是它们在美洲。去掉”America/“前缀并排序

答:

1
2
3
4
5
def sortAmericaTimeZone():Unit = {
val array = java.util.TimeZone.getAvailableIDs
val result = array.filter(_.startsWith("America")).map(_.replace("America/","")).sorted
result.foreach(println(_))
}

3.10
引入java.awt.datatransfer.并构建一个类型为SystemFlavorMap类型的对象:
val flavors = SystemFlavorMap.getDefaultFlavorMap().asInstanceOf[SystemFlavorMap]
然后以DataFlavor.imageFlavor为参数调用getNativesForFlavor方法,以Scala缓冲保存返回值。
(为什么用这样一个晦涩难懂的类?因为在Java标准库中很难找到使用java.util.List的代码)

答:

1
2
3
4
5
6
7
8
9
import java.awt.datatransfer.{DataFlavor, SystemFlavorMap}
import collection.JavaConversions.asScalaBuffer
import scala.collection.mutable
def test():Unit = {
val flavors = SystemFlavorMap.getDefaultFlavorMap().asInstanceOf[SystemFlavorMap]
val res:mutable.Buffer[String] = flavors.getNativesForFlavor(DataFlavor.imageFlavor)
println(res)
}

参考:
《快学Scala》:http://book.douban.com/subject/19971952/

(转载本站文章请注明作者和出处 Vernon Zheng(郑雪峰) – vernonzheng.com ,请勿用于任何商业用途)