在Java中使用ArrayList开发自定义计数
我试图用自定义值填充一个给定的数组。例如,如果我的基数是在Java中使用ArrayList开发自定义计数,java,arrays,eclipse,Java,Arrays,Eclipse,我试图用自定义值填充一个给定的数组。例如,如果我的基数是[2,3,1],则数组应如下所示: 0,0,0 0,0,1 0,1,0 0,1,1 0,2,0 0,2,1 0,3,0 0,3,1 1,0,0 and so on... 当我到达[2,3,1]时,循环应该完成。我对我的代码做了几处修改,所以可能比以前更糟糕 max=0; while (!(power.containsAll(listPot))){ while ((index<=listPot.get(pos)))
[2,3,1]
,则数组应如下所示:
0,0,0
0,0,1
0,1,0
0,1,1
0,2,0
0,2,1
0,3,0
0,3,1
1,0,0 and so on...
当我到达[2,3,1]
时,循环应该完成。我对我的代码做了几处修改,所以可能比以前更糟糕
max=0;
while (!(power.containsAll(listPot))){
while ((index<=listPot.get(pos))){ //Iterating the first digit
power.set(pos, index); //Updating the value
index++; //Increasing up to the limit found on listPot
}
index=0; //Reset the counter to put into the Array
if(max<limit){ //max would be the position of the next digit
max++;
}
if(power.get(max)<listPot.get(pos)){ //If next digit is < limit
index++; //move the index forward
power.set(max, index); //Increase the next digit
while (pos>=0){ //Removing the previous digits, like from 199 to 200
power.set(pos, 0);
pos--;
}
index=0;
}
else { //I increase max position again and proceed like above
pos=max;
max++;
while (pos>=0){ //Removing previous digits
power.set(pos, 0);
pos--;
}
index++; //Increasing the value to input
power.set(max, index);
}
index=0; //Reset the counters
pos=0;
}
max=0;
而(!(power.containsAll(listPot))){
虽然((index我知道您希望将数组中的值增加到给定的限制,但有一些排列。我建议将问题划分为:
calculate(new int[] {2, 3, 1}); // example
private static void calculate(int[] limits) {
int counters[] = new int[limits.length];
do {
something(counters);
} while (increment(counters, limits));
}
private static void something(int[] counters) {
// do whatever should be done with the counters
System.out.println(Arrays.toString(counters));
}
private static boolean increment(int[] counters, int[] limits) {
// index for counter to increment, starting at the last one
for (int i = counters.length-1; i >= 0; i--) {
counters[i] += 1;
// if the counter is within the limits, return true
if (counters[i] <= limits[i])
return true;
// if counted past limit, reset to zero and continue
// with previous counter (loop)
counters[i] = 0;
}
// if the first counter exceeded the limit, we are done
return false;
}
calculate(新的int[]{2,3,1});//示例
专用静态无效计算(int[]限制){
int counters[]=新的int[limits.length];
做{
某物(计数器);
}while(增量(计数器、限制));
}
私有静态无效内容(int[]计数器){
//用计数器做该做的事
System.out.println(Arrays.toString(counters));
}
专用静态布尔增量(int[]计数器,int[]限制){
//从最后一个计数器开始的递增计数器索引
对于(int i=counters.length-1;i>=0;i--){
计数器[i]+=1;
//如果计数器在限制范围内,则返回true
if(counters)[i]你能告诉我们你想要实现什么吗?你的问题很难理解,那么,你的问题是什么?我不明白:你试图构建的数组是什么?你能在顶部添加问题陈述吗,这样我们就有机会知道该做什么吗?你正在尝试做类似于'if base==[2,3,1]的事情,然后返回[0,0,0,0,1 0,1,0,1,0,1,1,0,1,0,2,1 0,3,0,3,1,1,0,0]?当然不是!你不仅要解释结果,还要解释它的含义或应该如何存档。如果我只告诉你给定2和2,它应该得到4,你能写一个程序吗?你不可能知道我想要幂函数(2^2)不是加法,甚至不是乘法……太完美了。谢谢你的帮助。