【问题标题】:Moving array in javajava中的移动数组
【发布时间】:2021-11-24 08:38:27
【问题描述】:

所以我有一个连续开始的 k 个元素的数组,例如 0 1 2

我试图让它上升到某个值,比如 4,最终得到

  • 0 1 2
  • 0 1 3
  • 0 1 4
  • 0 2 3
  • 0 2 4
  • 0 3 4

我理解每次数组中的最后一个元素达到最大值时,它必须增加前一个索引并将当前索引设置为前一个索引的值+1,如果前一个索引的值达到少1的最大值,我们重复上一个索引的步骤,依此类推

但我不确定如何处理它以使其适用于任何 k 元素数组。

非常感谢任何提示或建议!

更新:我尝试创建一个递归移动索引并尝试添加的方法。它有效,但我认为它不是很有效:/

public static int[] nextCombi(int[] arr, int index, int maxVal){
    if (index < 0 || maxVal < 0){
        return arr;
    }
    else{
        if (arr[index] + 1 == maxVal){
            if (index - 1 >= 0){
                nextCombi(arr, index - 1, maxVal - 1);
                arr[index] = arr[index - 1] + 1;
            }
            else{
                arr[index]++;
                return arr;
            }
        }

        else{
            // Can add
            arr[index]++;
        }
    }
    return arr;
}

主要

while (true){
    arr = nextCombi(arr, max, n);
    if (arr[0] > max)
        break;
}

【问题讨论】:

  • 到目前为止你有什么代码?你能让它适用于固定长度的数组吗? IE。长度=3?
  • 我需要动态的,因此很头疼 ;-;

标签: java dynamic


【解决方案1】:

我认为你应该从列表的末尾开始,并升级它直到它没有达到最大值,然后从列表中的第一项开始。

这是一个例子:

List<Integer> ints = new ArrayList<>(); // create the list
ints.addAll(Arrays.asList(0, 1, 3)); // add element in it:
int max = 4; // indicate max value
int maxOfLast = Integer.MAX_VALUE; // start with max value to be sure of not reached max
for(int currentIndex = ints.size() - 1; currentIndex >= 0; currentIndex--) {
    int current = 0;
    while((current = ints.get(currentIndex)) < max && (current + 1) < maxOfLast) { // until it's not the end or reach max of index + 1 value
        ints.set(currentIndex, ++current); // upgrade it
        System.out.println(ints); // print (see output)
    }
    maxOfLast = ints.get(currentIndex); // set current value as max for next interation
}

输出:

[0, 1, 4]
[0, 2, 4]
[0, 3, 4]
[1, 3, 4]
[2, 3, 4]

【讨论】:

  • 能不能做到没有重复的数字?
  • “没有重复的数字”是什么意思?比如保持 1/2/3/4 而不是 4/4/4/4 ?
  • 刚刚用我的工作尝试更新了这个问题,但我觉得效率不高
  • 我也只是更新了我的答案。它现在回答了吗?
  • 天哪,是的!没错,需要一点时间来消化它是如何工作的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-19
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
相关资源
最近更新 更多