public class Test {
private static Map<Integer, Integer> result = new HashMap<>();
private static ArrayList<Integer> remaining(final ArrayList<Integer> input, final int digit) {
ArrayList<Integer> remaining = new ArrayList<>(input);
remaining.remove(input.indexOf(digit));
return remaining;
}
private static Stack<Integer> getCandidates(final ArrayList<Integer> input, final int lower, final int higher) {
List<Integer> filtered = input.stream()
.filter(num -> num >= lower && num <= higher)
.sorted()
.collect(Collectors.toList());
Stack<Integer> result = new Stack<>();
result.addAll(filtered);
return result;
}
public static int findFirst(final ArrayList<Integer> input) {
Stack<Integer> candidates = getCandidates(input, 0, 2);
for (Integer candidate : candidates) {
final int next = findSecond(remaining(input, candidate));
if (next != -1) {
result.put(0, candidate);
return candidate;
}
}
return -1;
}
public static int findSecond(final ArrayList<Integer> input) {
Stack<Integer> candidates = getCandidates(input, 0, 9);
for (Integer candidate : candidates) {
final int next = findThird(remaining(input, candidate));
if (next != -1) {
result.put(1, candidate);
return candidate;
}
}
return -1;
}
public static int findThird(final ArrayList<Integer> input) {
Stack<Integer> candidates = getCandidates(input, 0, 5);
for (Integer candidate : candidates) {
final int next = findFourth(remaining(input, candidate));
if (next != -1) {
result.put(2, candidate);
return candidate;
}
}
return -1;
}
public static int findFourth(final ArrayList<Integer> input) {
Stack<Integer> candidates = getCandidates(input, 0, 9);
for (Integer candidate : candidates) {
final int next = findFifth(remaining(input, candidate));
if (next != -1) {
result.put(3, candidate);
return candidate;
}
}
return -1;
}
public static int findFifth(final ArrayList<Integer> input) {
Stack<Integer> candidates = getCandidates(input, 0, 5);
for (Integer candidate : candidates) {
final int next = findLast(remaining(input, candidate));
if (next != -1) {
result.put(4, candidate);
return candidate;
}
}
return -1;
}
public static int findLast(final ArrayList<Integer> input) {
Stack<Integer> candidates = getCandidates(input, 0, 9);
if (candidates.isEmpty()) {
return -1;
}
Integer last = candidates.peek();
result.put(5, last);
return last;
}
public static void main(String[] args) {
final ArrayList<Integer> input = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 6, 8));
findFirst(input);
System.out.println(result.values());
}
}