Re: compact or uniq that takes a block like sort?
2008/1/7, Bil Kleb <Bil.Kleb@nasa.gov>:
> Hi,
>
> I'm looking for an elegant way to do the following:
>
> Given an sorted array of (X,Y) pairs where Y is strictly
> increasing, i.e., no repeated Ys.
>
> Compact pairs with repeated Xs, keeping the pair with
> the highest Y value.
>
> E.g.,
>
> require 'test/unit'
>
> class TestConsolidation < Test::Unit::TestCase
> def test_should_remove_repeated_Xs_but_save_one_with_h ighest_Y
> initial = [ [ 1, 12 ], [ 3, 15 ], [ 3, 17 ], [ 3, 22 ], [ 7, 45 ] ]
> desired = [ [ 1, 12 ], [ 3, 22 ], [ 7, 45 ] ]
> assert_equal desired, initial.consolidate
> end
> end
>
> class Array
> def consolidate
> # Too embarrassed to show current hack.
> end
> end
>
> My least surprise inclination had me researching #uniq and #compact
> to see if they took a block like #sort.
This is easy with #inject:
ar.inject([]) do |res, (x,y)|
if res.empty? || res.last[0] != x
res << [x,y]
else
res.last[1] = y
end
res
end
Cheers
robert
--
use.inject do |as, often| as.you_can - without end
|