Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting regions from a Scala Array

I don't really know how to describe what I'm doing, but this example should help:

val vals = Array( (0, true), 
                  (1, true), 
                  (2,true), 
                  (3,true), 
                  (4,false), 
                  (5, true), 
                  (6, true), 
                  (7, false), 
                  (8, true), 
                  (9,true))

I'm looking to identify the first and last elements in each of the 'true' regions, though partitioning the array when the value changes could work as well. I could do this imperatively, but what's the best way to do this in scala?

like image 860
fbl Avatar asked Dec 13 '22 08:12

fbl


1 Answers

If you don't mind adding some infrastructure to handle a groupedWhile feature, you can steal from Rex Kerr's answer on extending scala collection. Use the section that handles array, in the second part of the answer.

Then it's a breeze:

scala> vals.groupedWhile(_._2 == _._2).filter(_.head._2 == true).map{g => 
  (g.head, g.last)}.foreach(println)

((0,true),(3,true))
((5,true),(6,true))
((8,true),(9,true))

Edit:

I came up with a solution that does not require groupedWhile. It's based on using Iterator.iterate which starts from a seed and repeatedly applies the span function to extract the next group of elements that have the same boolean property. In this instance the seed is a tuple of the next group and the remainder to process:

type Arr = Array[(Int, Boolean)] // type alias for easier reading

val res = Iterator.iterate[(Arr, Arr)]((Array(), vals)){ case (same, rest) => 
  // repeatedly split in (same by boolean, rest of data)
  // by using span and comparing against head
  rest.span(elem => elem._2 == rest.head._2)
}.drop(1).takeWhile{ case (same, _) =>        // drop initial empty seed array
  same.nonEmpty                               // stop when same becomes empty
}.collect{ case (same, _) if same.head._2 == true =>
  // keep "true" groups and extract (first, last)
  (same.head, same.last)                     
}.foreach(println)                            // print result

Which prints the same result as above. Note that span for empty arrays does not call the predicate, so we don't get an exception on rest.head if rest is empty.

like image 163
huynhjl Avatar answered Mar 02 '23 07:03

huynhjl