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
Solved

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

Posted on 2015-02-17
11
130 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
  • 4
  • 2
  • 2
  • +3
11 Comments
 
LVL 35

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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
servlet doXXX methods 3 62
HashTable highest marks enumeration alternative 9 43
servlet example issue 6 46
passing enum to a method 4 23
Article by: Nadia
Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

828 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