Last active
June 19, 2019 20:12
-
-
Save jubishop/8299b2357b07498fe8d5acf8f9c1637b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test/unit' | |
def minByColumn(data, column_name, multiple = false) | |
found_rows = [] | |
data.each { |row| | |
next unless row.has_key?(column_name) | |
if (found_rows.empty? or row[column_name] < found_rows.first[column_name]) | |
found_rows = [row] | |
elsif (row[column_name] == found_rows.first[column_name]) | |
found_rows.push(row) | |
end | |
} | |
return multiple ? found_rows : found_rows.first | |
end | |
def minByColumns(data, column_names, multiple = false) | |
found_rows = minByColumn(data, column_names.shift, true) | |
until (found_rows.length == 1 or column_names.empty?) | |
new_found_rows = minByColumn(found_rows, column_names.shift, true) | |
found_rows = new_found_rows unless new_found_rows.empty? | |
end | |
return multiple ? found_rows : found_rows.first | |
end | |
class MinByColumnTest < Test::Unit::TestCase | |
def setup | |
@simple_data = [ | |
{'a' => 0, 'b' => 1}, | |
{'a' => 14, 'b' => -1} | |
] | |
@mixed_data = [ | |
{'a' => 0, 'b' => 11}, | |
{'a' => 14, 'b' => 34}, | |
{'a' => -1}, | |
{'b' => 3} | |
] | |
@multi_data = [ | |
{'a' => 0, 'b' => 2}, | |
{'a' => 0, 'b' => 4} | |
] | |
@dupe_data = [ | |
{'a' => 0, 'b' => 2}, | |
{'a' => 0, 'b' => 4}, | |
{'a' => 0, 'b' => 2} | |
] | |
end | |
def testMinByColumn | |
assert_equal(minByColumn(@simple_data, 'a'), {'a' => 0, 'b' => 1}) | |
assert_equal(minByColumn(@simple_data, 'b'), {'a' => 14, 'b' => -1}) | |
assert_nil(minByColumn(@simple_data, 'c')) | |
assert_equal(minByColumn(@mixed_data, 'a'), {'a' => -1}) | |
assert_equal(minByColumn(@mixed_data, 'b'), {'b' => 3}) | |
assert_nil(minByColumn([], 'b')) | |
end | |
def testMynByColumns | |
assert_equal(minByColumns(@multi_data, ['a', 'b']), {'a' => 0, 'b' => 2}) | |
assert_equal(minByColumns(@multi_data, ['a', 'c', 'b']), {'a' => 0, 'b' => 2}) | |
assert_nil(minByColumns(@multi_data, ['c'])) | |
assert_equal(minByColumns(@dupe_data, ['a', 'b']), {'a' => 0, 'b' => 2}) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment