Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created June 16, 2017 11: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 ssaurel/e6c8ba58701c54ffa60f1f6418916a25 to your computer and use it in GitHub Desktop.
Save ssaurel/e6c8ba58701c54ffa60f1f6418916a25 to your computer and use it in GitHub Desktop.
CountdownMathGame Solver for a tutorial on the SSaurel's Channel
package com.ssaurel.countdowngame;
import java.util.ArrayList;
public class CountdownGame {
private static final Operation[] OPERATIONS = { new Add(),
new Subtract(),
new Multiply(),
new Divide() };
private ArrayList<String> solution = new ArrayList<>();
public boolean findSolution(int[] t, int nb, int total) {
for (int i = 0; i < nb; i++) {
if (t[i] == total) {
return true;
}
for (int j = i + 1; j < nb; j++) {
for (int k = 0; k < OPERATIONS.length; k++) {
int res = OPERATIONS[k].eval(t[i], t[j]);
if (res != 0) {
int savei = t[i], savej = t[j];
t[i] = res;
t[j] = t[nb-1];
if (findSolution(t, nb- 1, total)) {
solution.add(Math.max(savei, savej) + " " +
OPERATIONS[k].symbol() + " " +
Math.min(savei, savej) + " = " + res);
return true;
}
t[i] = savei;
t[j] = savej;
}
}
}
}
return false;
}
public void printSolution() {
for (int i = solution.size() - 1; i >= 0; i--) {
System.out.println(solution.get(i));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment