How to locate intervals of non-empty values in Ruby's NArray?

91 views Asked by At

I am interested in locating all non-empty intervals in a NArray as tuples of [begin, end] type. So if we have a NArray of a given size and all values at index positions 100 ... 200, 300 ... 400, etc are non-zero, I would like to obtain an array like this: [[100,200], [300,400], etc]. I wonder is there is something in the NArray interface - which unfortunately is under-documented - that can help me? Speed is of cause critical.

Cheers,

Martin

1

There are 1 answers

1
masa16 On BEST ANSWER
$ irb -rnarray
irb> a = NArray[0,1,2,0,0,5,0,7,8,9]
irb> tmp = NArray.new( a.typecode, a.size+2 )
irb> tmp[1..-2] = a
irb> tmp
=> NArray.int(12): 
[ 0, 0, 1, 2, 0, 0, 5, 0, 7, 8, 9, 0 ]

irb> empty = tmp.eq(0)
=> NArray.byte(12): 
[ 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1 ]

irb> beg = (~empty[1..-1] & empty[0..-2]).where
=> NArray.int(3): 
[ 1, 5, 7 ]

irb> fin = (empty[1..-1] & ~empty[0..-2]).where
=> NArray.int(3): 
[ 3, 6, 10 ]

irb> range = NArray[beg,fin].transpose(1,0)
=> NArray.int(2,3): 
[ [ 1, 3 ], 
  [ 5, 6 ], 
  [ 7, 10 ] ]