Solved

Given "n"(n>0) number of dices with "m"(m>0) sides. Print all possible combinations

Posted on 2015-02-17
11
143 Views
Last Modified: 2015-02-18
Hi,
  Write a Java program to print all possible combinations in below case
   "n"(n>0) number of dices with "m"(m>0) sides. Print all possible combinations
  for example.
     2 dices with 3 sides should print out this
 (1,1)
 (1,2)
 (1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
   I gave it a sincere try before posting this. My code doesn't work if number of dices is more than 2 which is not right. Thanks in advance for looking.
0
Comment
Question by:koppcha
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +3
11 Comments
 
LVL 36

Expert Comment

by:mccarl
ID: 40615484
Can you post your code?

Also, I assume that this is for a homework/assignment exercise, but can you please confirm if that is the case? This allows everyone to provide the correct level of assistance.
0
 
LVL 8

Author Comment

by:koppcha
ID: 40615501
This is definitely not homework/assignment.  It's been long time since I have been to school(which could be the reason I spent half day figuring this out )

import java.util.Arrays;

public class DiceHistogram {
	public void getHistogram(int dices, int sides) {
		int diceArray[] = new int[dices];
		
		//Initialize Array
		for (int i = 0; i< diceArray.length; i++) {
			diceArray[i] = 1;
		}
		
		//System.out.println(Arrays.toString(diceArray));
			for(int k=dices-2; k>=0; k--) {
				for(int j=1; j<= sides; j++) {
				   diceArray[k] = j;
			       for(int i=1; i<=sides; i++ ) {
				       diceArray[dices-1] = i;
				       System.out.println(Arrays.toString(diceArray));
				       
			       }
			       
				}   
			}

		}
		
		//for ( int j)
		
		
	
	public static void main(String[] args) {
		DiceHistogram dh = new DiceHistogram();
		dh.getHistogram(2, 3);
	}

}

Open in new window

0
 
LVL 32

Expert Comment

by:phoffric
ID: 40615514
Often, when the term "combinations" is used in an exercise, the order does not matter, so (2,1) is considered the same as (1,2).
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 8

Author Comment

by:koppcha
ID: 40615532
In this case they should be considered different. "Combination" is my own way of explaining it not part of original problem. Example should be taken for reference. They are considered different.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40615543
Can we assume that pow(m,n) fits in an int?
0
 
LVL 27

Accepted Solution

by:
dpearson earned 300 total points
ID: 40615547
This is actually a fairly tricky problem.  You can't just use one or two or even 5 loops to do it, but you really need 1 loop for each dice - which is a parameter to the problem.

That sort of problem is usually easiest to solve with recursion - where a function calls to itself.

Something like this.

Recursive functions tend to be not a lot of code, but can be hard to understand if you've not seen them before.  I added some comments to help explain what's going on.

Doug

	public static List<String> dice(int nDice, int nSides) {
		List<String> combinations = new ArrayList<>();

		if (nDice == 1) {
			// For one dice we get a list with just 1 entry
			// 1
			// 2
			// 3
			for (int side = 1; side <= nSides; side++) {
				combinations.add(Integer.toString(side));
			}
		} else {
			// When we have more than one dice we add the values for this dice
			// to all possible combinations from "nDice-1"
			// So add "1," to all subsequent combinations (e.g. "1,1", "1,2", "2,1", "2,2" etc.)
			List<String> following = dice(nDice-1, nSides) ;
			for (int side = 1; side <= nSides; side++) {
				for (String follow : following) {
					combinations.add(side + ", " + follow);
				}
			}
		}

		return combinations ;
	}

	public static void listCombinations() {
		List<String> combinations = dice(4, 3) ;

		for (String combo : combinations) {
			System.out.println("(" + combo + ")") ;
		}
	}

Open in new window

0
 
LVL 8

Author Comment

by:koppcha
ID: 40616252
Hi Dpearson,
  I tried your program with different inputs and it works as expected. I am still trying to understand. will get back to you. Thanks for your help.

Hi Ozo,
  Yes I think it's fair assumption.
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 100 total points
ID: 40616327
if pow(sides,dices) fits in an int, another method might be
static void getHistogram(int dices, int sides) {
        for( int i=(int)Math.pow(sides,dices);--i>=0;){
          System.out.print("(");
          int n=i;
          for( int d=0;d<dices;++d ){
            if( d>0 ){ System.out.print(","); }
            System.out.print(sides-(n%sides));
            n/=sides;
          }
          System.out.println(")");
       }      
}
0
 
LVL 27

Assisted Solution

by:rrz
rrz earned 100 total points
ID: 40617107
I think what your asking for here is permutations.  Look at  
http://www.mathsisfun.com/combinatorics/combinations-permutations.html     
Here is my version.  What you call a side, I call a face.
import java.util.*;
 public class Dice{
   public static void main(String[] args) {
     int numberOfDice = 3; 
	 int numberOfFaces = 3;
     int numberOfOutcomes = (int)Math.pow(numberOfFaces,numberOfDice);   
     int[] roll = new int[numberOfOutcomes]; //all initially 0 (roll to the next face)
     StringBuilder[] outcomes = new StringBuilder[numberOfOutcomes];
     for(int j=0; j<numberOfOutcomes; j++){
                                  outcomes[j] = new StringBuilder("("); 
     }
     for(int k = 1; k <= numberOfDice; k++){
                int numberOnFace = 1; 
                for(int y = 0; y < numberOfOutcomes; y++){
                                   if(roll[y] == 0){
                                            outcomes[y].append(numberOnFace);
					    if(k != numberOfDice)outcomes[y].append(",");
                                            numberOnFace++;
                                            roll[y] = 1; // don't roll, just stay on the same face
                                            if(numberOnFace == numberOfFaces + 1){
                                                              numberOnFace = 1;
                                                              roll[y] = 0; // roll to the next face
                                            }
                                   }else{
                                         outcomes[y].append(numberOnFace);
					 if(k != numberOfDice)outcomes[y].append(",");
                                        }
                }            
     }
     for(int z = 0; z < numberOfOutcomes; z++){
                                           System.out.println(outcomes[z].toString() + ")");
    }
   }
}

Open in new window

0
 
LVL 27

Expert Comment

by:dpearson
ID: 40617119
I am still trying to understand. will get back to you. Thanks for your help.

The key for a recursive solution is to understand that the larger problem can be seen as a repetition of a smaller problem.

E.g. If I gave you a list of all combinations of 2 dice with 3 sides:

 (1,1)
 (1,2)
 (1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)

then you can use this list to create the list of all combinations of 3 dice by adding "1, ...", "2, ..." and "3, ..." to the front of each of the earlier combinations:

1 +  (1,1) => (1,1,1)
1+  (1,2) => (1,1,2)
1 + (1,3) => (1,1,3)
1 + (2,1) => (1,2,1)
...
3 + (1,1) => (3,1,1)
3 + (1,2) => (3,1,2)
...
etc..

Once you recognize the problem has that property, then you can write a function that calls to itself to get it to compute this.

Anyway - hope you can figure it out :)

Doug
0
 
LVL 8

Author Comment

by:koppcha
ID: 40617404
Hi Doug,
  I got it now. Thanks for the help.

Ozo/rrz,
  Thanks guys. Your code works too.

Doug's solution is easier for me to understand.
I am going to close this question now.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
When there is a disconnect between the intentions of their creator and the recipient, when algorithms go awry, they can have disastrous consequences.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question