Skip to content

Instantly share code, notes, and snippets.

@AndrewTweddle
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save AndrewTweddle/9176739 to your computer and use it in GitHub Desktop.

Select an option

Save AndrewTweddle/9176739 to your computer and use it in GitHub Desktop.
A solver using Scala's flatmap to solve the Johnny Hates Math problem found at http://www.spoj.com/problems/ANARC07J/ (NB: this is to find all solutions to the problem, not to satisfy the SPOJ IO specification)
package jhm
case class SolverUsingFlatMap( digits: String, total: Int, maxDigitsPerNumber: Int = 5
) extends JHMSolver(digits, total, maxDigitsPerNumber) {
override def solve(digits: String, total: Int, maxDigitsPerNumber: Int = 5): List[List[Int]] = {
def getSolutionsForNextNumber(leftCount: Int): List[List[Int]] = {
val (leftStr, rightStr) = digits.splitAt(leftCount)
if (leftCount > 1 && leftStr(0) == '0') List.empty // Disallow numbers starting with zero
else {
val left: Int = leftStr.toInt
val remTotal: Int = total - left
if (remTotal < 0) List.empty // Exceeded target
else {
if (rightStr == "") {
if (remTotal == 0) List(List(left)) // Reached target exactly
else List.empty // Digits ran out before reaching target
}
else {
// Recursively solve the smaller problem:
val subNumbers = solve(rightStr, remTotal)
subNumbers map (left :: _)
}
}
}
}
val solutions = (
(1 to math.min(maxDigitsPerNumber, digits.length)).toList
flatMap getSolutionsForNextNumber
)
solutions
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment