Skip to content

Instantly share code, notes, and snippets.

@stphung
Created May 10, 2011 05:22
Show Gist options
  • Select an option

  • Save stphung/963932 to your computer and use it in GitHub Desktop.

Select an option

Save stphung/963932 to your computer and use it in GitHub Desktop.
Google Code Jam 2011 Qualifier Round - Problem B, Magicka
object Magicka {
def invokeElements(spells: String, combines: List[String], oppositions: List[String]) = {
val oppositionSets = oppositions.map(_.toSet)
val combineMap = combines.map(c => (Set(c.charAt(0),c.charAt(1)), c.charAt(2))).toMap
spells.map(List(_)).foldLeft(List[Char]())((acc,spell) => {
acc.size match {
case 0 => spell
case _ => {
// Lazily compute the set which represents spells in the accumulator that clash with the current spell.
lazy val clashes = oppositionSets.filter(_.contains(spell.head)).map(_.diff(Set(spell.head))).flatten
val combination = Set(acc.last,spell.head)
if (combineMap.contains(combination)) acc.dropRight(1) ::: List(combineMap(combination))
else if (clashes.intersect(acc).size != 0) List[Char]()
else acc ::: spell
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment