I am writing this code to run 10000000 times and randomly generate a number and pick the most oftenly generated number, but the results do not seem random. The I have written is
public class Randomizer {
public static int[][] numbers = new int[45][2];
public static int maxN = 0;
public static int finalChoice;
public static void main(String[] args){
int arithmoi[] = new int[5];
for(int i =0; i < 5; i++){
arithmoi[i] = randomizer(1000000, 45);
System.out.println("A "+i+": "+arithmoi[i]);
}
int extra_num = randomizer(1000000, 20);
System.out.println("\nT: "+extra_num);
}
public static int randomizer(int times, int amount){
int[][] numbers = new int[amount][2];
for(int i = 0; i < amount; i++){
numbers[i][0] = i + 1;
numbers[i][1] = 0;
}
for(int i = 0; i < times; i ++){
int rnd = (int)(Math.random() * amount + 1);
for(int j = 0; j < amount; j++){
if(rnd == numbers [j] [0]){
numbers[j][1] ++ ;
break;
}
}
}
for(int i = 0; i < amount; i++){
if(maxN < numbers[i][1]){
finalChoice = numbers[i][0];
maxN = numbers[i][1];
}
}
return finalChoice;
}
}
The result that it gives me are A 0: 36
A 1: 36
A 2: 36
A 3: 36
A 4: 29
T: 14, A 0: 26
A 1: 44
A 2: 44
A 3: 44
A 4: 44
T: 4
and similar. What could the problem be?
import java.util.Random;
public class Randomizer {
public static int[][] numbers = new int[45][2];
public static int maxN = 0;
public static int finalChoice;
public static void main(String[] args){
int arithmoi[] = new int[5];
for(int i =0; i < 5; i++){
arithmoi[i] = randomizer(1000000, 45);
System.out.println("A "+(i+1)+": "+arithmoi[i]);
}
int extra_num = randomizer(1000000, 20);
System.out.println("\nT: "+extra_num);
}
public static int randomizer(int times, int amount){
int[][] numbers = new int[amount][2];
Random randomGenerator = new Random();
for(int i = 0; i < amount; i++){
numbers[i][0] = i + 1;
numbers[i][1] = 0;
}
for(int i = 0; i < times; i ++){
int rnd = randomGenerator.nextInt(amount);
for(int j = 0; j < amount; j++){
if(rnd == numbers [j] [0]){
numbers[j][1] ++ ;
break;
}
}
}
for(int i = 0; i < amount; i++){
if(maxN < numbers[i][1]){
finalChoice = numbers[i][0];
maxN = numbers[i][1];
}
}
return finalChoice;
}
}
The new code has still the same results(I used the Random Class)
You should use Java's Random class (java.util.Random) instead of writing your own. It is written by experts and has improved over many years as it is used and therefore tested by millions. It has been proven to generate pseudo-random numbers that do not have any particular pattern.
Writing your own pseudo-random generator would not be straight forward as there are a lot of factors involved.
Here is an example of its use:
Random random = new Random();
int maxIterations = 10000000;
int maxRandomValue = 100;
for(int i=0; i< maxIterations; i++)
{
System.out.println("Next random value: " + random.nextInt(maxRandomValue));
}
I think the main problem of you code it the way you tired to solve the task.
First of int[][] numbers = new int[amount][2]; holds redundant information because numbers[*][0] hold the position. Since numbers[i][1] holds the result for position i + 1 you can reduce the structure to int[amount].
Unlike other languages java defines the initial state of an int array to be always zero, so you do not need the first loop.
Your task is to let it rain on a line and check after n rounds, how many raindrops hit a certain spot/position.
It is okay to loop n times but since rnd.nextInt(amount) already gives you the spot the raindrop landed on, you do not have to iterate to find it.
for(int i = 0; i < times; i++) {
number[rnd.nextInt(amount)]++;
}
This will simulate the raindrops, but to get the proper random, you should initialize private static Random rnd = new Random() at class level and not at method level.
I hope this will help to solve your task.
Related
I'm very new to coding.
I'm writing this code and I'm struggling because I need to make a code that makes an array with 8 random integers and then it swaps the largest integer with the first number in the array.
When doing this though I'm getting an error and I cannot seem to fix it.
import java.util.Scanner;
import java.util.Random;
public class finalExam {
public static void main(String []args) {
Scanner input = new Scanner(System.in);
Random spinner = new Random();
int [] userInputs = new int [8];
for (int i = 0; i < userInputs.length; i++) {
userInputs[i] = spinner.nextInt(100)+1;
System.out.println(userInputs[i]);
}
int largest = userInputs[0];
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest)
largest = userInputs[j];
}
System.out.println("Your largest number is: " + largest);
int holder;
int [] arr = new int[101];
for (int m = 0; m <= arr.length; m++) {
holder = largest;
userInputs[0] = userInputs[largest];
holder = userInputs[0];
}
}
}
The error comes from the last bit of your code. userInputs[largest] is out of bound because the array is only 8 integers long (while largest can have a value of 100).
Since you need the position of the largest number, you'll have to save it in largestPosition when you identify which number is the largest, like so:
int largest = userInputs[0];
int largestPosition = 0;
for(int j = 1; j < userInputs.length; j++) {
if(userInputs[j] > largest){
largest = userInputs[j];
largestPosition = j;
}
}
That said, the loop which you used at the end also isn't needed here. You could just swap the first value of the array with the largest one using this method:
int first = userInputs[0];
userInputs[0] = largest;
userInputs[largestPosition] = first;
I am creating a histogram using another class to help display it, but that is not important to my question. Let me start by showing my code below
public class DisplayHistogram {
public static void main(String[] args) {
int temp = 0;
int holder = 0;
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
the problem I am having is I set the histogram to have a min of 1 and max of 20. I am generating three random integers and finding the average of the 3 and submitting it to the histogram 10,000 times. However, after the first loop of 10000, the "holder" variable doesn't reset back to 0 causing my program trying to submit a value outside of the max, and creating an error. I have attempted to set holder to 0 at the end of every loop by doing
x.submit(average);
holder = 0;
temp = 0;
However that does not help.
I have tried some of your suggestions making my code look like
import java.util.*;
public class DisplayHistogram {
public static void main(String[] args) {
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
int temp = 0;
int holder = 0;
int average = 0;
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
However it still returns this error
Exception in thread "main" HistogramOutOfBoundsException:
*******
Submitted value 22 is outside range [1,20] of Histogram.
*******
at Histogram.submit(Histogram.java:31)
at DisplayHistogram.main(DisplayHistogram.java:19)
Write your loops like this:
for(int i = 0; i<=10000; i++)
{
holder = 0; // add this line
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
Fixed. Was looping four times instead of three. For loop should've looked like
for(int i=0; i<=2; i++)
Short answer
Pay attention to details.
The answer you want
Unlike the other answer,
don't just initialize the holder variable every loop.
Instead, minimize the scope of the holder variable to the loop.
public static void main(String[] args)
{
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for (final int trialCount = 0; trialCount <= 10000; ++trialCount)
{
int holder = 0;
for (final int sampleCount = 0; sampleCount <= 3; ++sampleCount)
{
int temp = rand.nextInt(20) + 1;
holder += temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
The problem is to find the minimum number in the random array 50 numbers. It should be between 0-100 and its index. I don't know what's the wrong with my code. It prints more than one minimum value and I haven't found a way to make limit to the array:
You are not generating random number properly.
To find a random number in range 0..99,use
Random r = new Random();
int randomInt = r.nextInt(100);
Try this
public class RandomTest {
public static void main(String[] args) {
int arr[] = new int[50];
Random r = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = r.nextInt(100);
System.out.println(arr[i]);
}
int minimum = arr[0];
for (int j = 1; j < arr.length; j++) {
if (minimum > arr[j])
minimum = arr[j];
}
System.out.println("Minimum value-->" + minimum);
}
}
Output
Output will vary as per the generated number.In my case,I got
Minimum value-->4
You shouldn't print inside the "for" loop.
The loop determines which value is the minimum.
Once it has ended, print the result.
for{
...
...
}
System.out.println(Minimum);
You can use the following code:
int[] a = ...; // after random for
int min = a[0];
int minIndex = 0;
for(int i = 1; i < a.length(); i++) {
if(a[i] < min) {
min = a[i];
minIndex = i;
}
}
System.out.println(minIndex);
I am trying to fill an array with random int values from 0 to 6. To control my code i am printing out the random values I generate. I try to exclude duplicates in the nested if-statement inside the for-loop, but when I run the code I get my seven values, but some of them are still duplicated. Can someone please help me?
Here is my code:
import java.util.Random;
public class TesterArrayer
{
public static void main(String[] args)
{
int size = 7;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int x =0; x < size; x++)
{
int randomValue = randomNumber.nextInt(6);
if (randomValue != randomArray[x])
{
randomArray[x] = randomValue;
}
}//End for-loop
for (int y = 0; y < size; y++)
{
System.out.println(randomArray[y]);
}
}
}
public static void main(String[] args) {
int size = 7;
boolean add = true;
int counter = 0;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int j = 0; j < size; j++)
{
randomArray[j] = -1;
}
while (counter < size) {
add = true;
int randomValue = randomNumber.nextInt(7);
for (int x = 0; x < size; x++) {
if (randomValue == randomArray[x]) {
add = false;
}
}// End for-loop
if(add)
{
randomArray[counter] = randomValue;
counter++;
}
}
for (int y = 0; y < size; y++) {
System.out.println(randomArray[y]);
}
}
Try something like this. You don't want to add the number unless it's not already in the list. Also for your random you need 7 instead of 6 if you want 0-6.
This code will fill your array with 0-6 not repeating any numbers.
If you only want the numbers 0..length-1 in random order you can do something like this:
int length = 7;
List<Integer> list = new ArrayList<>(length);
for(int i=0; i<length; i++){
list.add(Integer.valueOf(i));
}
//list is now in order, need to randomly shuffle it
Collections.shuffle(list);
//now list is shuffled, convert to array
int array[] = new int[length];
for(int i=0; i<length; i++){
array[i] = list.get(i);
}
Change minLimit, maxLimit and noOfItems to get random Numbers
public class RandomIntegers
{
public static final Random random = new Random();
public static final int maxLimit = 6;
public static final int minLimit = 0;
public static final int noOfItems = 7;
public static void main( String[] args )
{
Set<Integer> uniqueRandomIntegerSet = new HashSet< Integer >();
while(uniqueRandomIntegerSet.size() < noOfItems)
uniqueRandomIntegerSet.add( random.nextInt( maxLimit - minLimit + 1 ) + minLimit );
Integer[] randomUniqueIntegers = uniqueRandomIntegerSet.toArray( new Integer[0] );
}
}
As you should use a more optimal data structure for this approach, as mentioned in the other answer and comments, you can still accomplish this with an array of course. As you have defined the problem you would need to change int randomValue = randomNumber.nextInt(6); to int randomValue = randomNumber.nextInt(7); or else this will loop infinitely as there is no possible way to have no duplicates in a size 7 array with only 6 values.
You can do something like this to modify your code for it to work:
boolean flag = false;
for(int x = 0; x < size; x++)
{
int randomValue = randomNumber.nextInt(7);
for (int i = 0; i < x; i++)
{
if (randomValue == randomArray[i])
{
//randomArray[x] = randomValue;
flag = true;
x--;
}
}
if (!flag)
randomArray[x] = randomValue;
flag = false;
}//End for-loop
This code is simply flagging when it sees a duplicate value in the array already and will skip this value and decrement the x value so that it will create another random value for this spot in the array.
byte[] source = new byte[1024];
Random rand = new Random();
rand.nextBytes(source);
I have just had a brain block, I have a Deck object and want to get every 5 card combination from it in a iterative manner. Could someone show me how to do this, I would imagine it would be:
for(int i =0; i <52; i++){
for(int j = i + 1 ; j < 52; j++){
for(int k = j + 1; k < 52; k++{
for(int l = k + 1; l < 52; l++){
for(int m = l + 1; m < 52; m++){
}
}
}
}
}
Is this correct?
Thanks
Yes, that works fine. If you want to enumerate all n-card combinations, this doesn't work.
For that, you'd need recursion. Put card 0 in slot 0. Recursively enumerate all n-1 card hands (excluding 0) in the remaining n-1 slots. Repeat, with card 1 in slot 0. Pretty easy.
EDIT: some code:
private static final int NUM_CARDS = 52;
public static void main(String[] args) {
enumerateAllHands(Integer.parseInt(args[0]));
}
private static void enumerateAllHands(int n) {
if (n > NUM_CARDS) {
throw new IllegalArgumentException();
}
int[] cards = new int[n];
BitSet cardsUsed = new BitSet();
enumerate(cards, 0, cardsUsed);
}
private static void enumerate(int[] cards, int from, BitSet cardsUsed) {
if (from == cards.length) {
emit(cards);
} else {
for (int i = 0; i < NUM_CARDS; i++) {
if (!cardsUsed.get(i)) {
cards[from] = i;
cardsUsed.set(i);
enumerate(cards, from + 1, cardsUsed);
cardsUsed.clear(i);
}
}
}
}
private static void emit(int[] cards) {
System.out.println(Arrays.toString(cards));
}