如何在Scala中通过索引设置多个数组值?

时间:2015-10-21 00:19:23

标签: scala

假设我有一个整数序列和一个数字n< 30.如何在所有位置生成一个0(长度为n)的数组,除了序列指定的索引(它应该是1)?

例如

输入:

Seq(1, 2, 5)
7

输出:

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

3 个答案:

答案 0 :(得分:4)

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)

答案 1 :(得分:4)

可替换地,

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)

答案 2 :(得分: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)