# Chapter 3 array related operations of quick learning scala

Posted by tripleaaa on Mon, 04 May 2020 14:26:33 +0200

Recently, I am learning this book, without java foundation. According to the blogger (I am a painter), I wrote the after-school questions. In Chapter 3, the blogger used several kinds of questions, but Xiaobai was not clear about his lack of knowledge. In my own way, I wrote several questions.

3.1 write a piece of code to set a as a n array of N random integers, requiring random numbers between 0 (inclusive) and n (exclusive).

```class array{
def arr(args: Array[Int]){
getArr(20).foreach(println)
}
def getArr(n: Int):Array[Int]={
val a = new Array[Int](n)
val rand = new scala.util.Random()
for(i <- a)yield rand.nextInt(n)
}
}
object test {
def main(args: Array[String]){
val s = new array
s.arr(Array())
}
}
```

3.2 write a loop to replace the adjacent elements in the integer Array. For example, Array (1, 2, 4, 5, 6) is changed to Array (2, 1, 5, 4, 6) after replacement

```object convert {
def main(args: Array[String]): Unit = {
val s = Array(4,5,6,7,8)
for (i <- 0 until (s.length-1,2)){   /*If i gets s.length-1, when the number of elements in the array is odd, i is even and s(i+1) is empty*/
val t = s(i)
s(i) = s(i+1)
s(i+1) = t
}
s.foreach(println)
}
}
```

3.3 repeat the previous exercise, but this time generate a new value swapped array. Use for/yield

```object yield_convert {
def main(args: Array[String]): Unit = {
val s = Array(4, 5, 6, 7, 8)
val result = {
for(i <- 0 until s.length)yield {
if (i % 2 == 0 & i < s.length-1){/*When i is an even number, the conversion is performed. When i is an odd number, the original array elements are directly copied to the new array*/
val t = s(i)
s(i) = s(i+1)
s(i+1) = t
}
s(i)
}
}
result.foreach(println)
}
}
```

3.4 given an array of integers, a new array is generated, including all the positive values in the array, arranged in the original order, and the elements since are all zero or negative values, arranged in the original sequence

```import scala.collection.mutable.ArrayBuffer
object positive_negative {
def main(args: Array[String]): Unit = {
val s = Array(3,5,-2,0,6,7,8)
val a = new ArrayBuffer[Int]()
a ++= (for(i <- s if i>0)yield i)
a ++= (for(i <- s if i<= 0)yield i)
a.foreach(println)
}
}
```

Other topics can be learned according to the article of the blogger (I am a painter): http://www.cnblogs.com/yiruparadie/p/5519649.html

Question:

1. java.util.TimeZone.getAvailableIDs

2.java.awt.datatransfer

Topics: Scala Java