问题陈述如下: 有一个人名单,每个人都有名字和姓氏。姓氏相同的人属于同一个家庭。 目的是为每个人选择一个秘密的圣诞老人,使得秘密的圣诞老人不是同一个人,也不属于同一个家庭。 如果别无选择,我可以自由地从同一个家庭中分配圣诞老人。
我有以下代码来实现这一目标并且正在通过我的测试 - 但是我对这段代码在所有情况下都能产生正确结果并不十分有信心。
如果算法不正确,我会感谢有人能解释为什么这个算法失败了,同时审查代码会很有帮助。
代码中的主要方法是assign_angels,我试图在East Oriented Code
之后的大多数方法中返回self我使用均衡器模块进行等式检查Equalizer
require 'set'
require 'equalizer'
class People
include Equalizer.new(:people)
def initialize personList = []
@people = Array(personList).to_set
end
def add person
@people.add person
self
end
def assign_angels
@people.each do |person|
eligible_santas
.preferably_of_different_family(person)
.assign_angel_to_one(person)
end
self
end
def to_s
@people.map { |person| person.to_s }
end
protected
def sample
@people.to_a.sample || NilPerson.new
end
def size
@people.size
end
def assign_angel_to_one person
sample.assign_angel person
self
end
def eligible_santas
People.new @people.select { |person| person.angel == nil }
end
def preferably_of_different_family person_a
different_family = people_of_different_family person_a
if different_family.size == 0
same_family = people_of_same_family person_a
if(same_family.size == 0)
return People.new NilPerson.new
end
return same_family
end
return different_family
end
def people_of_different_family person_a
People.new @people.select { |person| person unless person.is_family? person_a }
end
def people_of_same_family person_a
People.new @people.select { |person| person unless person == person_a }
end
attr_reader :people
end