Created
September 1, 2016 10:33
-
-
Save realsonic/98070cfb62db23b8539f4affb095f5b2 to your computer and use it in GitHub Desktop.
One puzzle solution
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 org.toysoft; | |
import java.util.*; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.stream.Collectors; | |
public class Main { | |
/** | |
* Условия: | |
* XX * XX - X = XXX | |
* 01 23 4 567 | |
* Кортеж: 1 1 1 1 2 3 3 4 | |
*/ | |
public static void main(String[] args) { | |
List<Integer> tuple = new ArrayList<>(Arrays.asList(1, 1, 1, 1, 2, 3, 3, 4)); | |
List<List<Integer>> allVariants = pickAllVariants(tuple); | |
AtomicInteger inc = new AtomicInteger(0); | |
allVariants.stream().map(integers -> { | |
inc.incrementAndGet(); | |
return integers; | |
}).filter(Main::check).forEach(integers -> System.out.println(inc.get() + ": " + showExp(integers) + " -> right!")); | |
System.out.println("Checked " + allVariants.size() + " variants."); | |
} | |
private static String showExp(List<Integer> tuple) { | |
return String.format("%d%d * %d%d - %d = %d%d%d", tuple.toArray()); | |
} | |
private static boolean check(List<Integer> tuple) { | |
int firstNumber = tuple.get(0) * 10 + tuple.get(1); | |
int secondNumber = tuple.get(2) * 10 + tuple.get(3); | |
int thirdNumber = tuple.get(4); | |
int resultNumber = tuple.get(5) * 100 + tuple.get(6) * 10 + tuple.get(7); | |
int leftPart = firstNumber * secondNumber - thirdNumber; | |
return leftPart == resultNumber; | |
} | |
private static List<List<Integer>> pickAllVariants(List<Integer> tuple) { | |
if (tuple.size() == 1) { | |
return new ArrayList<>(Collections.singletonList(tuple)); | |
} | |
List<List<Integer>> results = new ArrayList<>(); | |
for (int i = 0; i < tuple.size(); i++) { | |
Integer digit = tuple.get(i); | |
List<Integer> subTuple = new ArrayList<>(tuple); | |
subTuple.remove(digit); | |
List<List<Integer>> allVariants = pickAllVariants(subTuple); | |
allVariants.stream().forEach(integers -> integers.add(0, digit)); | |
results.addAll(allVariants); | |
} | |
return results.stream().distinct().collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment