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;
}
Related
The task is to simulate a wheel of fortune, which you are allowed to turn ten times.
You can spin as many times as you like, but as soon as the 0 comes, all points are gone. The program should stop the round as soon as a score over 10 is reached or a 0 comes. The results should be added at the end.
We are now at the point where the points are added and fields are fixed, but we can't think of anything to do with stopping or adding the results.
Does anyone have an idea?
Thanks in advance!
import java.util.Map;
import java.util.LinkedHashMap;
public class RandomBeispielzwei {
private static final Map<Double, Integer> GRENZEN = new LinkedHashMap<Double, Integer>();
static {
GRENZEN.put(0.1, 1);
GRENZEN.put(0.2, 2);
GRENZEN.put(0.3, 3);
GRENZEN.put(0.4, 1);
GRENZEN.put(0.5, 2);
GRENZEN.put(0.6, 3);
GRENZEN.put(0.7, 1);
GRENZEN.put(0.8, 2);
GRENZEN.put(0.9, 3);
GRENZEN.put(1.0, 0);
}
private Integer naechsteZufallzahl() {
double random = Math.random();
for (Map.Entry<Double, Integer> entry : GRENZEN.entrySet()) {
if (random <= entry.getKey().doubleValue()) {
return entry.getValue();
}
}
throw new UnsupportedOperationException("Fuer die Zufallszahl wurde kein passender Wert in der Map gefunden");
}
public static void main(String[] args) {
int anzahl1 = 0;
int anzahl2 = 0;
int anzahl3 = 0;
int anzahl0 = 0;
RandomBeispielzwei b = new RandomBeispielzwei();
for (int i = 0; i < 10; i++) {
Integer z = b.naechsteZufallzahl();
if (z.intValue() == 1) {
anzahl1++;
} else if (z.intValue() == 2) {
anzahl2++;
} else if (z.intValue() == 3) {
anzahl3++;
} else {
anzahl0++;
}
}
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
System.out.println("1: " + anzahl1);
System.out.println("Punktzahl 1: " + ges1);
System.out.println("2: " + anzahl2);
System.out.println("Punktzahl 2: " + ges2);
System.out.println("3: " + anzahl3);
System.out.println("Punktzahl 3: " + ges3);
System.out.println("0: " + anzahl0);
System.out.println("Gesamtzahl: " + (anzahl1 + anzahl2 + anzahl3 + anzahl0));
System.out.println("Gesamtpunktzahl: " + (ges1 + ges2 + ges3));
}
}
For exiting the for-loop (and any other loop), you can use the "break" statement, which simply ends the loop (similar to how "return" will exit a method). In order to be able to stop once the total score reaches ten, you of course need to keep track of the total score. To do this, the easiest way would be to introduce aa integer variable (e.g. "gesamtpunktzahl"), to which you add the amount of points scored in each turn. In all, it would look something like this:
import java.util.Map;
import java.util.LinkedHashMap;
public class RandomBeispielZwei {
private static final Map<Double, Integer> GRENZEN = new LinkedHashMap<Double, Integer>();
static {
GRENZEN.put(0.1, 1);
GRENZEN.put(0.2, 2);
GRENZEN.put(0.3, 3);
GRENZEN.put(0.4, 1);
GRENZEN.put(0.5, 2);
GRENZEN.put(0.6, 3);
GRENZEN.put(0.7, 1);
GRENZEN.put(0.8, 2);
GRENZEN.put(0.9, 3);
GRENZEN.put(1.0, 0);
}
private Integer naechsteZufallzahl() {
double random = Math.random();
for (Map.Entry<Double, Integer> entry : GRENZEN.entrySet()) {
if (random <= entry.getKey().doubleValue()) {
return entry.getValue();
}
}
throw new UnsupportedOperationException("Fuer die Zufallszahl wurde kein passender Wert in der Map gefunden");
}
public static void main(String[] args) {
int anzahl1 = 0;
int anzahl2 = 0;
int anzahl3 = 0;
int anzahl0 = 0;
int gesamtpunktzahl = 0; // this will store what the total score is so far
RandomBeispielzwei b = new RandomBeispielzwei();
for (int i = 0; i < 10000; i++) {
Integer z = b.naechsteZufallzahl();
if (z.intValue() == 1) {
anzahl1++;
gesamtpunktzahl++; // a 1 was scored, so we increase the total score by 1
} else if (z.intValue() == 2) {
anzahl2++;
gesamtpunktzahl += 2; // same with a 2
} else if (z.intValue() == 3) {
anzahl3++;
gesamtpunktzahl += 3; // same with a 3
} else {
anzahl0++;
break; // a 0 was rolled, so we end the game (by exiting the for-loop)
}
if (gesamtpunktzahl >= 10) break; // at least 10 points were scored so far, so we exit the for-loop
}
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
System.out.println("1: " + anzahl1);
System.out.println("Punktzahl 1: " + ges1);
System.out.println("2: " + anzahl2);
System.out.println("Punktzahl 2: " + ges2);
System.out.println("3: " + anzahl3);
System.out.println("Punktzahl 3: " + ges3);
System.out.println("0: " + anzahl0);
System.out.println("Gesamtzahl: " + (anzahl1 + anzahl2 + anzahl3 + anzahl0));
System.out.println("Gesamtpunktzahl: " + gesamtpunktzahl); // since we calculated it anyway, we might as well just use it here
}
}
I suggest using the loop do ... while for the counting and printing.
And please check you code - does you need count the same variable anzahl1 for each ges?:
int ges1 = anzahl1 * 1;
int ges2 = anzahl1 * 2;
int ges3 = anzahl1 * 3;
if not - then replace ges[i] = anzahles[1] * (i+1); to ges[i] = anzahles[i+1] * (i+1);
public static void main(String[] args) {
int[] anzahles = new int[4];
int gesamtpunktzahl = 0;
Integer z = 0;
RandomBeispielzwei b = new RandomBeispielzwei();
do {
z = b.naechsteZufallzahl();
anzahles[z]++;
gesamtpunktzahl += z;
} while (!(z == 0 || gesamtpunktzahl >= 10));
int ges[] = new int[3];
for (int i = 0; i < 3; i++) {
ges[i] = anzahles[1] * (i+1);
System.out.println((i+1) + ": " + anzahles[i+1]);
System.out.println("Punktzahl " + (i+1) + ": " + ges[i]);
}
System.out.println("0: " + anzahles[0]);
System.out.println("Gesamtzahl: " + Arrays.stream(anzahles).sum());
System.out.println("Gesamtpunktzahl: " + Arrays.stream(ges).sum());
}
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--;
}
}
I am currently attempting to solve a ProjectEuler problem and I have got everything down, except the speed. I am almost certain the reason the program executes so slowly is due to the nested loops. I would love some advice on how to speed this up. I am a novice programmer, so I am not familiar with a lot of the more advanced methods/topics.
public class Problem12 {
public static void main(String[] args) {
int num;
for (int i = 1; i < 15000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
for (int x = 1; x <= num; x++) {
if (num % x == 0) {
counter++;
}
}
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
}
}
}
EDIT : Below is the new code that is exponentially faster. Removed the constant line printing as well to speed it up even more.
public class Problem12 {
public static void main(String[] args) {
int num;
outerloop:
for (int i = 1; i < 25000; i++) {
num = i * (i + 1) / 2;
int counter = 0;
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
if (counter >= 500) {
System.out.println("[" + i + "] - " + num + " is divisible by " + counter + " numbers.");
break outerloop;
}
}
}
}
}
}
For starters, when looking at divisors, you never need to go further than the root square of the number, because each divisor below the square root has an equivalent above.
n = a * b => a <= sqrt(n) or b <= sqrt(n)
Then you need to count the other side of the division:
double root = Math.sqrt(num);
for (int x = 1; x < root; x++) {
if (num % x == 0) {
counter += 2;
}
}
The square root is special because it counts only once if it is integer:
if ((double) ((int) root) == root) {
counter += 1;
}
You just need to factorize the number. p^a * q^b * r^c has (a+1)*(b+1)*(c+1) divisors. Here is some basic implementation using this idea:
static int Divisors(int num) {
if (num == 1) {
return 1;
}
int root = (int) Math.sqrt(num);
for (int x = 2; x <= root; x++) {
if (num % x == 0) {
int c = 0;
do {
++c;
num /= x;
} while (num % x == 0);
return (c + 1) * Divisors(num);
}
}
return 2;
}
public static void test500() {
int i = 1, num = 1;
while (Divisors(num) <= 500) {
num += ++i;
}
System.out.println("\nFound: [" + i + "] - " + num);
}
I want to take the array of random values I've generated and print the aforementioned array with parentheses outside the longest run of the same number.
For example, if the array was [0,1,1,1,2,4,7,4] I'd like to receive 0(111)2474 as an output.
This is my code thus far.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax {
runMax = counter;
runMin = i - counter + 1;
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter - 1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
}
}
try this code:
import java.util.Arrays;
import java.util.Random;
public class Snippet {
/**
* This method will generate my random numbers for my array.
*
* #param min
* minimum random value wanted
* #param max
* maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
// Part 1 - Generate a random array of length 40 with random 1-6
// inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
// Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
// Counts the longest run of the same number. A run continues only when
// consecutive numbers have the same value.
// RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 0;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax) {
runMax = counter;
startCounter = i - counter +2;
// runMin = i-counter+1;
variableNum = array1[i];
endCounter = i+1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax
+ " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter
+ " and ends at " + endCounter);
for (int i = 0; i < array1.length; i++) {
if (i==startCounter) {
System.out.print("(");
}
System.out.print(array1[i]);
if (i==endCounter) {
System.out.print(")");
}
}
System.out.println();
// Prints the array with parentheses outside the longest run, if there
// is more than one max run, use the last one.
}
}
Okay. I think I have this. The first answer was close, but if you run the program a few times, you discover issues. There is a logic error somewhere in your above code, but I have a work around. I think it is how you get the endCounter. It seems to count odd. But I got the program to work as far as I can tell. Try this out. I have run it several times and it seems consistent.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax ){
runMax = counter;
runMin = i - counter ;// was plus one I cahnged this.
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter -1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
String output = "";// added this
for(int x = 0; x < array1.length; x++)
{
if( x == startCounter)
{
output += "("+array1[x];
}
else if( x == startCounter + runMax )
{
else if( x == startCounter + runMax )
{
if(x == array1.length-1)
{
output += ")";
}
else
{
output += ")"+array1[x];
}
}
else
{
output += array1[x];
}
}
System.out.print("\n"+output);
}
}
Here's a shorter, more generic solution. This method takes any array of ints and prints parenthesis around the longest run of numbers. If there are two runs of the same lengths it prints it around the first one.
public String makeString(int[] ints) {
if (ints.length == 0) return ""; // Quit early if there's nothing to do.
// Initialize variables.
int lastNumber = ints[0];
// We keep track of the all time best run. Defaults to first int found.
int bestStart = 0;
int bestRun = 1;
// ... as well as the current run.
int currentStart = 0;
int currentRun = 1;
String s = ""+ints[0];
// Starting from the second int, we check if the current run is continuing.
for (int i = 1; i < ints.length; i++) {
int current = ints[i];
// If the current run continues, we update currentStart/currentRun, else we reset it.
if (current == lastNumber) {
currentRun++;
} else {
currentStart = i;
currentRun = 1;
}
// Now we check if the currentRun is better than the best.
// If so, we update bestStart/bestRun.
if (currentRun > bestRun) {
bestStart = currentStart;
bestRun = currentRun;
}
lastNumber = current;
s += current;
}
// Now that we've found it, we insert parenthesis aaaaaaand we're done!
return s.substring(0, bestStart)
+"("+s.substring(bestStart, bestStart+bestRun)+")"
+s.substring(bestStart+bestRun);
}
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;
}
}