Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python
C++

JAVA


PHP
SQL
Assignments

CSCI125Code


Die.java

import java.util.Random;
import java.util.ArrayList;

/**
 * Modeling a die (the singular for dice) with a given number of side.
 * It can be fun to look at the results after rolling 5-10 dice, then after throwing 100,
 * then after 1,000, and maybe even 10,000,000 to see how the distriution changes.
 * 
 * @author Charles Cusack
 * @version 10/9/24
 */
public class Die
{
   // A random object so we can get random numbers
   private Random rand;
   // How many sides the die has
   private int sides;
   // An ArrayList to keep track of how many times each number comes up.
   private ArrayList<Integer> counts;
   
   /**
    * @param sides how many sides the die should have.
    */
   public Die(int sides) {
       rand = new Random();
       this.sides = sides;
       counts = new ArrayList<>();
       // Need to initialize the count of each size to 0.
       for(int i=0;i<sides;i++) {
           counts.add(0);
       }
   }
   
   /**
    * Roll the die times times, discarding the results.
    * 
    * @param times how many times to roll the die.
    */
   public void throwDie(int times) {
       for(int i=0;i<times;i++) {
           throwDie();
       }
   }
   
   /**
    * Roll the die. Update the count for the given result.
    * 
    * @return the random die roll
    */
   public int throwDie() {
       int roll = rand.nextInt(sides);
       counts.set(roll,counts.get(roll)+1);
       return roll+1;
   }
   
   /**
    * Print the distribution of die rolls.
    */
   public void printDistribution() {
       for(int i=0;i<sides;i++) {
           System.out.println((i+1)+": "+counts.get(i));
       }
   }
}