开发者

list all possible combinations of a 9x9 box with 9 cells are occupied each time

开发者 https://www.devze.com 2023-02-14 17:52 出处:网络
this is the 2D array 9x9 grids ini开发者_StackOverflowtially 000000000 000000000 000000000 000000000 000000000

this is the 2D array 9x9 grids ini开发者_StackOverflowtially

000000000  
000000000  
000000000  
000000000  
000000000  
000000000  
000000000  
000000000  
000000000  

if a cell is occupied, it will use 1 to represent... and each time there must be 9 cells to be used at a time...

111111111  
000000000  
000000000  
000000000  
000000000  
000000000  
000000000  
000000000  
000000000

how to write some codes to generate all the different combination with these nine "1" in the 9x9 graph?


I would probably use a recursive method, or a couple of nested for loops.

However, you should know that there are

     81 choose 9 = 260 887 834 350

such combinations.


Nested loops are not a good idea for n choose k problems: If you had to occupy only 2 cells, you could do that (pseudo-code):

for(int i= 0; i < grid.length*grid[0]*length; i++){
    for(int j = i + 1; j < grid.length*grid[0]*length; j++){
        // Build grid with cells i and j occupied
    }
}

With 3, you would have to do this:

for(int i= 0; i < grid.length*grid[0]*length; i++){
    for(int j = i + 1; j < grid.length*grid[0]*length; j++){
        for(int j = k + 1; k < grid.length*grid[0]*length; k++){
            // Build grid with cells i, j and k occupied
        }
    }
}

... I suppose you see the problem now, to have 9 cells occupied, you would have 9 nested loops (nasty), and more importantly, your code won't be valid for any other value of occupied cells.

Use recursion, I'm not doing it for you but here is a clue:

The point of recursion is to reduce the problem so many times that it will become trivial. What's a trivial case here? n-choose-1 is trivial, it's n.

// This function calculates n-choose-k
public static int nchoosek(int n, int k){
    if(k == 1){
        return n;
    }else{
            // To come up with this, you need to write down your equation and try
            // to express n-choose-k as a function of n-1-choose-k-1
        return nchoosek(n - 1, k - 1) * n / k;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消