Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an Array of n1 "zeros" and n2 "ones" in scala

Tags:

arrays

scala

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

like image 664
user3370773 Avatar asked Nov 02 '14 16:11

user3370773


People also ask

How do you create an array with zeros?

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.

How do you assign zeros to all array elements?

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.

Why do we use N 1 in array?

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 ).

What is array in Scala?

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.


1 Answers

You can do

scala> Array.fill(3)(0) ++ Array.fill(2)(1) 
res2: Array[Int] = Array(0, 0, 0, 1, 1)
like image 82
mohit Avatar answered Oct 10 '22 09:10

mohit