This method helps in arranging any type of objects in given number of positions. It is brut-force method of getting all type of combinations.
Please leave comments below for more questions and remarks.
Results:
Input1:[ 'A','B','C','D'] & 2 positions
output1: [[A, A], [A, B], [A, C], [A, D], [B, A], [B, B], [B, C], [B, D], [C, A], [C, B], [C, C], [C, D], [D, A], [D, B], [D, C], [D, D]]
Input2: [1,2] & 4 positions
[[1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 2, 1], [1, 1, 2, 2], [1, 2, 1, 1], [1, 2, 1, 2], [1, 2, 2, 1], [1, 2, 2, 2], [2, 1, 1, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 1, 2, 2], [2, 2, 1, 1], [2, 2, 1, 2], [2, 2, 2, 1], [2, 2, 2, 2]]
Please leave comments below for more questions and remarks.
public class Solution { public static void main(String[] args) { List<Integer> a = Arrays.asList(1, 2); System.out.println(getArrangements(a, 4)); } public static <T> List<List<T>> getArrangements (List<T> numbers, int n) { List<List<T>> result = new ArrayList<List<T>>(); int itr = (int) Math.pow(n, numbers.size()); for (int i = 0; i < itr; i++) { List<T> comb = new ArrayList<T>(); for (int j = 0; j < n; j++) { int pos = (int) Math.pow(numbers.size(), (n - j - 1)); int element = (i / pos) % (numbers.size()); comb.add(numbers.get(element)); } result.add(comb); } return result; } }
Results:
Input1:[ 'A','B','C','D'] & 2 positions
output1: [[A, A], [A, B], [A, C], [A, D], [B, A], [B, B], [B, C], [B, D], [C, A], [C, B], [C, C], [C, D], [D, A], [D, B], [D, C], [D, D]]
Input2: [1,2] & 4 positions
No comments:
Post a Comment