Tim
Tim

Reputation: 2028

Convert positions to offsets with collections API

I am given a sequence of filed lengths in a line, and want to convert it into offsets from the start of the line. Easy to do procedurally with accumulator, wonder what would be the functional way. Quick solution is:

scala> val positions = Array(9,10,15,4)
positions: Array[Int] = Array(9, 10, 15, 4)

scala> val offsets = positions.zipWithIndex.map(t => positions.take(t._2).sum)
offsets: Array[Int] = Array(0, 9, 19, 34)

This is obviously sub-optimal as it computes offset for every element from scratch. Any better ideas?

Upvotes: 0

Views: 64

Answers (1)

Eastsun
Eastsun

Reputation: 18869

How about this:

positions.scanLeft(0){ _+_ }

If you wan to drop the last element:

positions.scanLeft(0){ _+_ }.init

Upvotes: 4

Related Questions