【求助】关于数组取值问题
求各位大神帮忙提供个思路,有代码更好,小弟万分感谢~需求:
有一个数组,其内值如:其内仅有1和2两个数,
我想从数组取出和等于4的所有组合,并打印输出,将不能组合为和4的所有数据选择出来,放到一个数组中返回
这个需求该怎么做呀?一直没想出来。。。 不明白楼主意思。2+1+1=4,2+2=4,1+1+1+1=4,你的数据基本都能加到4啊。 /**
*
*/
package demo;
import java.util.ArrayList;
/**
* @author renxiao2003
*
*/
public class Demo {
private static int[] arr = { 1, 2, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, 2, 2 };
private static int sum = 4;
private static ArrayList<ArrayInfo> oldValueInfos = new ArrayList<ArrayInfo>();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < arr.length; i++) {
int next = i + 1;
int temp = arr + arr;
while (true) {
if (temp == sum) {
i = next;
break;
} else if (temp < sum) {
next = next + 1;
temp = temp + arr;
} else {
for (int j = i; j < (next + 1); j++) {
ArrayInfo arrayInfo = new ArrayInfo();
arrayInfo.setOldPosition(j);
arrayInfo.setValue(arr);
oldValueInfos.add(arrayInfo);
}
i = next;
break;
}
}
}
System.out.println("数组下标从0开始输出");
for (ArrayInfo arrayInfo : oldValueInfos) {
System.out.println("Position = " + arrayInfo.getOldPosition()
+ ";Value = " + arrayInfo.getValue());
}
}
}
class ArrayInfo {
private int oldPosition;
private int value;
public int getOldPosition() {
return oldPosition;
}
public void setOldPosition(int oldPosition) {
this.oldPosition = oldPosition;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
看看是你想要的不。
页:
[1]