我想编写一个模拟以下内容的程序:我有 6 个骰子,每次都掷一些骰子。
当我不掷骰子时,我只是假设我掷骰子是 0。
我想列出我可以通过这种方式获得的所有可能的变化。几个例子:
1,2,4,6,0,1
3,5,1,0,0,4
6,6,4,2,0,0 等
关于如何做到这一点的任何想法?(我使用的是java,但当然我只对一般概念感兴趣。)
提前致谢。
我想编写一个模拟以下内容的程序:我有 6 个骰子,每次都掷一些骰子。
当我不掷骰子时,我只是假设我掷骰子是 0。
我想列出我可以通过这种方式获得的所有可能的变化。几个例子:
1,2,4,6,0,1
3,5,1,0,0,4
6,6,4,2,0,0 等
关于如何做到这一点的任何想法?(我使用的是java,但当然我只对一般概念感兴趣。)
提前致谢。
由于您特别要求“仅一般概念”,因此这里有两种一般方法:
0-6(更有效)0-66666,并丢弃任何包含7, 8, 9; 然后使用一些格式化的填充和逗号打印数字(如果您不关心小的效率差异,请查看更清晰的代码)您可以使用递归方法,跟踪深度:编辑,也许这种方法会更好:
class Main {
    public static void roll(String s, int depth) {
        if(depth == 0)
            System.out.println(s.substring(1));
        else
            for(int i = 0; i <= 6; i++)
                roll(s + "," + i, depth - 1);
    }
    public static void main(String[] args) {
        roll("", 6); //2nd parameter > 0
    }
}
只是为了优雅起见,我会编写一个递归方法,通过 0-7 为给定索引调用循环,然后自己初始化下一个索引。
然后它可以初始化一个数组或 abritrary 大小。
简单的 Python 实现。
这是你刚刚打印的时候。
def PrintAllPerms(n, str_):
    if (n == 0):
        print str_
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            PrintAllPerms(n-1, str_)
            str_ = str_[:-1]
PrintAllPerms(2,"")
这是您想要返回整个排列的时候。
def PrintAllPerms(n, arr, str_):
    if (n == 0):
        arr.append(str_)
        return arr
    else:
        for i in ["1","2","3","4","5","6"]:
            str_ = str_ + i
            arr = PrintAllPerms(n-1,arr,str_)
            str_ = str_[:-1]
        return arr
PrintAllPerms(2,[],"")
public class DiceTest {
    public static void main(String[] args) {
        int[] dice = {0, 1, 2, 3, 4, 5, 6 };
        for (int i : dice) {
            for (int j : dice) {
                System.out.println("Printing dice values : " + i + " " + j);
            }
        }
    }
}