Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package einsteinsriddle;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * @author ??? && Joel Brito
- */
- public class Permute2 {
- private static Object[] input;
- private static int outputIndex;
- private static List<List<Object>> output;
- public Permute2() {
- outputIndex = 0;
- }
- public List<List<Object>> getPermutation(Object[] input) {
- this.input = input;
- this.output = new ArrayList<>();
- permutations(0);
- return output;
- }
- private static void permutations(int offset) {
- if (input.length - offset == 1) {
- // Input now contains a permutation, here I store it in output,
- // but you can do anything you like with it
- List<Object> tmp = new ArrayList<>();
- for (Object o : input) {
- tmp.add(o);
- }
- output.add(tmp);
- return;
- }
- Object a = input[offset];
- for (int i = offset; i < input.length; i++) {
- // Swap elements
- Object b = input[i];
- input[i] = a;
- input[offset] = b;
- permutations(offset + 1);
- // Restore element
- input[i] = b;
- }
- input[offset] = a;
- }
- private static int factorial(int n) {
- return n == 1 ? n : n * factorial(n - 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement