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

Select an option

Save AndrewTweddle/9177389 to your computer and use it in GitHub Desktop.
A solver using Scala's for-yield syntax 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 SolverUsingFor( 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]] = for {
leftCount <- (1 to maxDigitsPerNumber).toList
if leftCount <= digits.length
(leftStr, rightStr) = digits.splitAt(leftCount)
if (leftCount == 1 || leftStr(0) != '0') // No numbers may start with '0' (except zero)
left = leftStr.toInt
if (left < total && rightStr != "") || (left == total && rightStr.replace("0","") == "")
// Still going, or reached the target sub-total with no remaining text to match except maybe zeroes
solution <- if (left == total && rightStr == "") List(List(left))
else solve(rightStr, total - left) map (left :: _)
} yield solution
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment