Skip to content

Instantly share code, notes, and snippets.

@Angeldude
Last active February 27, 2019 04:28
Show Gist options
  • Save Angeldude/83e0416719898adcb79509ea194f62bd to your computer and use it in GitHub Desktop.
Save Angeldude/83e0416719898adcb79509ea194f62bd to your computer and use it in GitHub Desktop.
Don's hash problem in ruby
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