Attempting to create chance calculator - java

I am relatively new to Java and wanted to try and make a code that would randomly generate 2 numbers a set amount of times, and it would track how many times the 2 numbers are the same. Then after X amount of attempts it would calculate the chance of it happening.
# of randoms divided by times they were the same
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
int[] anArray;
anArray = new int[100000];
Random randomGenerator = new Random();
for (int loop = 1; loop < 1000; loop++) {
int random1 = randomGenerator.nextInt(100);
int random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
int number = number + 1;
countArray[number] = loop;
}
if (loop == 1000) {
System.out.println("Took " + loop + " randoms.");
break;
}
else {}
}
}
}
Main issue seems to be getting array to fill and to get ints in/out of the loop.

Here is my version of your code:
import java.util.Random;
import java.util.ArrayList;
public class RandomTest {
public static void main(String[] args) {
ArrayList<Integer> duplicates = new ArrayList<Integer>();
int random1 = 0, random2 = 0;
Random randomGenerator = new Random();
for (int loop = 1; loop <= 1000; loop++) {
random1 = randomGenerator.nextInt(100);
random2 = randomGenerator.nextInt(100);
if (random1 == random2) {
duplicates.add(new Integer(random1));
}
}
for (Integer i : duplicates) {
System.out.println("Duplicate: "+i.toString());
}
}
}
There are a number of problems that your solution contains:
int number = number + 1;
The above will create a new int called number and give it the value null + 1, this is because the above can be split into 2 lines:
int num;
num = num + 1;
The first line will reserve memory space for a variable called num. The second line will try and put the value of (num + 1) into num. As we are calling num and it has not been initialised - this will give us a java.lang.Error (at least that is what I got).
So as you can see, putting number outside the for loop and initialising it like this:
int number = 0;
for (int loop = 1; loop <= 1000; loop++) {
number = number + 1;
}
Will increment the value of number by 1, 999 times.
Which brings me to the next point. The for loop will never make loop = 1000 because the condition will stop the loop before the condition is true, so when the for loop finishes, loop will equal 999. If you wanted the loop to finish on loop = 1000 you should use loop <= 1000. Also, the if condition is not necessary as when the loop finishes it will just carry on with the rest of the code beneath it.
I haven't used number at all in my solution, this is because I used an ArrayList, which is essentially a much more advanced version of an array that can grow dynamically and do loads of other cool stuff. Unfortunately ArrayLists need to contain objects, so I wrap each int inside an Integer object and this is fine. At the end I use a for loop to iterate through the duplicates list, for each result I print it out.
Hope this helps and if you have any questions feel free to comment beneath.

You probably want to do something about this line:
int number = number + 1;
To step through the array, set number to zero
int number = 0;
before entering the loop then increment number with
number = number + 1;

Related

How to randomly generate integers between 0 to 3 without making them consecutive in Java?

So far I have managed to generate random numbers using Random.
for(int i=0; i<10; i++){
prevnum = num;
num = random.nextInt(4);
num = num==prevnum?ran.nextInt(4):num;
System.out.println("random number: " + num);
}
I do not want consecutive repeats, what should I do?
EDIT/SOLUTION:
I solved the issue using this workaround.
By checking if it was running for the first time to avoid nullpointerexception.
And the just used an ArrayList to remove any chances of repitition by removing the previous randomly generated number from the small pool/range.
public void printRandom(){
for(int i=0; i<10; i++){
if(firstrun){
firstrun=false;
num = random.nextInt(4);
System.out.println(num);
} else{
num = getRandom(num);
System.out.println(num);
}
}
}
int getRandom(int prevNum){
ArrayList choices = new ArrayList(Arrays.asList(0, 1, 2, 3));
choices.remove(prevNum);
return (int) choices.get(random.nextInt(3));
}
You better to get a random number until it would be different with the last number, not just once, in other words repeat this condition:
num = num==prevnum?ran.nextInt(4):num;
like:
do {
num = num==prevnum?ran.nextInt(4):num;
while (num != prevnum);
because your numbers are few, they might be the same, so check it more than once if it is needed.
Try this
Random ran = new Random();
int cur, pre = ran.nextInt(4);
for (int i = 0; i < 10; i++) {
cur = ran.nextInt(4);
while (cur == pre) {
cur = ran.nextInt(4);
}
pre = cur;
System.out.println(cur);
}
If you do not want a consecutive repeat, then you always want the gap between two consecutive numbers to be non-zero. That you suggests you pick your first number normally, and from that point on you pick a random, but non-zero, gap. Add the gap to the previous number to get the next number, which will always be different.
Some pseudocode:
// First random number.
currentNum <- random(4);
print(currentNum);
// The rest of the random numbers.
repeat
gap <- 1 + random(3);
currentNum <- (currentNum + gap) MOD 4;
print(currentNum);
until enough numbers;

Why my code compare only first and last number of array - Java

I want to get the minimum number of my array, but my "if" compare only checks the first and last positions of array.
Here is my code:
int[] randNumbers = new int[20]; //deklaracja nowej tablicy 20-elementowej
Random r = new Random(); // Dodana metoda random do losowania
for(int i=0; i<randNumbers.length; i++) {
randNumbers[i] = r.nextInt(101);
int min = randNumbers[0];
System.out.println("Number "+i+": " + randNumbers[i]);
if (randNumbers[i] < min) {
min = randNumbers[i];
}
if (i == randNumbers.length-1) {
System.out.println("Min number is: " + min);
}
}
You don't even need the array here. Just iterate from 0 to N and check each random number if it less than min:
Random r = new Random();
int min = 101; // assign max value 101 before loop
for(int i = 0; i < 20; i++) {
int number = r.nextInt(101);
System.out.println("Number " + i + ": " + number);
if (number < min) {
min = number;
}
}
System.out.println(min);
If you want use array, you could initialize it before. For example using Random.ints():
int[] randNumbers = new Random().ints(20, 0, 101).toArray();
And then use the same for-loop idea with randNumbers[i] instead of nextInt(101)
try this out, your int min = randNumbers[0]; resets the min value every time so move it out of the loop
int min = 100;
for(int i=0; i<randNumbers.length; i++) {
randNumbers[i] = r.nextInt(101);
System.out.println("Number "+i+": " + randNumbers[i]);
if (randNumbers[i] < min) {
min = randNumbers[i];
}
}
System.out.println("Min number is: " + min);
The issue is that you are not remembering the minimum number as the loop runs. If you make a variable outside of the loop, it won't get updated every single iteration. Your code might look something like this:
int[] randNumbers = new int[20]; //deklaracja nowej tablicy 20-elementowej
Random r = new Random(); // Dodana metoda random do losowania
int min = 0;
for(int i=0; i<randNumbers.length; i++) {
int number = r.nextInt(101);
if(i == 0) min = number;
randNumbers[i] = number;
System.out.println("Number "+i+": " + number);
min = Math.min(min, number);
}
System.out.println("Min number is: " + min);
A few things to notice:
The variable min was moved outside of the loop. This is to make sure it is persistent across the loop, and won't be updated every iteration of the loop.
A new variable number is introduced. This is to prevent you from constantly calling randNumbers[i], which looks nicer, and to my knowledge slightly speeds it up. It also make it easier to change the variable once, and have it effective everywhere it is needed.
The last S.O.P was moved outside of the loop. There is no point in checking if the loop is at the last element if you can just put the statement the line after the loop ends. It will work the same functionally, but this looks nicer.
Instead of using an if statement to set min, it uses the output of Math.min. This is just a cosmetic change, and behaves the exact same with an if statement.
Move min int outside loop with value 0 isn't working, because my result will be everytime because Not initialized array have only '0'
Move it with 100+ is good idea. It's working when we know maximum number.
#geneSummons "int min = Integer.MAX_INT"
This works very well with different range/scope of numbers:) Thanks
Btw. I still don't understand why it's compare only first and last number ;)

Finding a missing number in an array that uses a random generator

I'm trying to make it so the random generator doesn't produce the same number in the array. I also don't know how to find the missing number. I tried the if statement, and it works, but it repeats.
The question problem "find the missing number in an array. The array consists of numbers from 1 to 10 in random sequence. One of the numbers in the array is absent and you must find it. Use one loop. An example {5,6,9,4,1,2,8,3,10} – the result will be: 7
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [10];
Random rand = new Random();
int numArr = 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
if (numbers[i] == numArr)
numArr++;
else
System.out.println("The missing num is " +numArr);
}
for(int val : numbers)
{
System.out.println("The next value is " +
val);
}
}
}
Assumption:
Numbers are unique
Only one entry is missing
number ranges from [1, 10] inclusive.
Solution
return 55 - Arrays.stream(yourArr).sum();
This is with O(n) runtime and O(1) space complexity.
If we break assumptions.
You will need O(N) space to figure out which entries are missing. To hold the marker either you can use List or BitSet or 2 bytes and manage it by hand. N is here the random number generation width.
There seems to be no mention on using a temporary data structure.
You can either sort the array and find the missing number, OR use a temporary sorted data structure.
You are conflating two things: the generator algorithm for a problem case and the solution to the problem itself. You shouldn't be interested in how the "random array" is generated at all (unless you want to test your solution). What you certainly shouldn't do is try to write the code that solves the problem in the method that generates the sample array.
If you want a randomly sorted list, Collections.shuffle will handle that for you. If you want a list without a single element, just generate a list of all elements 1..n and then remove the randomly selected number (then shuffle). So much for the generator. As for the solution, there are many methods to do it, someone already suggested using the sum, that's a perfectly valid solution.
It seems you are looking for this code.
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
int numArr = 1;
numbers[0] = rand.nextInt(10) + 1;
for (int i = 1; i < 9; i++)
{
int n = rand.nextInt(10) + 1;
numbers[i] = n;
int x =0;
while(x<i){
if(numbers[x] == n){
i = i-1;
break;
}
x++;
}
}
int sum = 0;
for (int val : numbers) {
sum = sum + val;
System.out.println("The next value is " +
val);
}
System.out.println("Missing number is " + (55 - sum));
}
}
Output is -
The next value is 6
The next value is 2
The next value is 8
The next value is 1
The next value is 4
The next value is 3
The next value is 9
The next value is 10
The next value is 7
Missing number is 5
I am generating 9 Numbers between(1 to 10) randomly and then printing which number is missing among them.
You have two options:
The way I did it in the code below: setting the random array without repeating the same number. And then a for loop from 1 to 10 and check if that number exist in the array.
You know that 1 + 2 + 3 + 2 + 3 + 4 + 5 + 6 + 8 + 9 + 10 = 55. So if you get the sum of all ints in the array you will have 55 - (the missing number). So now the missing number = 55 - sum.
This is the code I did (first method):
import java.util.Random;
public class questionThree
{
public static void main(String[] args)
{
int [] numbers = new int [9];
Random rand = new Random();
for (int i = 0; i <9; i++)
{
//setting random numbers in array without repeating
numbers[i] = checkForANumber(rand, numbers, i);
}
//print all nums
for(int val: numbers) System.out.println("The next value is " +
val);
for (int i = 1; i <= 10; i++)
{
boolean exist = false;
for(int val : numbers)
{
if(val == i){
exist = true;
}
}
if (!exist) System.out.println("The missing number is " + i);
}
}
private static int checkForANumber(Random rand, int[] numbers, int i){
int n = rand.nextInt(10) + 1;
boolean NumAlreadyExist = false;
for(int j = 0; j < i; j++)
{
if(numbers[j] == n){
NumAlreadyExist = true;
}
}
if(NumAlreadyExist) return checkForANumber(rand, numbers, i);
else return n;
}
}
Output:
The next value is 9
The next value is 3
The next value is 8
The next value is 6
The next value is 7
The next value is 10
The next value is 4
The next value is 2
The next value is 1
The missing number is 5

How can I change the values exceeding the int data type to the long data type in this code?

In the last portion of this code (where the last for loop and if statements are), I'm trying to change the data type of the integers to long when they exceed the integer data type limit. What am I doing wrong in this code? When I run, I get the same values as before I even tried to change them to long (which are increasingly huge integers until they get negative).
public class UniqueElements {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int maxValue = 0;
int numElements = 0;
int programRuns = 12;
Scanner sc = new Scanner(System.in);
for (int newExecution = 0; newExecution <= programRuns; newExecution++ ) {
System.out.print("Enter the maximum value for an element: ");
//prompt user to enter the maximum value
maxValue = sc.nextInt(); //user input for max value
System.out.print("Enter the number of elements in the array: ");
numElements = sc.nextInt(); //number of elements in an array
int A[] = new int[numElements];
//array comprising of the number of elements chosen by the user
int totalComp = 0; //set total comparisons to 0
for (int runs = 1; runs <= 100; runs++) { //program runs 100 times
Random rand = new Random(System.nanoTime());
//initiate the random number generator
int numComp = 0; //set number of comparisons to 0
for (int index = 0; index < numElements; index++) {
A[index] = rand.nextInt(maxValue);
//length of array is the number of elements the user puts in
}
for (int i = 0; i < A.length; i++) { //for each integer in the array
for (int j = i + 1; j < A.length; j++) {
//for each integer following i
if (A[i] == A[j]) { //if the are equal to eachother
//end the if statement
break;
}
if (numComp == (int)numComp) {
numComp++;
}
else {
Long.valueOf(numComp);
numComp++;
}
}
}
totalComp+= numComp;
} //end 100 loops
if (totalComp == (int)totalComp)
System.out.println("Average number of comparisons: " + totalComp / 100);
else {
System.out.println("Average number of comparisons: " +
Long.valueOf(totalComp) / 100L);
}
}
}
}
update:
somehow.... changing the total number of runs to 2 and dividing the totalComp variable by 2 and 2L made it work. Anyone know how that changed it?
You can't change the type of a variable after it's already been declared. You can cast that variable to another type, or "interpret" it as another type (as in your Long.valueOf()), but the variable still remains whatever type you declared it as.
In your code, you've declared totalComp to be an int, which in Java means it holds 32 bits (one of which is a sign bit). There's no way to make Java store more than 32 bits in an int. If you continue to add beyond Integer.MAX_VALUE, or subtract below Integer.MIN_VALUE, the value in the variable will simply under/overflow. So this statement after your for loop isn't doing what you expect, and will always be true: if (totalComp == (int)totalComp)
In other words, you can't go "back in time" and re-declare your primitive int as a long because you found out at runtime that you need to store larger values. The easiest way to solve this problem would be to declare totalComp as a long. If for some reason you can't change the type of totalComp, it is possible to detect overflow/underflow before performing the calculation; see this answer for details.

Counter for calculate number of runs in java

Here is my code which take an input value and compare it with a random value
I have 15 times to run the code to estimate and get the input value equals to the random value which the code decide ...
I want to make a counter to calculate how many times I did run the code ...
I tried to put count++; in different places in the code but I did not get right answer ... Where do you think that count++; should be put to get number of runs in the out put ...
thanks
Here is my code
package person;
import java.util.Random;
import java.util.Scanner;
public class Cat {
public static void main(String[] args) {
int max = 100;
int min = 0;
int diff = max-min;
Random rn = new Random();
int i = rn.nextInt(diff+1);
i+=min;
for (int k=0; k<15; k++){
int count=0;
Scanner sb = new Scanner(System.in);
System.out.println("Enter your number");
int x = sb.nextInt();
if(x>i){
System.out.println(x+"is bigger than i");
} else if(x<i){
System.out.println(x+"is smaller than i");
} else if (x==i){
System.out.println(x+"is equals to i "+" "+" no. of try"+count);
break;
}
}
}
}
The problem with your approach was that you count was in the loop so it would always be reseted. you can move it outside the loop or just print the counter loop variable.
package person;
import java.util.Random;
import java.util.Scanner;
public class Cat {
public static void main(String[] args) {
int max = 100;
int min = 0;
int diff = max-min;
Random rn = new Random();
int i = rn.nextInt(diff+1);
i+=min;
int k;
for (k=0; k<15; k++) {
Scanner sb = new Scanner(System.in);
System.out.println("Enter your number");
int x = sb.nextInt();
if(x>i) {
System.out.println(x+"is bigger than i");
} else if(x<i) {
System.out.println(x+"is smaller than i");
} else if (x==i) {
System.out.println(x+"is equals to i "+" "+" no. of try"+k+1);
break;
}
}
if(sb !=null) {
sb.close();
}
}
}
That's because you're setting count = 0 in your for loop. move
int count = 0;
above the for loop and add
count++;
at the beginning of the for-loop. If you had it at the end, you wouldn't count the last run when the loop might break out. Having it at the beginning of the loop means you definitely count each time you even start the process of looking for the randomly generated number.
But it would actually be better to just use the look counter k to keep track of the number of time. No need to waste the extra space on another variable when you already have k to keep track of everything. Just be careful because k starts at 0, so make sure you add 1 to your number of runs if using k.

Categories