Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanhandley/e917653fb4bad3a5858b to your computer and use it in GitHub Desktop.
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
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
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]
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