java - 验证骰子组合

标签 java android algorithm validation dice

我正在 Android 中构建一个名为 Thirty Throws 的应用程序,但我完全卡住了 通过我的验证。 在 Thirty Throws 中,您的骰子得分为 4、5、6、7、8、9、10、11、12 和 6。 每回合包含 3 次掷骰,用户可以在每次掷骰之间选择他希望保留的骰子。 示例说用户掷出了 4,4,3,5,1,5 那么他可以选择分数 11 因为 4 + 4 +3 = 11 和 5 + 1 + 5 = 11 或者如果用户掷出了 2,2 ,2他可以选择6。

我正在努力验证分数。我目前拥有的代码能够验证最多。我错过了什么?

我一直在寻找一些递归解决方案,但它们似乎不是我要找的,因为我必须返回一个 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;
}

最佳答案

您应该从任何位置获取所有可能的数字。因此,为了获得所有可能的结果,您可以使用这些数字的排列来序列化这些数字。另一种方法是使用位掩码递归。 这是您的问题的解决方案。 (基于位掩码递归)。

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;
}

您可以从此链接了解位掩码:https://discuss.codechef.com/t/a-small-tutorial-on-bitmasking/11811/3

关于java - 验证骰子组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56733139/

相关文章:

java - 为什么我在这里得到一个空的注释数组

android - 如何在 Android 中保存数据

algorithm - 该算法的复杂性

java - 如何以编程方式更改复选框选中的颜色

java - Java中数组索引越界

java - Mockito:模拟 AnnotationType

android - 从Android中的事件处理方法返回的 bool 值是什么意思

android - 无法实例化以下类:-com.google.android.youtube.player.YouTubePlayerView

python - 从英文文本中提取产品名称

c - 洪水填充算法 - 迷宫导航