Last active
August 29, 2015 14:02
-
-
Save seanhandley/e917653fb4bad3a5858b to your computer and use it in GitHub Desktop.
Given N sets, returns the set of all elements which occur in only one of those sets
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
TheHodge: anyone got any suggestions on how to compare | |
four arrays for unique elements | |
TheHodge: I want a count of the unique elements in each | |
array, elements that don't appear in any of the other | |
three | |
TheHodge: the four arrays could easily turn into 6 and | |
then 8 as they are files in a directory |
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
require 'set' | |
a = Set[1,2,3,4] | |
b = Set[2,3,4,5] | |
c = Set[3,4,5,6] | |
d = Set[4,5,6,7] | |
diff = a - (b | c | d) | |
puts diff.inspect # => #<Set: {1}> | |
diff = d - (b | c | a) | |
puts diff.inspect # => #<Set: {7}> | |
# What you need is the difference of given set A, against | |
# the Union of sets B, C and D | |
# This means you'll need to do some combinatorial stuff | |
all_sets = Set[a,b,c,d] | |
uniques = all_sets.collect do |s| | |
others = all_sets.dup.delete(s) | |
union = others.reduce(:|) | |
diff = union ? s - union : nil | |
diff | |
end.reduce(:|) | |
puts uniques.inspect # => #<Set: {1, 7}> | |
puts uniques.to_a.inspect # => [1, 7] |
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
require 'set' | |
require 'securerandom' | |
all_sets = Set[] | |
100.times do | |
s = Set[] | |
100.times do | |
s.add(SecureRandom.hex(2)) | |
end | |
all_sets.add(s) | |
end | |
uniques = all_sets.collect do |s| | |
others = all_sets.dup.delete(s) | |
union = others.reduce(:|) | |
diff = union ? s - union : nil | |
diff | |
end.reduce(:|) | |
uniques_count = uniques.to_a.count | |
puts "Generated #{uniques_count} unique hex strings across 100 sets (#{10_000 - uniques_count} were duplicated.)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment