Это может быть ресурсоемким, но вот мое решение
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Combinations {
public static void main(String[] args) {
List<Integer[]> finalPatternList = getCombinations(6, 10, 12);
}
static List<Integer[]> getCombinations(int n, int target, int max) {
/*
first generate all the combinations on the given n
*/
List<Integer[]> allCombinationsList = new ArrayList<>();
//generate the digits list
List<Integer> digitList = new ArrayList<Integer>();
for (int i = 0; i <= max; i++) {
digitList.add(i);
}
//generate the number system
int powerBase = digitList.size();
int maxPower = n ;
int totalCombinations = (int) Math.pow(powerBase, maxPower);
//generating default array
for (int i = 0; i < totalCombinations; i++) {
Integer pattern[] =new Integer[n];;
allCombinationsList.add(pattern);
}
//filling the Columns one by one
for (int i =n ; i >= 1 ; i -- ){
int currentColumn = i - 1;
int noOfIterations =(int) Math.pow(max + 1, n - i);
populateRows(allCombinationsList ,digitList ,currentColumn ,noOfIterations );
}
/*
example :
[0, 0, 0, 0]
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 1]
[0, 1, 0, 0]
[0, 1, 0, 1]
[0, 1, 1, 0]
[0, 1, 1, 1]
............
current row variable is the array index
if currentRow = 3,
pattern 1 - its 0
pattern 2 - its 1
pattern 3 - its 0
if currentRow = 2 ,
pattern 1 - its 0
pattern 2 - its 0
pattern 3 - its 1
iterations means the number of consecutive digits appear on each column
in column 1 - its 1
in column 2 - its 2
in column 3 - its 4
*/
/*
select the patterns that match the target
*/
List<Integer[]> finalPatternList = new ArrayList<>();
for (Integer[] currentArray : allCombinationsList){
int sum = 0 ;
for (int i =0 ; i < currentArray.length ; i++ ){
sum +=currentArray[i] ;
}
if (sum == target) finalPatternList.add(currentArray);
}
for (Integer a[] : finalPatternList) {
System.out.println(Arrays.toString(a));
}
return finalPatternList;
}
static void populateRows(List<Integer[]> combinationList, List<Integer> digitList, int currentColumn, int iterations) {
int combinationListPosition = 0;
while (combinationListPosition < combinationList.size()) {
int digitListPosition = 0;
while (digitListPosition < digitList.size()) {
int currentIteration = 0;
while (currentIteration < iterations) {
if (combinationListPosition == combinationList.size()){
// end the loop when all combinations are filled
System.out.println();
return;
}
combinationList.get(combinationListPosition)[currentColumn] = digitList.get(digitListPosition);
currentIteration++;
combinationListPosition ++ ;
}
digitListPosition ++ ;
}
}
}
}