Skip to content

Instantly share code, notes, and snippets.

@eranation
Last active August 29, 2015 14:20
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 eranation/c039ce9e22e04db18d14 to your computer and use it in GitHub Desktop.
Save eranation/c039ce9e22e04db18d14 to your computer and use it in GitHub Desktop.
Silly programming problem: add either +, - or nothing between 1 to 9, which combinations yields 100?
import javax.script.ScriptEngineManager
// I *could* write an evaluation engine by hand, since it's only + and - it would be dead easy, but... not this time...
val e = new ScriptEngineManager().getEngineByName("javascript")
val operators:Seq[String] = Seq("+","-","")
val choose1 = for {
c1 <- operators
c2 <- operators
c3 <- operators
c4 <- operators
c5 <- operators
c6 <- operators
c7 <- operators
c8 <- operators
stringRep = s"1${c1}2${c2}3${c3}4${c4}5${c5}6${c6}7${c7}8${c8}9"
result = e.eval(stringRep).asInstanceOf[Double].toInt
if result == 100
} yield {
stringRep
}
import javax.script.ScriptEngineManager
// I *could* write an evaluation engine by hand, since it's only + and - it would be dead easy, but... not this time...
val e = new ScriptEngineManager().getEngineByName("javascript")
val operators:Seq[String] = Seq("+","-","")
def operatorPermutations(position:Int):Seq[String] = {
if (position > 1) {
for {
curOp <- operators
choose1 = operatorPermutations(position-1)
choice<-choose1
strRes = choice + curOp + position.toString
} yield {
strRes
}
} else {
Seq("1")
}
}
for {
option <- operatorPermutations(9)
result = e.eval(option).asInstanceOf[Double].toInt
if result == 100
} yield {
option
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment