/*
I don’t understand the logic behind the formulas below, example converting X to Y bla bla bla…
*/
From the book:
Let’s assume the range of interger values we want is [min, max]. If X is a number returned by random, then we can convert it into a number Y such that Y is in the range [min, max] that is, min< =Y<= max by applying the following formula:
Y = X * (max - min + 1) + min
For many applications, the value for min is 1, so the formula is simplified to
Y = X * max + 1
Let's write a program that selects a winner among the party goers of the annual spring fraternity dance. The party goers will receive numbers M+1, M+2, and so on, as they enter the house. The starting value M is selected by the chairperson of the party committee. The last number assigned is M+N if there are N party goers. At the end of the party, we run the program that will randomly select the winning number from the range of M+1 and M+N.
Expression in JAVA
int randomNumber = (int) (Math.floor(Math.random() * (max-min+1)) + min);
//Here is the program they have in the book using the formula above
import java.util.*;
class Ch3SelectWinner{
public static void main( String[] args) {
int startingNumber;
int count;
int winningNumber;
int min, max;
Scanner scanner = new Scanner(System.in);
System.out.print(”Enter the starting number M: “);
startingNumber = scanner.nextInt();
System.out.print(”Enter the number of party goers: “);
count = scanner.nextInt();
min = startingNumber + 1;
max = startingNumber + count;
winningNumber = (int)(Math.floor(Math.random()*(max-min+1))+min);
System.out.println(”\nThe Winning Number is ” + winningNumber);
}
}