【问题标题】:Generate possible values for dice rolls为掷骰子生成可能的值
【发布时间】:2018-06-13 03:08:34
【问题描述】:

我需要一个能够生成所有可能的掷骰子组合的 java 程序。骰子的数量和骰子的面数可能会有所不同。 例如。 3个六面骰子的组合可能如下。 111 112 113 114 115 116 121 122 123 124 125 126……等等……直到666。 有什么帮助吗??? 某种

public Map generatePossibleNumbers(int face, int numberOfDice){
   // generate numbers and return map
   Map generatedMap=new HashMap();
   return generatedMap;
}

提前致谢

【问题讨论】:

  • Stack Overflow 不是代码编写服务。
  • 对不起,兄弟,我在征求意见.. 零先生...如果您不希望,您可能不会回答...
  • 我建议你尝试手动生成更多的序列。开始寻找模式。然后用文字描述解决问题需要采取的步骤。

标签: java


【解决方案1】:

我建议使用Collection 而不是Map,因为您不需要存储Key-Value 对。

这是我想出的:

public static void diceRoll(int dice, int numberOfDice) {
    Deque<Integer> list = new ArrayDeque<>(dice);
    diceRoll(dice, numberOfDice, list); // initially we have chosen nothing
}

// Private recursive helper method to implement diceRoll method.
// Adds a 'list' parameter of a list representing
private static void diceRoll(int dice, int numberOfDice, Deque<Integer> list) {
    if (dice == 0) {
        // Base Case: nothing left to roll. Print all of the outcomes.
        System.out.println(list);
    } else {
        // Recursive case: dice >= 1.
        for (int i = 1; i <= numberOfDice; i++) {
            list.addLast(i); // choose
            diceRoll(dice - 1, numberOfDice, list); // explore
            list.removeLast(); // un-choose
        }
    }
}

【讨论】:

  • 没问题。但请尝试理解代码,而不仅仅是复制它。 ;)
  • 是的,我猜到了,你递归地调用了这个方法......这真的很有帮助:)
猜你喜欢
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2021-06-18
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2018-05-03
相关资源
最近更新 更多