Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Participant {
- let name: String
- weak var givesGiftTo: Participant?
- weak var pair: Participant?
- init(name: String, pair: Participant?) {
- self.name = name
- self.pair = pair
- pair?.pair = self
- }
- }
- extension NSMutableSet {
- func takeRandomParticipant(#thatIsNotParticipant: Participant?, forParticipant participant: Participant) -> Participant {
- let poolForParticipant = self.mutableCopy() as NSMutableSet
- poolForParticipant.removeObject(participant)
- if let thatIsNotParticipant = thatIsNotParticipant {
- poolForParticipant.removeObject(thatIsNotParticipant)
- }
- let index = arc4random_uniform(UInt32(poolForParticipant.count))
- let participant = poolForParticipant.allObjects[Int(index)] as Participant
- self.removeObject(participant)
- return participant
- }
- }
- class Pool {
- var participants: [Participant]
- let pool: NSMutableSet
- init(participants: [Participant]) {
- self.participants = participants
- self.pool = NSMutableSet(array: participants)
- for participant in participants {
- participant.givesGiftTo = self.pickForParticipant(participant)
- }
- }
- func pickForParticipant(participant: Participant) -> Participant {
- return pool.takeRandomParticipant(thatIsNotParticipant: participant.pair, forParticipant: participant)
- }
- func printResult() {
- for participant in self.participants {
- println("\(participant.name) dāvina dāvanu \(participant.givesGiftTo!.name)")
- }
- }
- }
- let janis = Participant(name: "Jānis", pair: nil)
- let liga = Participant(name: "Līga", pair: janis)
- let adams = Participant(name: "Ādams", pair: nil)
- let ieva = Participant(name: "Ieva", pair: adams)
- let juris = Participant(name: "Juris", pair: nil)
- let zane = Participant(name: "Zane", pair: juris)
- let andrejs = Participant(name: "Andrejs", pair: nil)
- let baiba = Participant(name: "Baiba", pair: nil)
- let andris = Participant(name: "Andris", pair: nil)
- let maija = Participant(name: "Maija", pair: nil)
- let marite = Participant(name: "Mārīte", pair: nil)
- let sandra = Participant(name: "Sandra", pair: nil)
- let maris = Participant(name: "Māris", pair: nil)
- let ruta = Participant(name: "Ruta", pair: nil)
- let emils = Participant(name: "Emīls", pair: nil)
- let pool = Pool(
- participants: [
- janis,
- liga,
- adams,
- ieva,
- juris,
- zane,
- andrejs,
- baiba,
- andris,
- maija,
- marite,
- sandra,
- maris,
- ruta,
- emils
- ]
- )
- pool.printResult()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement