我如何使用嵌套循环来帮助识别我是否有2个不同的匹配对骰子

时间:2018-02-10 05:11:43

标签: java nested-loops

所以我刚学了一些关于循环和嵌套循环的课程。我的教授说嵌套循环可以帮助我们完成任务,例如知道我们是否用4个骰子滚动了2个不同的匹配对(4242)我对这将如何工作有点困惑。

所以我开始研究它,这是我能够创造的。

public boolean 4matchDice(String dice){

   for (int i = 0; i < 4; i++) {

      for (int j = 0; j < 4; j++) {

      }
    }

我使用boolean作为返回,因为它会告诉我们是否有2个不同的匹配对。

事情是,我在循环中放入什么?这最令我困惑的是什么。

3 个答案:

答案 0 :(得分:0)

如果你只是比较两组两个骰子,这就足够了:

public boolean match4Dice(int first, int second, int third, int fourth) {
    if ((first == third && second == fourth) || (first == fourth && second == third)) {
        return true;
    }
    return false;
}

但如果您将2组与任意数量的骰子进行比较,以下算法将更适合您。

public boolean matchDice(String firstDiceSet, String secondDiceSet) {
    // validate input, string must contain numbers from 1 - 6 only. 
    // lenghts of strings firstDiceSet & secondDiceSet must be equal
    // works for any number of dice in each set.

    // The dice only match if all numbers in the firstDiceSet all present in the secondDiceSet also.
    // Let us count the matching numbers to check if this true.

    int numberOfMatches = 0;

    for (int i = 0; i < firstDiceSet.length(); i++) {
        for (int j = 0; j < secondDiceSet.length(); j++) {
            if (firstDiceSet[i] == secondDiceSet[j]) { // and not used
                // increment number of matches
                // mark secondDiceSet[j] as used, so that you do not count the same match twice.
                // account for cases where firstDiceSet = "33" and the secondDiceSet = "35"
            }
        }
    }

    // your dice set match if the following condition is true
    return (numberOfMatches == secondDiceSet.length());
}

答案 1 :(得分:0)

嗨我刚编写了一个以“4242”作为输入的解决方案,尽管sindhu_sp的方法更实用我相信。我只想向您展示另一个帮助您学习Java的示例!

public static boolean fourMatchDice(String dice){
        int match = 0;
        for (int i = 0; i < dice.length(); i++){

            for (int j = i+1; j < dice.length(); j++){

                if (dice.toCharArray()[i] == dice.toCharArray()[j]){
                    System.out.println("does " + dice.toCharArray()[i] + " = " + dice.toCharArray()[j]);
                    match ++;
                }
            }
        }

        if(match == 2) *EDIT* //Change to (match >= 2) if 4 of the same pair is allowed.
            return true;
        return false;
    }

    public static void main(String[] args) {
        System.out.println(fourMatchDice("4242"));
    }

输出:

does 4 = 4
does 2 = 2
true

答案 2 :(得分:0)

这是我提出的解决方案,似乎正在为我运行的所有测试用例返回正确的结果。

    public static boolean matchDice(String dice) {

    char[] diceArray = dice.toCharArray();
    int pairs = 0;

    for (int i = 0; i < 4; i++) {

        for (int j = i + 1; j < dice.length(); j++) {


            if (diceArray[i] == diceArray[j]) {

                diceArray[i] = 'X';
                diceArray[j] = 'Y';
                pairs++;
            }

        }
    }
    return (pairs > 1);
}