I am buidling an app called Thirty Throws in Android and I am completely stuck with my validation. In Thirty Throws you have the scores 4, 5, 6 ,7, 8, 9, 10, 11, 12 and 6 dice. Each turn consists of 3 throws and the user can choose the dice he wish to keep between every throw. Example say that the user has thrown 4,4,3,5,1,5 then he can choose the score 11 because 4 + 4 +3 = 11 and 5 + 1 + 5 = 11 or if the user has thrown 2,2,2 he can choose 6.
I'm struggling with validating the score. The code I have at the moment manage to validate most. What am I missing?
I've been looking at some recursive solution here but they seem no to be what I am looking for since I have to return a boolean.
public static boolean isValidResult(ArrayList<Integer> score, int selectedPoints)
{
ArrayList<Integer> notReadyNumbers = new ArrayList<>();
for (int i: score) {
if (i == selectedPoints) {
continue;
}
if (CalcSum(notReadyNumbers) + i == selectedPoints) {
notReadyNumbers.clear();
} else {
boolean isDone = false;
if (notReadyNumbers.size() > 0) {
for (int z: notReadyNumbers) {
if (z + i == selectedPoints) {
isDone = true;
}
}
}
if (isDone) {
notReadyNumbers.clear();
} else {
notReadyNumbers.add(i);
}
}
}
return notReadyNumbers.size() == 0 ? true : false;
}
You should take all possible numbers from any position. So in order to take all possible result you may use permutation of these numbers to serialise the numbers. Another way is to use bit-masking with recursion. Here is a solution of your problem. (Based on bit-masking and recursion).
public static boolean isValidResult(ArrayList<Integer> score, int selectedPoints)
{
return canMakeValid(score, selectedPoints, 0, 0); // first 0 is for masking, second 0 is for summation.
}
public static boolean canMakeValid(ArrayList<Integer> score, int selectedPoints, int mask, int sum)
{
if(sum > selectedPoints) return false;
sum %= selectedPoints;
int sz = score.size();
if(mask == ((1<<sz)-1)) {
if(sum == 0) return true;
return false;
}
boolean ret = false;
for(int i = 0; i < sz; i++) {
if((mask&(1<<i)) == 0) {
ret = ret | canMakeValid(score, selectedPoints, mask | (1<<i), sum + score.get(i));
}
}
return ret;
}
You can learn about bit-masking from this link: https://discuss.codechef.com/t/a-small-tutorial-on-bitmasking/11811/3