Skip to content

Instantly share code, notes, and snippets.

@Synesso
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Synesso/b05770e19e223d63a875 to your computer and use it in GitHub Desktop.
Save Synesso/b05770e19e223d63a875 to your computer and use it in GitHub Desktop.
package com.github.synesso.cheryl
object Main extends App {
val possibleAnswers = Set(
May(15), May(16), May(19),
Jun(17), Jun(18),
Jul(14), Jul(16),
Aug(14), Aug(15), Aug(17)
)
// the month does not include a date that would give the answer
val monthDoesNotContainUniqueDate = {
val datesThatGiveTheAnswer = singletonsFrom(mapByDom(possibleAnswers))
mapByMonth(possibleAnswers).filter { case (k, v) => !v.exists(datesThatGiveTheAnswer.contains) }.values.toSet.flatten
}
// days-of-month that give a unique value in the remaining possible answers
val uniqueByDom = singletonsFrom(mapByDom(monthDoesNotContainUniqueDate))
// months that give a unique value in the remaining possible answers
val uniqueByMonth = singletonsFrom(mapByMonth(uniqueByDom))
println(s"Cheryl's birthday is ${uniqueByMonth.head}")
def mapByMonth(days: Set[Day]) = days.foldLeft(Map.empty[String, Set[Day]].withDefaultValue(Set.empty)) { case (m, d) =>
m.updated(d.month, m(d.month) + d)
}
def mapByDom(days: Set[Day]) = days.foldLeft(Map.empty[Int, Set[Day]].withDefaultValue(Set.empty)) { case (m, d) =>
m.updated(d.dom, m(d.dom) + d)
}
def singletonsFrom(m: Map[_, Set[Day]]) = m.filter{case (_,v) => isSingleton(v)}.values.flatten.toSet
def isSingleton(set: Set[_]) = set.size == 1
}
case class Day(dom: Int, month: String)
object May { def apply(d: Int) = Day(d, "May") }
object Jun { def apply(d: Int) = Day(d, "Jun") }
object Jul { def apply(d: Int) = Day(d, "Jul") }
object Aug { def apply(d: Int) = Day(d, "Aug") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment