Created
June 16, 2017 11:56
-
-
Save ssaurel/e6c8ba58701c54ffa60f1f6418916a25 to your computer and use it in GitHub Desktop.
CountdownMathGame Solver for a tutorial on the SSaurel's Channel
This file contains 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 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