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/9168772 to your computer and use it in GitHub Desktop.

Select an option

Save AndrewTweddle/9168772 to your computer and use it in GitHub Desktop.
A base class 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
abstract class JHMSolver(digits: String, total: Int, maxDigitsPerNumber: Int = 5)
{
def solve(digits: String, total: Int, maxDigitsPerNumber: Int = 5): List[List[Int]]
lazy val solutions = solve(digits, total, maxDigitsPerNumber)
def getSolutionsAsString(): String = solutions match {
case Nil => "IMPOSSIBLE"
case slns => slns map (
(solution: List[Int]) => s"${ solution mkString "+" }=$total"
) mkString "\n"
}
}
object JHMSolver {
def getDefaultSolver(digits: String, total: Int): JHMSolver
= new SolverUsingFlatMap(digits, total, maxDigitsPerNumber = 5)
def getSolutions(digits: String, total: Int): List[List[Int]] = {
getDefaultSolver(digits, total).solutions
}
def getSolutionsAsString(digits: String, total: Int): String = {
getDefaultSolver(digits, total).getSolutionsAsString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment