1

Suppose I have a sequence of integers and a number n < 30. How can I produce an array (of length n) that is 0 in all places except at the indices specified by the sequence (where it should be 1)?

For instance

Input:

Seq(1, 2, 5)
7

Output:

Array(0, 1, 1, 0, 0, 1, 0)

3 Answers 3

6
scala> val a = Array.fill(7)(0)
a: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0)

scala> Seq(1,2,5).foreach(a(_) = 1)

scala> a
res1: Array[Int] = Array(0, 1, 1, 0, 0, 1, 0)
Sign up to request clarification or add additional context in comments.

Comments

4

Alternatively,

scala> val is = Set(1, 2, 5)
is: scala.collection.immutable.Set[Int] = Set(1, 2, 5)

scala> Array.tabulate(10)(i => if (is contains i) 1 else 0)
res0: Array[Int] = Array(0, 1, 1, 0, 0, 1, 0, 0, 0, 0)

1 Comment

Use is(i) if you can afford the parens.
2
def makeArray(indices: Seq[Int], size: Int): Array[Int] = Iterable.tabulate(size) {
  case idx if indices contains idx => 1
  case _ => 0
}.toArray

makeArray(Seq(1, 2, 5), size = 7)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.