【发布时间】:2012-01-06 05:19:59
【问题描述】:
我是 Java 新手。我正在编写一个 Android 游戏,我需要生成一个 int 数组数组,其中包含所有可能的和(不包括包含数字 2 或大于 8 个数字的组合),它们加起来为给定的数字。
例如:
ganeratePatterns(5) 必须返回数组
[patternNumber][summandNumber] = value
[0][0] = 5
[1][0] = 1
[1][1] = 1
[1][2] = 1
[1][3] = 1
[1][4] = 1
[2][0] = 3
[2][1] = 1
[2][2] = 1
[3][0] = 4
[3][1] = 1
我已经尝试像那里那样Getting all possible sums that add up to a given number 但我很难做到这样http://introcs.cs.princeton.edu/java/23recursion/Partition.java.html
解决方案
int n = 10;
int dimension = 0;
//First we need to count number of posible combinations to create a 2dimensionarray
for(List<Integer> sumt : new SumIterator(n)) {
if(!sumt.contains(2) && sumt.size() < 9) {
dimension++;
}
}
int[][] combinationPattern = new int[dimension][];
int foo = 0;
for(List<Integer> sum : new SumIterator(n)) {
if(!sum.contains(2) && sum.size() < 9) {
System.out.println(sum);
combinationPattern[foo] = toIntArray(sum);
foo++;
}
}
它的工作不是 100% 正确,而且非常漂亮,但对于我的游戏来说已经足够了
我在这里使用了 SumIterator 类 SumIterator.class
我必须将此代码 for(int j = n-1; j > n/2; j--) { 更改为此 for(int j = n-1; j >= n/2; j--) {,因为旧版本不会返回所有组合(如 10 的 [5,5])
而且我使用了 toIntArray 函数。我在 StackOverflow 上创建了 hare,但忘记了链接,所以这里是来源:
public static int[] toIntArray(final Collection<Integer> data){
int[] result;
// null result for null input
if(data == null){
result = null;
// empty array for empty collection
} else if(data.isEmpty()){
result = new int[0];
} else{
final Collection<Integer> effective;
// if data contains null make defensive copy
// and remove null values
if(data.contains(null)){
effective = new ArrayList<Integer>(data);
while(effective.remove(null)){}
// otherwise use original collection
}else{
effective = data;
}
result = new int[effective.size()];
int offset = 0;
// store values
for(final Integer i : effective){
result[offset++] = i.intValue();
}
}
return result;
}
【问题讨论】:
-
如果我可以问一下,您觉得在哪方面比较困难?看来您必须更新数组,而不是打印。
-
因为我是 Java 递归的新手,所以对我来说是火箭科学:) 而且我无法从所有可能的模式中计算出数字来初始化数组 (int[?][] = value)
-
抱歉,当我试图理解您需要实现的算法时,我的脑袋几乎要爆炸了。你能改写它的定义吗?编辑:没关系,终于明白了。
标签: java algorithm math multidimensional-array partition-problem