1 回答
TA贡献1818条经验 获得超11个赞
我想出了这个解决方案,这有点笨拙,但可能适合你的情况,评论应该解释一切:
public static void printCombinations(int R, int N) {
// calculate the combinations
String[][] combinations = calculateCombinations(R, N);
// iterate over all
for (int i = 0; i < combinations.length; i++) {
// prints the commas at the end
if (i != 0) {
System.out.println(',');
}
// print to std out
System.out.print(Arrays.toString(combinations[i]));
}
System.out.println();
}
public static String[][] calculateCombinations(int R, int N) {
// calculate our limit
int limit = (int) StrictMath.pow(N, R);
// create the result array
String[][] result = new String[limit][R];
// iterate over all possibilities
for (int i = 0; i < limit; i++) {
// convert to base
String base = Long.toString(i, N);
// holds our temporary value
StringBuilder intermediate = new StringBuilder(R);
// pad the value from the start with zeroes if needed
for (int sub = R - base.length(); sub > 0; sub--) {
intermediate.append('0');
}
// append our number
intermediate.append(base);
// append to result
result[i] = intermediate.toString().split("");
}
// return the result
return result;
}
然后可以这样调用以漂亮地打印出来:
printCombinations(6, 2);
或者得到它的结果:
String[][] result = calculateCombinations(6, 2);
运行演示
添加回答
举报