[英]Find all combinations in an array
我正在使用Java在Android Studio中开发游戏,但是对计算分数的方法有一些麻烦。 基本上在游戏中,我有一个骰子数组,其值从1到6。在这些值中,我需要找出一个特殊值出现多少次。
现在,我有一种方法可以使其很好地用于查找所有单个值(例如,所有具有值5的骰子),以及是否两个骰子加起来等于特殊值(例如2 + 3或1 + 4)。 但是当有两个以上的骰子加起来时,它找不到特殊值(例如1 + 1 + 3)
示例:如果我的骰子具有[1、2、2、2、3、5]值,则结果应为三个“ numberOfPairs”(1 + 2 + 2、2 + 3、5),因此该方法应返回15 ,但对我来说只返回10。
我真的很感谢一些想法,建议如何更改此方法以更好地工作。
这是我现在正在研究的方法:
public static int evaluatePoints(Dice dices[], int sumToReach) {
int values[] = new int[dices.length];
int numberOfPairs = 0;
int left = 0;
int right = values.length - 1;
for(int i = 0; i < dices.length; i++){
values[i] = dices[i].getValue();
if(values[i] == sumToReach){
numberOfPairs++;
values[i] = 0;
}
}
Arrays.sort(values);
while (values[right] > sumToReach + values[0]) {
right--;
}
while (left < right) {
if (values[left] + values[right] == sumToReach) {
numberOfPairs++;
left++;
right--;
}
else if(values[left] + values[right] < sumToReach) {
left++;
}
else right--;
}
return numberOfPairs*sumToReach;
}
您的问题可以解释为“获取所有可能的数字表示形式以及其他自然数的和”。 这是很好的解决方案。
算法说明:
Suppose the input array is [1 2 2 2 3 5]
First the program will search for grpSize 6 i.e. 6 elements that sum upto sum of 5
Then the program will search for grpSize 5 i.e. 5 elements that sum upto sum of 5
.
.
.
then the program will search for grpSize 1 i.e. 1 element that sums upto sum of 5
If a set is found then elements will be removed from the resultList
Warning: This approach is recursive, may lead to stack overflow if number of dice increases manyfold
public static boolean func(int grpSize,int sum,int index,List<Integer> resultList,ArrayList<Integer> values) {
if(grpSize==1) {
int j;
for(j = index; j < resultList.size(); j++) {
if(resultList.get(j) == sum) {
values.add(resultList.get(j));
resultList.remove(j);
return true;
}
}
}
for(; index < resultList.size(); index++) {
if(func(grpSize-1, sum-resultList.get(index), index+1, resultList, values)) {
values.add(resultList.get(index));
resultList.remove(index);
return true;
}
}
return false;
}
public static void main(String[] args) {
List<Integer> resultList = new ArrayList<>();
ArrayList<ArrayList<Integer>> values = new ArrayList<>();
resultList.add(1);
resultList.add(2);
resultList.add(2);
resultList.add(2);
resultList.add(3);
resultList.add(5);
//3 2 2 2 3 5
int sum = 5;
int n = resultList.size();
for(int i = 0; i < n; i++) {
int k=i;
while(true) {
values.add(new ArrayList<>());
func(n-i, sum, 0, resultList, values.get(values.size() - 1));
if(values.get(k).isEmpty()) {
break;
} else {
k++;
}
}
}
values.removeIf(p -> p.isEmpty());
System.out.println("Number of pairs: "+values.size());
values.forEach((it) -> {
System.out.println(it);
});
int temp = 0;
for(int i = 0; i < values.size(); i++) {
for(int j = 0; j < values.get(i).size(); j++) {
temp += values.get(i).get(j);
}
}
System.out.println("sum: "+temp);
}
}
递归函数的工作:
此功能需要
这是布尔函数,如果发现一个特定的集合加起来等于THE SUM,它将返回true。 这个概念就是基本的回溯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.