Skip to content

Instantly share code, notes, and snippets.

@aneveux
Created April 2, 2013 12:53
Show Gist options
  • Save aneveux/5291990 to your computer and use it in GitHub Desktop.
Save aneveux/5291990 to your computer and use it in GitHub Desktop.
Simple Java code written during a Live Coding session (~30min.) solving the "Compte est bon" game, which aims at finding all the operations to apply to a list of numbers to get an expected result. Warning: this source code is not optimized, and could be better, but the goal was to write it quickly in some kind of competition ;)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class LCEB {
public List<String> resolve(final List<Integer> numbers,
final Integer expected) {
return getSolutions(expected, numbers, null, null);
}
protected List<String> getSolutions(final Integer expected,
final List<Integer> numbers, final Integer result,
final String operation) {
final List<String> results = new ArrayList<String>();
if (expected.equals(result))
results.add(operation);
else {
final Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
final Integer selected = iterator.next();
final List<Integer> rest = new ArrayList<Integer>(numbers);
rest.remove(selected);
if (result == null)
results.addAll(getSolutions(expected, rest, selected,
selected.toString()));
else {
results.addAll(getSolutions(expected, rest, result
+ selected,
"(" + operation + " + " + selected.toString() + ")"));
results.addAll(getSolutions(expected, rest, result
- selected,
"(" + operation + " - " + selected.toString() + ")"));
results.addAll(getSolutions(expected, rest, result
* selected,
"(" + operation + " * " + selected.toString() + ")"));
if (result % selected == 0)
results.addAll(getSolutions(expected, rest, result
/ selected,
"(" + operation + " / " + selected.toString()
+ ")"));
}
}
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment