Last active
October 9, 2018 23:43
-
-
Save keithrbennett/633b30516ea3095ae7ddff24755e8f14 to your computer and use it in GitHub Desktop.
A solution to including duplicates of some classes but not others
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
#!/usr/bin/env ruby | |
# A solution to the problem where one wants to create a new array | |
# that includes all instances of A and B but only the first instances | |
# of C & D. | |
require 'set' | |
class A; end | |
class B; end | |
class C; end | |
class D; end | |
def class_duplicates_ok?(klass) | |
[A, B].include?(klass) | |
end | |
def prune_array(array) | |
classes_found = Set.new | |
array.each_with_object([]) do |element, pruned_array| | |
klass = element.class | |
if class_duplicates_ok?(klass) || (! classes_found.include?(klass)) | |
pruned_array << element | |
end | |
classes_found << klass | |
end | |
end | |
def main | |
options = [A.new, B.new, A.new, B.new, C.new, C.new, D.new] | |
pruned = prune_array(options) | |
puts "\nOriginal: "; puts options | |
puts "\nPruned: "; puts pruned | |
end | |
main | |
=begin | |
Sample Output: | |
Original: | |
#<A:0x00007f8c81915130> | |
#<B:0x00007f8c81915108> | |
#<A:0x00007f8c819150e0> | |
#<B:0x00007f8c819150b8> | |
#<C:0x00007f8c81915018> | |
#<C:0x00007f8c81914ff0> | |
#<D:0x00007f8c81914f28> | |
Pruned: | |
#<A:0x00007f8c81915130> | |
#<B:0x00007f8c81915108> | |
#<A:0x00007f8c819150e0> | |
#<B:0x00007f8c819150b8> | |
#<C:0x00007f8c81915018> | |
#<D:0x00007f8c81914f28> | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment