문제

I want to write a program that simulates the following: I have 6 dices, and I roll with some dices every time.

When I don't roll with a die, I just assume that I rolled 0 with that.

I want to list all the possible variations I can get this way. A few examples:

1,2,4,6,0,1

3,5,1,0,0,4

6,6,4,2,0,0 etc.

Any ideas on how to do this? (I am using java, but of course I'm only interested in the general concept.)

Thanks in advance.

도움이 되었습니까?

해결책

You can use a recursive method, keeping track of depth: EDIT, maybe this method would be better:

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

다른 팁

Since you specifically asked for "only the general concept", here are two general approaches, either:

  • Use a 6-level nested for-loop for just do an exhaustive enumeration of all possible rolls between 0-6 (more efficient)
  • Just use 1 for-loop to generate all numbers between 0-66666, and discard any numbers that contain 7, 8, 9; and then print the numbers with some formatted padding, and commas (cleaner code to look at if you don't care about the small efficiency difference)

Just for elegance sake, I would write a recursive method that calls loops through 0-7 for a given index then itself to initialize the next index.

It could then initialize an array or abritrary size.

Simple Python implementation.

This is when you just print.

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,"")

This is when you want to return the whole permutation.

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);
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top