B
Bil Kleb
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_highest_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.
Thanks,
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_highest_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.
Thanks,