Skip to content

Instantly share code, notes, and snippets.

@lesiki
Created May 9, 2015 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lesiki/e3fd104f0574c0bbd7a6 to your computer and use it in GitHub Desktop.
Save lesiki/e3fd104f0574c0bbd7a6 to your computer and use it in GitHub Desktop.
Coding challenge
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