user266003
user266003

Reputation:

Initializing an array so that each element of it would be equal to its index

I want to initialize an array so that each element of it would be equal to its index:

def method1(obj: AnyRef) = {
  //.... 
  if (obj.isInstanceOf[Array[Int]]) {
      val arr1 = obj.asInstanceOf[Array[Int]]
      val arr2: Array[Int] = new Array[Int](arr1.length)
      // initialize arr2. How?
      arr2 // arr2[0] = 0, arr2[1] = 1, etc....
    }

Upvotes: 0

Views: 454

Answers (2)

senia
senia

Reputation: 38045

You could convert Range to Array.

var arr2 = (0 until arr1.length).toArray

Method indices on collection returns Range:

var arr2 = arr1.indices.toArray

If you have an array and want to fill it you could use copyToArray method:

(0 until arr2.length).copyToArray(arr2)

There is no performance difference between this methods: toArray is implemented by the method copyToArray.

Range contains only 3 Int fields: start, end and step, so there is almost no memory overhead.

There is also method range in the Array object:

val arr2 = Array.range(0, arr1.length) // contains 0, excludes arr1.length

There are also some other methods to fill array. These methods are not so useful in this case.

Method fill:

var i = -1
val arr2 = Array.fill(arr1.length)({i+=1; i})

Method apply:

val arr2 = Array.apply(0, (1 until arr1.length): _*) // Array(0) on empty arr1

In case you have not Array collection and you want to change its elements and get Array you could use collection.breakOut method:

// this is not that case
val arr2: Array[Int] = (0 until arr1.length).map(identity)(breakOut)

Upvotes: 5

Marius Danila
Marius Danila

Reputation: 10401

For index based initializations we have the tabulate methods. In your case:

val arr2 = Array.tabulate(arr1.length)(index => index)

or, shorter

val arr2 = Array.tabulate(arr1.length)(identity)

Upvotes: 5

Related Questions