Skip to content

Instantly share code, notes, and snippets.

@austra
Last active January 5, 2018 19:15
Show Gist options
  • Save austra/43185b650c74c934a5c6d19cc9fcde7c to your computer and use it in GitHub Desktop.
Save austra/43185b650c74c934a5c6d19cc9fcde7c to your computer and use it in GitHub Desktop.
Odd Occurrences In Array
Now that I found this... Lets do the next one.
https://codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/
a = [9,3,9,3,9,7,9]
a.group_by(&:itself).inject(0){|hash, (k,v)| v.first if v.size.odd?}
# Could also use transform_values instead of inject on Ruby 2.4
Turns out this one is easy with XOR exlusive or operator ^.
a.inject(:^)
Which does:
9.to_s(2) #1001 #9
(9^0).to_s(2) #1001 #9
3.to_s(2) # 111 #3
(9^3).to_s(2) #1010 #10
9.to_s(2) #1001 #9
(10^9).to_s(2) # 11 #3
3.to_s(2) # 111 #3
(10^3).to_s(2) #1001 #9
9.to_s(2) #1001 #9
(9^9).to_s(2) # 0 #0
7.to_s(2) # 111 #7
(9^7).to_s(2) #1110 #14
9.to_s(2) #1001 #9
(14^9).to_s(2) # 111 #7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment