Created
May 9, 2015 14:56
-
-
Save lesiki/e3fd104f0574c0bbd7a6 to your computer and use it in GitHub Desktop.
Coding challenge
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
class AddsToAHundred { | |
/* | |
Challenge: Write a program that outputs all possibilities | |
to put + or - or nothing between the numbers 1, 2, ..., 9 (in this order) | |
such that the result is always 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100. | |
from https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour | |
*/ | |
public static void main(String [] args) { | |
explore([]) | |
} | |
static def explore(commandsSoFar) { | |
if(commandsSoFar.size() == 8) { | |
return testIfAHundred(commandsSoFar) | |
} | |
else { | |
explore(commandsSoFar + '') | |
explore(commandsSoFar + '+') | |
explore(commandsSoFar + '-') | |
} | |
} | |
static def testIfAHundred(list) { | |
def input = [] | |
def accumulator = 0 | |
8.times { | |
input << (it + 1) | |
input << list[it] | |
} | |
input << '9' | |
def command = input.join('') | |
command.split('\\+').each { addOperand -> | |
addOperand.split('-').eachWithIndex { subOperand, index -> | |
accumulator += ((index == 0) ? 1 : -1) * Integer.parseInt(subOperand) | |
} | |
} | |
if(accumulator == 100) { | |
println command | |
return true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment