Last active
August 29, 2015 13:56
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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