Modelling the queues at a restaurant at a college - java

Here are the constraints:
The restaurant runs from 6am to 11:59 pm daily (hence opens at minute 360).
On average, a customer arrives at the restaurant every 5 minutes. (Hence 20% chance of a customer in one minute.)
The restaurant requires between 2 and 7 minutes to fill a customer order, and because there is only one person running the entire restaurant, the next customer in line will be served only after the food is served to the previous customer.
While the restaurant tries to serve everyone in the order they came in, some groups of people are given a priority. Seniors will be served before Juniors; juniors before sophomores; sophomores before freshmen.
So far, I have implemented the code below, using Java Priority Queues and Maps. I tried to identify each customer by the time they came in (ranging from 360 and onwards) and their grades. However, this is my first time using priority queues and maps, and I am not very sure if I'm doing things right—in fact, it returns this error below, which I'm not sure how to fix despite having consulted the APIs and some other java resources:
Exception in thread "main" java.lang.ClassCastException: java.base/java.util.AbstractMap$SimpleEntry cannot be cast to java.base/java.lang.Comparable
import java.util.*;
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.Map;
class CustomerComparator implements Comparator<Customer>
{
public int compare(Customer c1, Customer c2)
{
if(c1.grade < c2.grade)
return 1;
else if(c1.grade > c2.grade)
return -1;
else
return 0;
}
}
class Customer
{
public int grade;
public double waitingTime;
public Customer(int grade, double waitingTime)
{
this.grade = grade;
this.waitingTime = waitingTime;
}
public int getGrade()
{
return grade;
}
public double getWaitingTime()
{
return waitingTime;
}
}
public class RestaurantPriority
{
public static Queue<Map.Entry<Integer, Integer>> Restaurant = new PriorityQueue<Map.Entry<Integer, Integer>>();
public static int waitingTime = 2 + (int)(Math.random() * ((7 - 2) + 1));
public static void main(String[] args)
{
RestaurantPriority();
}
public static void RestaurantPriority()
{
double rand = 0.0;
boolean newCustomer = false;
for(int i = 360; i<1440; i++)
{
if(Restaurant.isEmpty())
waitingTime = 2 + (int)(Math.random() * ((7 - 2) + 1));
if(i == 1439)
{
while(!Restaurant.isEmpty())
{
waitingTime--;
if(waitingTime == 0)
{
Restaurant.remove();
waitingTime = 2 + (int)(Math.random() * ((7 - 2) + 1));
}
System.out.println(i + ": " + Restaurant);
i++;
}
}
rand = Math.random();
if(rand >= 0.0 && rand < 0.2)
newCustomer = true;
else
newCustomer = false;
if(newCustomer)
{
int grade = 0;
double rand2 = Math.random();
if(rand >= 0.0 && rand < 0.25)
grade = 1;
else if(rand >= 0.25 && rand < 0.5)
grade = 2;
else if(rand >= 0.5 && rand <0.75)
grade = 3;
else
grade = 4;
Restaurant.add(new AbstractMap.SimpleEntry(grade,i));
}
if(!Restaurant.isEmpty())
{
waitingTime--;
if(waitingTime == 0)
Restaurant.poll();
}
if(!Restaurant.isEmpty() && waitingTime == 0)
{
waitingTime = 2 + (int)(Math.random() * ((7 - 2) + 1));
}
if (i<1439)
System.out.println(i + ": " + Restaurant);
}
}
}
(The entire code is all written in one file. I'm not sure if this is relevant information, but I thought it might help.)
I have been stuck at this for a few days now, and I'd really appreciate any help.

public class RestaurantPriority {
public static Queue<Customer> Restaurant = new PriorityQueue<Customer>(new CustomerComparator());
public static int waitingTime = 2 + (int) (Math.random() * ((7 - 2) + 1));
public static void main(String[] args) {
RestaurantPriority();
}
public static void RestaurantPriority() {
double rand = 0.0;
boolean newCustomer = false;
for (int i = 360; i < 1440; i++) {
if (Restaurant.isEmpty()) {
waitingTime = 2 + (int) (Math.random() * ((7 - 2) + 1));
}
if (i == 1439) {
while (!Restaurant.isEmpty()) {
waitingTime--;
if (waitingTime == 0) {
Restaurant.remove();
waitingTime = 2 + (int) (Math.random() * ((7 - 2) + 1));
}
System.out.println(i + ": " + Restaurant);
i++;
}
}
rand = Math.random();
if (rand >= 0.0 && rand < 0.2) {
newCustomer = true;
} else {
newCustomer = false;
}
if (newCustomer) {
int grade = 0;
double rand2 = Math.random();
if (rand >= 0.0 && rand < 0.25) {
grade = 1;
} else if (rand >= 0.25 && rand < 0.5) {
grade = 2;
} else if (rand >= 0.5 && rand < 0.75) {
grade = 3;
} else {
grade = 4;
}
Restaurant.add(new Customer(grade, i));
}
if (!Restaurant.isEmpty()) {
waitingTime--;
if (waitingTime == 0) {
Restaurant.poll();
}
}
if (!Restaurant.isEmpty() && waitingTime == 0) {
waitingTime = 2 + (int) (Math.random() * ((7 - 2) + 1));
}
if (i < 1439) {
System.out.println(i + ": " + Restaurant);
}
}
}}

You want to save Customers in the Queue not Maps. For the priority queue to know how to order them you need to give it a comparator.
One other more elegant solution might be to use the class Random instead of Math.random(). Random can give you integer with a defined upper bound. Further, you don't need a named comparator.
P.S. please try to use the java naming convention. https://www.oracle.com/technetwork/java/codeconventions-135099.html
public static void RestaurantPriority() {
Random random = new Random();
Queue<Customer> customers = new PriorityQueue<>(Comparator.comparingInt(o -> o.grade));
double servingTime = 0;
for (int i = 360; i < 1440; i++) {
if(servingTime <= 0 && !customers.isEmpty()){
servingTime = customers.poll().waitingTime;
}
if (random.nextDouble()<0.20) {
customers.add(new Customer(
random.nextInt(4),
random.nextInt(5)+2)
);
}
servingTime--;
}
}

Related

How can I use values stored in an array to another method to do a calculation?

static void diceRoll(int[] val) {
for (int i=0;i<6;i++) {
int roll1 = (int) ((Math.random() * 1000 % 6 + 1));
int roll2 = (int) ((Math.random() * 1000 % 6 + 1));
int roll3 = (int) ((Math.random() * 1000 % 6 + 1));
int roll4 = (int) ((Math.random() * 1000 % 6 + 1));
int total =0;
if ((roll1 < roll2) && (roll1 < roll3) && (roll1 < roll4)) {
total= roll2 + roll3 + roll4;
} else if ((roll2 < roll1) && (roll2 < roll3) && (roll2 < roll4)) {
total= roll1 + roll3 + roll4;
} else if ((roll3 < roll1) && (roll3 < roll2) && (roll3 < roll4)) {
total = roll1 + roll2 + roll4;
} else if ((roll4 < roll1) && (roll4 < roll2) && (roll4 < roll3)) {
total = roll1 + roll2 + roll3;
}
}
}
static void calculateBonus(int[] bonusVal){
int bonus=0;
int[] val= new int[6];
for (int i=0;i<6;i++)
for(int j=0;j<6;j++)
if (val[i] > 10 && val[i] != 11) {
bonusVal[j] = (val[i] - 10) / 2;
} else if (val[i] < 10) {
bonusVal[j] = ((val[i] / 2) - 5);
} else if (val[i] == 10 || val[i] == 11) {
bonusVal[j] = 0;
}
}
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
//Declaring variables
int level;
String choice = null;
//Getting the Level value
System.out.println("Enter the Level value :");
level = sc.nextInt();
while ((level<=0)||(level>20)){
System.out.println("Invalid input.Please enter a number between 1-20.");
System.out.println("Enter the Level value : ");
level = sc.nextInt();
}
do{
int[] val= new int[6];
int _str= val[0];
int con= val[1];
int dex= val[2];
int _int= val[3];
int wis= val[4];
int _cha= val[5];
int [] bonusVal=new int[6];
int bonus1= bonusVal[0];
int bonus2= bonusVal[1];
int bonus3= bonusVal[2];
int bonus4= bonusVal[3];
int bonus5= bonusVal[4];
int bonus6= bonusVal[5];
//Printing the Level
System.out.println("\n\n\n\n\nLevel : [ "+level+" ]");
//Displaying out put
System.out.println("_Str : ["+_str+" ]"+"["+bonus1+"]");
System.out.println("Dex : ["+dex+" ]"+"["+bonus2+"]");
System.out.println("Con : ["+con+" ]"+"["+bonus3+"]");
System.out.println("Int : ["+_int+" ]"+"["+bonus4+"]");
System.out.println("Wis : ["+wis+" ]"+"["+bonus5+"]");
System.out.println("_Cha : ["+_cha+" ]"+"["+bonus6+"]");
//Calculating the Hit points
double hp = (((Math.random()*1000 %6+1)+bonus3)*level);
//Print the Hit points
System.out.println("HP : ["+hp+"]");
//Give the chance to re-roll or continue
System.out.println("Type r if you want to re-roll or any other character if you want to continue :");
choice = sc.next();
}
while (choice.equals("r"));;
}
}
I think i had made mistakes in the second method .I want to figure out how can i use above stored values in the array to calcuate bonus and store the values for bonus in another array.This is the program i have so far.I still didnt got the output i neede.I need to get 6 values from dice roll method and store them in an array.and then i want to call the values to calculate bonus and store those bonus values in another array.
I think you want to do something like below. I haven't compiled the code, let me know if you face any issues in compiling.
static int[] calculateBonus(int[] val) {
int[] bonusVal = new int[val.length];
for(int j=0; j < val.length; j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonusVal;
}
You need to return an array from the first method to start with, right now it doesn't work with an array at all.
Change it to the below to return an array and have a new array variable
static int[] diceRoll() {
final int rolls = 6;
int[] result = new int[rolls];
//the for loop...
at the end of the for loop you store the value in the array and then at the end return the array so the end of the method will look like
result[i] = total;
}
return result;
}
The calculateBonus will use this returned array as input and it will also work internally with an array and not an int as you have now. I also added that it will return an array.
static int[] calculateBonus(int[] val){
int count = val.length;
int[] bonus = new int[count];
for(int j=0;j<count;j++) {
if (val[j] > 10 && val[j] != 11) {
bonus[j] = (val[j] - 10) / 2;
} else if (val[j] < 10) {
bonus[j] = ((val[j] / 2) - 5);
} else if (val[j] == 10 || val[j] == 11) {
bonus[j] = 0;
}
}
return bonus;
}
A simple run
public static void main(String[] args) {
int[] values = diceRoll();
int[] bonus = calculateBonus(values);
for(int i=0; i<bonus.length; i++) {
System.out.println(bonus[i]);
}
}
Update
Below is a new version of the two methods that addresses the questions I asked in the comment and also clean up the code some.
Main difference is that I use a ArrayList in the diceRole method and that calculateBonus now uses double.
static int[] diceRoll() {
int[] result = new int[6];
for (int i=0;i<6;i++) {
List<Integer> list = new ArrayList<>();
for (int j = 0; j < 4; j++) {
list.add(new Integer((int) ((Math.random() * 1000 % 6 + 1))));
}
Collections.sort(list); //list is now in ascending order
int total =0;
for (int j = 1; j < list.size(); j++) {
total += list.get(j).intValue();
}
result[i] = total;
}
return result;
}
static double[] calculateBonus(int[] val) {
int count = val.length;
double[] bonus = new double[count];
for(int j=0;j<count;j++) {
double value = 0.0;
if (val[j] > 11) {
value = (val[j] - 10.0) / 2.0;
} else if (val[j] < 10.0) {
value = ((val[j] / 2.0) - 5.0);
}
bonus[j] = value;
}
return bonus;
}

Changing variable based on loop sequence in java

So I am building the petals on a rose game and the dice defined as dice1, dice 2 etc. i then run a loop to decide for each dice what its value is and add that to the game value. What i want is for every sequence of the loop for it to switch which variable it is looking at. So first run through look at dice1. and then second look at dice2.
public class Rosegame
{
private int dice1;
private int dice2;
private int dice3;
private int dice4;
private int dice5;
private int gameValue;
public void rollDice()
{
dice1 = (int) ((6-1+1) * Math.random()) + 1;
dice2 = (int) ((6-1+1) * Math.random()) + 1;
dice3 = (int) ((6-1+1) * Math.random()) + 1;
dice4 = (int) ((6-1+1) * Math.random()) + 1;
dice5 = (int) ((6-1+1) * Math.random()) + 1;
}
public void printValues()
{
System.out.println("Dice 1 is:" + dice1);
System.out.println("Dice 2 is:" + dice2);
System.out.println("Dice 3 is:" + dice3);
System.out.println("Dice 4 is:" + dice4);
System.out.println("Dice 5 is:" + dice5);
}
public int calculatePetalsOnRose()
{
gameValue = 0;
for(int i = 1; i <=5; i++)
{
if (dice1 == 5)
{
gameValue = gameValue + 4;
}
else if (dice1 == 3)
{
gameValue = gameValue + 2;
}
else
{
gameValue = gameValue;
}
}
return gameValue;
}
}
this is my current code and what I need is inside the if statement where it has dice1, i want that to be able to change everytime it loops. Their is also a driver that runs the methods and allows input but so far that is working. Thank you so much in advance
Edit:
switching the variables to an array i now have which gives me an error saying java.lang.NullPointerException. It happens when the rollDice function is being called.
public class PetalsGame
{
private int[] anArrayDice;
private int gameValue;
public void rollDice()
{
anArrayDice[0] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[1] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[2] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[3] = (int) ((6-1+1) * Math.random()) + 1;
anArrayDice[4] = (int) ((6-1+1) * Math.random()) + 1;
}
public void printDice()
{
System.out.println("Dice 1 is:" + anArrayDice[0]);
System.out.println("Dice 2 is:" + anArrayDice[1]);
System.out.println("Dice 3 is:" + anArrayDice[2]);
System.out.println("Dice 4 is:" + anArrayDice[3]);
System.out.println("Dice 5 is:" + anArrayDice[4]);
}
public int calculateAllPetals()
{
gameValue = 0;
for(int i = 0; i <=4; i++)
{
if (anArrayDice[i] == 5)
{
gameValue = gameValue + 4;
}
else if (anArrayDice[i] == 3)
{
gameValue = gameValue + 2;
}
else
{
gameValue = gameValue;
}
}
return gameValue;
}
}
I was able to fix it by adding anArrayDice = new int[5]; inside of the rollDice method. Thank you for the help.
You only seem to roll one die (at least that is the only value you seem to be interested in), so I would start by extracting a method to roll one die. I would also prefer, for readability, Random.nextInt(int). Something like,
private static final Random rand = new Random();
private static int rollDie(int sides) {
return rand.nextInt(sides) + 1;
}
Then you can roll and calculate your rose with that method as needed. Also, you can use x += y; instead of x = x + y;. Something like,
public int calculatePetalsOnRose() {
int gameValue = 0;
for (int i = 1; i <= 5; i++) {
int dice = rollDie(6);
System.out.printf("Dice %d is: %d%n", i, dice);
if (dice == 5) {
gameValue += 4;
} else if (dice == 3) {
gameValue += 2;
}
}
return gameValue;
}
I think it would be alot easier to do this if you use an array to store your dice. Also it saves you from having to repeat the same lines of code over and over again.
public int [] diceArray;
private int gameValue;
public void rollDice()
{
for(int i =0; i < diceArray.length; i++)
{
diceArray[i] = 6 *((int)Math.random()+ 1);
}
}
public void printValues()
{
for(int i=0; i < diceArray.length; i++)
{
System.out.println("Dice" + (i+1) +"is:" + diceArray[i]);
}
}
public int calculatePetalsOnRose()
{
gameValue = 0;
for(int i = 0; i < diceArray.length; i++)
{
if(diceArray[i] == 5)
{
gameValue += 4;
}
else if (diceArray[i] == 3)
{
gameValue +=2;
}
}
return gameValue;
}

Can't figure out the error Luhn check

Its supose to tell me if a card is valid or invalid using luhn check
4388576018402626 invalid
4388576018410707 valid
but it keeps telling me that everything is invalid :/
Any tips on what to do, or where to look, would be amazing. I have been stuck for a few hours.
It would also help if people tell me any tips on how to find why a code is not working as intended.
im using eclipse and java
public class Task11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long number = input.nextLong();
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
}
public static boolean isValid(long number) {
return (getSize(number) >= 13) && (getSize(number) <= 16)
&& (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37))
&& (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long start = 0;
String digits = Long.toString(number);
if ((digits.length() % 2) == 0) {
start = digits.length() - 1;
} else {
start = digits.length() - 2;
}
while (start != 0) {
result += (int) ((((start % 10) * 2) % 10) + (((start % 10) * 2) / 2));
start = start / 100;
}
return result;
}
public static int getDigit(int number) {
return number % 10 + (number / 10);
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number != 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
return getPrefix(number, getSize(d)) == d;
}
public static int getSize(long d) {
int numberOfDigits = 0;
String sizeString = Long.toString(d);
numberOfDigits = sizeString.length();
return numberOfDigits;
}
public static long getPrefix(long number, int k) {
String size = Long.toString(number);
if (size.length() <= k) {
return number;
} else {
return Long.parseLong(size.substring(0, k));
}
}
}
You should modiffy your isValid() method to write down when it doesn't work, like this:
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
System.out.println("Err: Number "+number+" is too long");
return false;
} else if (! (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37)) ){
System.out.println("Err: Number "+number+" prefix doesn't match");
return false;
} else if( (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 != 0){
System.out.println("Err: Number "+number+" doesn't have sum of odd and evens % 10. ");
return false;
}
return true;
}
My guess for your problem is on the getPrefix() method, you should add some logs here too.
EDIT: so, got more time to help you (don't know if it's still necessary but anyway). Also, I corrected the method I wrote, there were some errors (like, the opposite of getSize(number) >= 13 is getSize(number) < 13)...
First it will be faster to test with a set of data instead of entering the values each time yourself (add the values you want to check):
public static void main(String[] args) {
long[] luhnCheckSet = {
0, // too short
1111111111111111111L, // too long (19)
222222222222222l // prefix doesn't match
4388576018402626l, // should work ?
};
//System.out.print("Enter a credit card number as a long integer: ");
//long number = input.nextLong();
for(long number : luhnCheckSet){
System.out.println("Checking number: "+number);
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
System.out.println("-");
}
}
I don't know the details of this, but I think you should work with String all along, and parse to long only if needed (if number is more than 19 characters, it might not parse it long).
Still, going with longs.
I detailed your getPrefix() with more logs AND put the d in parameter in long (it's good habit to be carefull what primitive types you compare):
public static boolean prefixMatched(long number, long d) {
int prefixSize = getSize(d);
long numberPrefix = getPrefix(number, prefixSize);
System.out.println("Testing prefix of size "+prefixSize+" from number: "+number+". Prefix is: "+numberPrefix+", should be:"+d+", are they equals ? "+(numberPrefix == d));
return numberPrefix == d;
}
Still don't know what's wrong with this code, but it looks like it comes from the last test:
I didn't do it but you should make one method from sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 and log both numbers and the sum (like i did in prefixMatched() ). Add logs in both method to be sure it gets the result you want/ works like it should.
Have you used a debugger ? if you can, do it, it can be faster than adding a lot of logs !
Good luck
EDIT:
Here are the working functions and below I provided a shorter, more efficient solution too:
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count- 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
in.close();
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
I also found a solution with less lines of logic. I know you're probably searching for an OO approach with functions, building from this could be of some help.
Similar question regarding error in Luhn algorithm logic:
Check Credit Card Validity using Luhn Algorithm
Link to shorter solution:
https://code.google.com/p/gnuc-credit-card-checker/source/browse/trunk/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
And here I tested the solution with real CC numbers:
public class CreditCardValidation{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
public static void main(String[] args){
//String num = "REPLACE WITH VALID NUMBER"; //Valid
String num = REPLACE WITH INVALID NUMBER; //Invalid
num = num.trim();
if(Check(num)){
System.out.println("Valid");
}
else
System.out.println("Invalid");
//Check();
}
}

reducing using instance variable to decrease the use of memory

I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}

Generating two random prime numbers in JAVA

I'm trying to generate two random prime numbers in JAVA, however, I want the loop to keep repeating itself until both of those two variables are prime numbers, and then they output themselves.
The p and q variables are randomized by the Math.random() function and are in the range of 2 to 128 (excluding the 128).
Here is my code:
int pRandom = (int) (Math.random() * (127 - 2) + 2);
int qRandom = (int) (Math.random() * (127 - 2) + 2);
int p = pRandom;
int q = qRandom;
for (int i = 1; i < p; i++) {
boolean isPPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPPrime = false;
break;
}
}
if (isPPrime){
JOptionPane.showMessageDialog(null, "YAY!");
break;
}
System.out.println("P value: " + p + "\n" + "Q value: " + q);
}
Here is what you want:
public class RandomPrimeGenerator {
public static void main(String[] args) {
while (true) {
int pRandom = (int) (Math.random() * (127 - 2) + 2);
if(isPrime(pRandom)){
System.out.println("Got Random Prime P :"+pRandom);
break;
}
}
while(true){
int qRandom = (int) (Math.random() * (127 - 2) + 2);
if(isPrime(qRandom)){
System.out.println("Got Random Prime Q :"+qRandom);
break;
}
}
}
private static boolean isPrime(int n) {
int i;
for(i=2;i<=Math.sqrt(n);i++){
if(n % i == 0){
return false;
}
}
return true;
}
}

Categories