Last active
February 27, 2019 04:28
-
-
Save Angeldude/83e0416719898adcb79509ea194f62bd to your computer and use it in GitHub Desktop.
Don's hash problem in ruby
This file contains 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
some_array_of_hashes = [ | |
{a: 1, b: 1, c: 1, d: 2, e: 4}, | |
{a: 1, b: 1, c: 1, d: 5, e: 1}, | |
{a: 1, b: 1, c: 1, d: 7, e: 8}, | |
{a: 1, b: 1, c: 1, d: 9, e: 6}, | |
{a: 1, b: 1, c: 2, d: 2, e: 3}, | |
{a: 1, b: 1, c: 3, d: 2, e: 3}, | |
{a: 1, b: 1, c: 4, d: 2, e: 3}, | |
] | |
# first, a one liner | |
some_array_of_hashes.uniq {|x| [ x[:a], x[:b], x[:c] ]} | |
#now recursively | |
def remove_duplicates array_of_hashes | |
if array_of_hashes.empty? | |
[] | |
else | |
remove_duplicates_helper array_of_hashes, array_of_hashes[0], [array_of_hashes[0]] | |
end | |
end | |
def remove_duplicates_helper hashed, comp, acc | |
temp = {a: comp[:a], b: comp[:b], c: comp[:c]} | |
if hashed.empty? | |
return acc | |
end | |
temp2 = {a: hashed[0][:a], b: hashed[0][:b], c: hashed[0][:c]} | |
if temp == temp2 | |
remove_duplicates_helper(hashed[1..-1], comp, acc) | |
else | |
remove_duplicates_helper(hashed[1..-1], hashed[0], acc + [hashed[0]]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment