Skip to content

Instantly share code, notes, and snippets.

@possen
Created November 8, 2015 21:09
Show Gist options
  • Save possen/2071e8499d06ec1f20e7 to your computer and use it in GitHub Desktop.
Save possen/2071e8499d06ec1f20e7 to your computer and use it in GitHub Desktop.
Silly Hat village CS problem where through deduction, the town saves its self from having to tell jokes for 100-1 years.
//
// Description Silly Hat village in Swift solution
//
// Author: Paul Ossenbruggen
// Date: Nov 8, 2015
// Language: Swift 2.1
// See comment below for problem statement.
//
import Foundation
//There is a village full of people. One day the mayor gathers all the villagers together and declares that their that some among the villagers are must wear a invisible to themselves silly hat. All hats are visible to each other but noone will know if there is a hat on their own head. Furthermore, the hat will not be visible in the mirror and one person is forbidden from telling another if they are wearing one. The villagers must work out which among them are wearing one at which point all hat wearers are to leave the village. The village has been given one week and if at the end of the week, there are still hat wearers present, the whole village will have to tell jokes every day until they are 99, with no break..
// Solution: Note that there is at least one hat wearer. Each day the villagers look at the number of
// villagers, if the first day they see that, there was no other hat wearers, they must assume that
// they are the hat wearer, so they will leave. If they see another hat wearer then they don't know, if on
// day two they see the same situation, then they have to assume that there were two hat wearers, and
// they both exit. On day three, if they see two others and they are still there, then they
// must be one of the three hat wearers, etc.
func sillyHatVillage(villagers : [Bool]) {
print("Silly Hat Village")
var hatWearerExist = true
var day = 0
while hatWearerExist {
print(day)
for index in 0..<villagers.count {
var allButVillager = villagers
allButVillager.removeAtIndex(index)
let hatWearers = allButVillager.reduce(0, combine: { $0 + ($1 ? 1 : 0) })
print(allButVillager, hatWearers)
if hatWearers == day {
print("hat weaerer exits")
hatWearerExist = false
}
}
day += 1
}
}
sillyHatVillage([true])
sillyHatVillage([false, true])
sillyHatVillage([true, true, true, false])
sillyHatVillage([true, false, false, false])
sillyHatVillage([true, true, false, true, false, true, false, false, false, true])
sillyHatVillage([true, true, true, true, true, true, true, true, true, true])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment