Learn scala-. Chapter III Array related operations

Source: Internet
Author: User
Tags time zones

Knowledge Points:

1. Fixed-length array

New // array of 10 integers, all elements initialized to 0 New // A string array of 10 elements, all elements initialized to null // An array (String) of length 2 is inferred by the compiler, and the initial value provided does not require a new // Array ("Google", "World") uses () instead of [] to access elements

Scala's array is implemented as a Java array, and s in the example corresponds to java.lang.string[]

2. Variable-length array: Array buffer ArrayBuffer

For an array of length changes as needed, Java-arraylist | | C++-vector | | Scala-arraybuffer

  // or new Arraybuffer[int]  // ArrayBuffer (1) Adding elements to the tail end with + =  // ArrayBuffer (1,1,2,3,4,5) adds multiple elements at the end, wrapping them  in parentheses // ArrayBuffer (1,1,2,3,4,5,6,7,8)  append any set  with ++= // ArrayBuffer (1,1,2,3) removes the last 5 elements

Adding or removing elements at the tail end of an array buffer is an efficient operation. You can also insert and delete elements at any location, which is not efficient, and the elements that are raised after the position must be panned.

  // ArrayBuffer (1,1,9,2,3)  // ArrayBuffer (1,1,10,11,9,2,3)  // ArrayBuffer (1,1,11,9,2,3)  // ArrayBuffer (1,1,3)

Sometimes you need to build an array, but you don't know how many elements there are, you can build Arraybuffer first, then call B.toarray (), and in turn, call A.tobuffer to convert an array A to an array buffer.

3. Iterating through arrays and array buffers

 for // variable I value is taken from 0 to a.length-1    println (i + ":" + A (i))

for (i <-interval) will let I traverse all values of the interval.

0 until (a.length, 2)   //Range (0,2,4,6,...) One hop per two elements     (0 until A.length ). Reverse  //Range (..., 3,2,1,0) reverse order for    (Elem <-a)  // When array subscripts are not used    println (Elem)

3. Array conversion

Val aa = Array (2,5,8,9)  for (elem <-AA) Yield 2 * elem  //  Result is an array (4,10,16,18)

The for (...) yield loop creates a new collection of the same type as the original collection. The result contains the expression after yield, which corresponds to one iteration at a time. When you traverse a collection, you only want to handle those elements that satisfy a particular condition, which can be implemented by guarding: for If.

 for if elem% 2 = = 0) Yield 2 * elem//Another way to implement
% 2 = = 0). Map (2*% 2 = = 0} map {2 * _}

4. Common methods

The array element type of the sum\max\sorted sum method must be a numeric type, the sorted method sorts the array or buffer array, returns a sorted array or buffer array, and does not modify the original version.

You can use the Mkstring method to display the contents of an array or buffer array.

5. Multidimensional arrays are implemented by array arrays

  Val matrix = array.ofdim[double] (3,4)  =//create irregular    array new Array[array[int] (10 )  for (i <-0 until triangle.length)    new Array[int] (i+1)


Exercise: (Answer Source link)

1. Write a piece of code that sets a to an array of n random integers, requiring a random number between 0 (inclusive) and n (not included)

class test{  def main (Args:array[int]) {    Getarr (ten). foreach (println)  }    = {     new  Array[int] (n)    new  scala.util.Random ()    for (i <- a) yield Rand.nextint ()  }  }

2. Write a loop that replaces adjacent elements in an array of integers

class test{  def main (Args:array[int]) {    = Array (1,2,3,4,5)    revert (arr)    Arr.foreach (println  }    = {    for (i <-0 until (a.length-1,2)) {      = A (i)      = A (i+1)      A (i+ 1) = t    }   }}

3. Repeat the previous exercise, but this time generate a new value for the swapped array. With For/yield.

classtest{def main (Args:array[int]) {val a= Array (1,2,3,4,5) Val B=Revertyield (a) B.foreach (println)} def revertyield (A:array[int])= {     for(I <-0until A.length) yield {if(I < (a.length-1) && I% 2 = = 0){        //when even subscript, the next adjacent element value is exchangedVal t =A (i) a (i)= A (i+1) A (i+1) =T} A (i)//because a new array is generated, each element is returned    }  }}

4. Given an array of integers, a new array is produced, containing all the positive values in the tuple, arranged in the original order, followed by all 0 or negative values, arranged in the original order.

Import Scala.collection.mutable.ArrayBuffer class test{  def main (Args:array[int]) {    = Array (1,-2,0,4,5,0,-3)    = recombine (a)    B.foreach (println)  }    = {    new  Arraybuffer[int] ();     ++= (forif(i > 0)) yield i)    ++= (forif(i = = 0 | | I < 0
   
    )) yield i)    Buf.toarray  }}
   

5. How do I calculate the average of array[double]?

class test{  def main (Args:array[int]) {    = Array (1.0,5.6,0.0,-3.0)    = average (a)    println (b)  }    = {    = 0.0 for    (i <- a) {      + = I    }    t/a.length  }    = {     / a.length  }}

6. How do I reorganize the elements of array[int] to order them in reverse order? What are you going to do about Arraybuffer[int]?

Importscala.collection.mutable.ArrayBufferobject Hello {def main (args:array[string]) {val a= Array (1,2,3,4,5) Reversearray (a) println ("Array Reverse:") A.foreach (println) Val b= A.reverse//turn the value of a back in reverse.B.foreach (println) println ("Bufferarray Reverse:") Val C= ArrayBuffer (6,7,8,9,0); Val d=c.reverse D.foreach (println)} def reversearray (A:array[int])= {     for(I <-0 until (A.LENGTH/2) ) {val T=A (i) a (i)= A (a.length-1-i) A (a.length-1-i) =T} }}

7. Write a piece of code that outputs all the values in the array, removing duplicates

 import   Scala.collection.mutable.ArrayBufferobject Hello {def main (args:array[string]) {val ab  = new   Arraybuffer[int] () val c  = new   Arraybuffer[int] () println (" Input the array line, Separated by a space,ended with an enter. "    ) val input  = ReadLine (). toString (). Split (" for  (i <- input) {AB  += I.toint}  //  Ab.foreach ( println)  c ++= ab.distinct C.foreach (println)}}  

8. Rewrite The example at the end of section 3.4. Collect the subscript of the negative element, reverse the order, remove the last subscript, and then call A.remove (i) for each subscript. Compare the efficiency of this and the efficiency of the other two methods in section 3.4

Importscala.collection.mutable.ArrayBufferobject Hello {def main (args:array[string]) {val a= ArrayBuffer (1,2,4,-2,0,-1,-4,8) Deleteneg (a) A.foreach (println)} def Deleteneg (A:arraybuffer[int])={val Indexes= for(i <-0 until A.lengthifA (i) < 0) Yield I//cannot val B = indexex.reverse.trimEnd (1) After reverse, it is a SEQ sequence. //value TrimEnd is not a member of Scala.collection.immutable.indexedseq[int]Val B =NewArraybuffer[int] () b++=indexes.reverse B.trimend (1)    //Remove is a function of arraybuffer, and if an array is passed in, you need to call Tobuffer     for(I <-b) {A.remove (i) }}}

9. Create a collection of time zones returned by Java.util.TimeZone.getAvailableIDs, judging by the condition that they are in the Americas, removing the "america/" prefix and sorting.

 import   Scala.collection.mutable.ArrayBuffer  import   Scala.collection.JavaConversions.asScalaBufferobject hello{def main (args:array[ String])  = {var c  = timeZoneName () C.forea CH (println)} def timezonename ()  = {val arr  = Java.util.TimeZone.getAvailableIDs (); val tmp  = (for  (i <-arr if  I.startswith ("america/"  "america/"    .length)}) Scala.util.Sorting.quickSort (TMP) tmp}}  

10. Introduce java.awt.datatransfer._ and construct an object of type Systemflavormap type. The Getnativesforflavor method is then called with the Dataflavor.imageflavor parameter, and the return value is saved in Scala buffer.

Import Scala.collection.JavaConversions.asScalaBuffer Import Scala.collection.mutable.Buffer Import java.awt.datatransfer._object hello{  def main (args:array[string])  = {     =  Systemflavormap.getdefaultflavormap (). Asinstanceof[systemflavormap]     =  Flavors.getnativesforflavor (dataflavor.imageflavor);     Buf.foreach (println);  }}

Learn scala-. Chapter III Array related operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.