I'm new to scala and I have a simple question.
What is the best way to create an Array[int] of length n1+n2 such that it has n1 "zero" elements and n2 one elements.
Example:
n1 = 3, n2 = 2
Array[Int] = Array(0, 0, 0, 1, 1)
Thanks
Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.
If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.
Elements in an array are obtained by using a zero-based index. That means the first element is at index 0, the second at index 1, and so on. Therefore, if the array has size N , the last element will be at index N-1 (because it starts with 0 ).
Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one. It is a collection of mutable values.
You can do
scala> Array.fill(3)(0) ++ Array.fill(2)(1)
res2: Array[Int] = Array(0, 0, 0, 1, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With