Skip to content

Instantly share code, notes, and snippets.

@kevbuchanan
Last active December 17, 2015 23:49
Show Gist options
  • Select an option

  • Save kevbuchanan/5692042 to your computer and use it in GitHub Desktop.

Select an option

Save kevbuchanan/5692042 to your computer and use it in GitHub Desktop.
From Best of Ruby Quiz by James Edward Gray II.
# Randomly assigns secret santas. Will not match up two people with the same last name.
class SecretSanta
attr_accessor :names
def initialize(names_array)
@names = names_array.map { |name| name.split(' ') }
raise "Odd number of names!" if @names.size.odd?
@assignments = {}
end
def run
name_check
assign
display
save
end
private
def name_check
last_name_count = {}
last_names = @names.map { |name| name[1] }
last_names.each { |name| last_name_count[name] ? last_name_count[name] += 1 : last_name_count[name] = 1 }
raise "Incompatible last name count!" if last_name_count.values.any? { |x| x > last_names.size / 2 }
end
def assign
santas = @names.shuffle
@names.each do |name|
santas.shuffle! until santas[-1][1] != name[1]
assignment = santas.pop
@assignments[name.join(" ")] = assignment.join(" ")
end
end
def display
@assignments.each { |name, assignment| puts "#{name} --> #{assignment}" }
end
def save
File.open "secret_santa.txt", 'w' do |f|
f.write "Name --> Assignment \n"
@assignments.each { |name, assignment| f.write "#{name} --> #{assignment}" + "\n" }
end
puts "Secret santa list saved as secret_santa.txt"
end
end
names = []
while true
name = gets.chomp
break if name == ''
names << name
end
list1 = SecretSanta.new(names)
list1.run
@kevbuchanan
Copy link
Copy Markdown
Author

The assign function will occasionally go into an endless loop if the shuffle works out such that the only remaining names have the same last name. I need to figure out how to fix this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment