/**
This is a simple dice rolling program. It is designed to simulate the rolling of 10 sided dice. The program takes in two numbers from the user,
the number of dice rolled (r), and the number of dice kept (k). The program then generates r sets of random integers from 1-10.
If a roll is equal to 10, it is rerolled and 10 is added to the new value (called exploding, in game terms). The r numbers are then arragned highest to lowest,
and k of the highest are kept. These k numbers are added and printed to the screen as the output, along with other data to make it more user-friendly.
created by Colin Ahern, May 2007
*/
import java.util.Random;
import java.util.*;
class roll{
public static void main(String[]args){
Scanner sc = new Scanner(system.in);
Random rand = new Random(45);
int[] dice;
int r,k,total,temp=-1;
While(temp<=0){ //Determines number of "dice" to be rolled
System.out.print("Enter the number of dice to be rolled: ");
if(sc.hasNextInt()) temp=sc.nextInt();
}
r=temp;
temp=-1;
while(temp<=0){ //Determines number of "dice" to be kept
System.out.print("Please enter the number of dice to be kept: ");
if(sc.hasNextint()) temp=sc.nextInt();
if(temp>r){ //Checks if kept is greater than rolled
temp=-1;
System.out.println("Dice kept greater than dice rolled. "+r+" dice will be rolled.");
}
}
k=temp;
dice = new Int[r];
for(int i=0;i<r;i++){ //Generates random numbers for dice values
dice[i]=rand.nextInt(10)+1;
while((dice[i]%10)==0){ //Exploding loop
dice[i]+=rand.nextInt(10)+1;
}
}
sort(dice);
for(int i=0;i<k;i++){ //Adds up the kept dice to total
total+=dice[i];
} //the following line is the game-specific notation of the roll result
System.out.print("Result: "+r+"k"+k+": "+total+" ( ");
for(int i=0;i<r;i++){ //Outputs the individual values of each dice roll
System.out.print(dice[i]+" ");
}
System.out.println(")");
}
static void sort(int[] rolls){ //Sorts the array from highest to lowest
int sz = rolls.length;
boolean swapped = true; // 'cause we want to actually do something.
while(swapped) {
swapped = false; // if everything is sorted, then we'll never set swapped to true, and we'll be done.
for(int i=0; i<sz-1; i++) {
if(rolls[i+1] > rolls[i]) { // if the next roll is greater than the one we're looking at, move it down towards [0].
int r = rolls[i+1];
rolls[i+1] = rolls[i];
rolls[i] = r;
swapped = true; // to continue the while loop.
}
}
}
}
}