1

How can I get specific elements of an array by having the sequence of indices, I do it now by following:

val indices = Array(1,3,3,2)
val a = Array("a","b","c","d","e","f")
indices.map(a(_))

the problem is if I want to make it a safe search I have to check a.contains or modify the indices. sometimes the indices is to big and I can not modify it fast. What is the best time/space solution?

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
Omid
  • 1,959
  • 25
  • 42

4 Answers4

6

Here it is:

scala> val indices = Array(1, 2, 3, 2, 100, -100, 4, 5)
indices: Array[Int] = Array(1, 2, 3, 2, 100, -100, 4, 5)

scala> val arr = Array("a", "b", "c", "d")
arr: Array[String] = Array(a, b, c, d)

scala> indices collect arr
res1: Array[String] = Array(b, c, d, c)
Eastsun
  • 18,526
  • 6
  • 57
  • 81
0

Assuming you just want to ignore every out-of-bounds-index you could just use a filter before mapping:

indices.filter(_ < a.length).map(a(_))
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
  • the first filter needs go over all data, it takes 2*size of indices time and size – Omid Sep 06 '14 at 23:04
  • Change `filter` to `withFilter` and you remove the `2n` iteration time at the least (not sure about the space off the top of my head though). – Sean Vieira Sep 06 '14 at 23:30
  • @SeanVieira What is the difference between them ? – Omid Sep 07 '14 at 01:41
  • See http://stackoverflow.com/a/19618241/135978 - basically, withFilter is most likely lazy and doesn't create another collection - instead it's a simplified `view`. – Sean Vieira Sep 07 '14 at 02:04
0

Using flatMap where out of bound indexes are mapped onto None, like this,

indices.flatMap(i => if (i < a.length) Some(a(i)) else None)

Simpler forms with flatMap,

indices.flatMap(i => Some(a(i)))
res: Array(b, d, d, c)

indices.flatMap(a(_))
res: Array(b, d, d, c)
Paul Reiners
  • 8,576
  • 33
  • 117
  • 202
elm
  • 20,117
  • 14
  • 67
  • 113
0

If you don't want to use collect you may try :

val indices = Array(1, 2, 3, 2)
val arr = Array("a", "b", "c", "d")
val res = for (i <- indices) yield arr(i)
Lucas Meier
  • 369
  • 3
  • 6