[英]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.