ArrayList contains - java

I don't really understand what's happening, if someone could explain this to me that would be great.
So, here's my code:
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
for(int i =0; i != 90; i++){
System.out.println(generate());
}
}
public static int generate(){
Random random = new Random();
int rand = random.nextInt(89)+1;
while(numbers.contains(rand)){ //<---Here seems to be my problem
rand = random.nextInt(89)+1;
System.out.println("Number: " + rand + " already exists!");
}
numbers.add(rand);
return rand;
}
I am writing a program that generates a random number from 0-90, each of which are different to the last. Unfortunately, it seems that the while loop only returns true.

You're picking from 89 random numbers (1-89 inclusive) and trying to find a unique number each time... but you're calling that 90 times. What do you expect the last iteration to do? (To put it another way - you're trying to squeeze 90 numbers into 89 slots. That's not going to work.) On the last iteration, all the possible values will already be in the list, so the condition of your while loop will always be met, whatever value is randomly chosen on each iteration.
If you wanted the numbers to be between 1 and 90 inclusive, you should be using random.nextInt(90) + 1. The argument to nextInt is the maximum number exclusive to generate - so if you call random.nextInt(3) for example, it will generate 0, 1 or 2.
(There are better ways of doing this, by the way - such as populating the list and then using Collections.shuffle - but I've concentrated on explaining the behaviour of your current code.)

You can do it easily by using collections shuffle
public static ArrayList<Integer> numbers = new ArrayList<Integer>();
for(int i =1; i <= 90; i++){
number.add(i)
}
Collections.shuffle(numbers); // at this point the number are shuffled.
Read about shuffle.

Related

Java: Make sure the last 9 digits in ArrayList unique

trying to make a Sudoku game, but stuck at checking (and fixing) duplicates in rows and columns
if (buttons.getSource().equals(newGame)) {
String diffic = JOptionPane.showInputDialog("Choose difficulty, ranging from 1-3 where 1 is easy");
int difficulty = Integer.parseInt(diffic);
ArrayList<Integer> allnumbers = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9));
if (difficulty == 1) {
for (int i = 0; i < 81; i++) {
fields.get(i).setEditable(true);
fields.get(i).setText("");
double d = Math.random();
if (d < 0.6) {
random = new Random();
Integer randomInt = allnumbers.get(random.nextInt(allnumbers.size()));
fields.get(i).setText(randomInt + "");
fields.get(i).setEditable(false);
}
}
}
As of now, it prints and stuff works, but it prints duplicated numbers.
My pseudo-way right now:
1. Find a way to print the arraylist in random order for each row. The random part is done, but it still prints duplicated numbers (im thinking to print numbers 1-9 in random order 9 times, 1 time for each row)
2. Find a way to check columns afterwards. No clue how yet, taking one problem at a time
Anyone here been around the same problems, got some tips?
Thank you :)
Create an ArrayList with the nine number.
Use Collections.shuffle(...) to shuffle the numbers in random order.

Range in Array Java

I need to complete this task. But I am not entirely sure how to get the range into the array. I think I am supposed to use a loop somehow but I do not get it to work.
This is what I have so far:
import java.util.*;
public class A2_1
{
static Scanner x = new Scanner(System.in);
public static void main(String[] args)
{
int [] myArray = new int [1000000];
int x;
for ( x = 0; x <= 100; x++)
{
myArray [x] = x+1;
}
System.out.println(myArray);
}
}
This is the task:
"Create a program that generates 1,000,000 integer random values in the range of [1,..,100] and for any given x (between 1 and 100) taken from the user input computes "(๐‘‡๐‘œ๐‘ก๐‘Ž๐‘™ ๐‘›๐‘ข๐‘š๐‘๐‘’๐‘Ÿ ๐‘œ๐‘“ ๐‘’๐‘™๐‘’๐‘š๐‘’๐‘›๐‘ก๐‘  ๐‘™๐‘’๐‘ ๐‘  ๐‘กโ„Ž๐‘Ž๐‘› ๐‘œ๐‘Ÿ ๐‘’๐‘ž๐‘ข๐‘Ž๐‘™ ๐‘ก๐‘œ ๐‘ฅ)/1,000,000".
This value must be comparable to the CDF of a uniform distribution U[1,100] at point x."
Im not going to give you the answer since this sounds like homework but I will help you break it down into manageable chunks.
First, generate 1000000 random numbers between 1 and 100. You were on the right track and combine it with Dawnkeepers hint. int[] randoms = new int[1000000]; is an int array with a size of 1000000. Now iterate over each index and assign it a random number(see above). Now you have an array with a million random numbers. Generating a million randoms can be a lengthy procedure depending on you machine, so yea.
Next, use the Scanner class to get the users input.(pro tip: dont use the same variable name for your scanner as your variable in the for loop lol). Now do an if check to make sure they enter a number between 1 and 100. if(val > 0 && val <= 100). If this passes, move on, else quit or prompt for user to give a new input. Using the scanner is pretty trivial so I wont go into this.
Finally, iterate through your list of randoms and keep a counter of how many numbers less then or equal to x.
int counter = 0;
for(int i = 0; i < randoms.length; i++) {
//if randoms[i] is less then or equal x, counter++
}
Take that counter and do your math, int final_answer = counter/randoms.length;
That's all that is to it. There are more efficient ways of doing this but I tried to make it simple to follow. If I misread the question, sorry.

Explain what this code is doing

I'm a newbie in java. I was going through some tutorials and came across this code I was not able to understand the code. Please explain what it means.
class Randoms
{
public static void main(String[] args)
{
Random rand = new Random();
int freq[] = new int[7];
for(int roll = 1; roll < 10; roll++)
{
(++freq[1 + rand.nextInt(6)]);
}
...
Line by line:
Random rand = new Random(); create new instance of the Random object, this is responsible for the creation of random numbers.
int[] freq = new int[7]; create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java, the ints stored in the array are initialized to 0. (This is not true for all languages, an example being C, as in C the int arrays initially store memory junk data, and must be explicitly initialized to zero).
for(int roll = 1; roll < 10; roll++) this rolls 9 times (because 1...9, but it's better practice to go from 0)
(++freq[1 + rand.nextInt(6)]); this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.
Do something like this:
for(int roll = 0; roll < 9; roll++)
{
int randomNumber = rand.nextInt(6); //number between 0...5
int index = 1 + randomNumber; //number between 1...6
freq[index]++; //increment the number specified by the index by 1
//nearly equivalent to freq[index] += 1;
}
So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.
Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.
So in the end, if you say:
for(int i = 1; i <= 6; i++)
{
System.out.println("Thrown " + freq[i] + " times of number " + i);
}
Then it will be clearly visible what's happened.
(++freq[1 + rand.nextInt(6)]); // this line of code.
The above line of code is pre-incrementing the value of freq[] array at the specified position,i.e., 1+rand.nextInt(6) --- referred value is ++freq[some-position to be evaluated] which we will evaluate below.
This rand.nextInt(6) will generate an integer number lesser than 6 and greater than 0,as it is a pre-defined method of Random Class ,randomly.We can't predict it.
And,then say number generated is 4. SO, 1+rand.nextInt(6)=5.
Hence,your code would simplify to (++freq[1 + rand.nextInt(6)]) OR `(++freq[5]).
So,simplification of this code will be equivalent to a number which equals 1 more than 6th element of array freq[].
// as freq[5] is the 6th element of the array freq[].
Also,there are some other points which SIR David Wallace suggested me to include which I would like to explain a bit more.It goes below :-
++a here ++ is called pre-increment operator and it increases the value of a by 1. There also exists an altered reverse version of it.
a++ here this ++ is called post-increment operator and it also increases the value of a by 1.But,WAIT,you might have thought that there aren't differences,but there are.
For the differences potion,I'd like to suggest to have a reading of What is the difference between pre-increment and post-increment in the cycle (for/while)?, though it is questioned in sense of C++,the same is in Java too!
// Create a new Random Object, this helps you generate random numbers
Random rand = new Random();
// create a integer array with 7 integers
int freq[] = new int[7];
// loop 9 times
for(int roll = 1; roll < 10; roll++)
{
// rand.nextInt(6) generates a number between 0 and 5 (<6). add one to it
// ++ adds one to the integer in the array that is at the index of 1-6.
(++freq[1 + rand.nextInt(6)]);
}
Some strange things about this code:
Roll loop starts at 1 then goes to 10 so at first glance it would seem to loop 10 times but actually runs 9 times.
The ++ inside the loop would generally be located on the right and could lead to some confusion among newer programmers.
freq[1 + rand.nextInt(6)] causes freq[0] to never be used.
At first a new object of the Random-Class and an array with 7 elements are created. Each element of the Array has the value 0. Inside the for-loop you randomly pick element 2 to 7 of the Array and increase its current value by 1. This is done 9 times.
Your code will never pick the first element of the Array which has the index 0.
I would rewrite the code to make it more clear:
Random rand = new Random();
int freq[] = new int[6];
int randomIndex = 0;
for(int roll = 0; roll < 9; ++roll)
{
randomIndex = rand.nextInt(6);
freq[randomIndex] = freq[randomIndex] + 1;
}
This code has not been tested, but it should basicly do the same.

How can we use array elements as a counters in java?

import java.util.Random;
public class DemoArrayElement {
public static void main(String arg[]) {
Random rand = new Random();
int[] freq = new int[7];
for (int roll = 1; roll < 10; roll++) {
++freq[1 + rand.nextInt(6)];
}
System.out.println("FACE\tFREQUENCY");
for (int face = 1; face < freq.length; face++) {
System.out.println(face + "\t\t" + freq[face]);
}
}
}
Can someone please explain me this ++freq[1+rand.nextInt(6)]; line of code.
This program simulates rolling a die 10 times. The array freq is used to count the frequencies each face value is rolled - the index represents the face value and the content the number of times it was rolled. So, e.g., freq[3] contains the number of times 3 was rolled.
Let's take a look at ++freq[1+rand.nextInt(6)]; and take it apart:
rand.nextInt(6) calls Java's random number generator (a java.util.Random instance) and asks it for a uniformly distributed random number between 0 and 5 (inclusive). Adding 1 to it gives you a random face value form a die - a number between 1 and 6.
Accessing this index in the freq array (freq[1+rand.nextInt(6)]), as noted above, will return the number of times this face value was randomly encountered. Since we just encountered it again, this number is incremented (the ++ operator).
frec is an array containing 7 numeric elements.
++freq[1+rand.nextInt(6)]; means pre-increment a random element from an array.
Example: if the second element from the array is 5:
++freq[1]; will make it 6.

What is the best way to create a random value?

I am triying to create random value for my game to show enemies on screen. BUt it some times shows 2 together some times 3 ...I want to ask that which is the best formul for creating random value.. This is my so far random value
random = 1 * (int) (Math.random() * 100);
"BUt it some times shows 2 together some times 3"
Given perfectly random numbers... In every 100 random values from 0 to 99, you'll find an average of 1.0 doubles. A triple will occur on average once for every 10,000 values. Given 10 million random numbers, java.util.Random yeilds the following results on my machine:
Doubles: 99873
Triples: 985
Double Rate: 1 in 100
Triple Rate: 1 in 10152
Source code:
import static java.lang.System.*;
import java.util.Random;
public class Sandbox {
public static final int NUM_ITERATIONS = 10000000;
public static void main(String[] args) {
Random rand = new Random();
int cur;
int last = -1;
int secondLast = -2;
int nDoubles = 0;
int nTriples = 0;
for (int i = 0; i < NUM_ITERATIONS; i++) {
cur = rand.nextInt(100);
if (cur == last) {
nDoubles++;
if (cur == secondLast) nTriples++;
}
secondLast = last;
last = cur;
}
out.println("Doubles: " + nDoubles);
out.println("Triples: " + nTriples);
out.println();
out.println("Double Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nDoubles));
out.println("Triple Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nTriples));
exit(0);
}
}
Actually the creation of genuinely random random numbers is a complex game in its own right. The Wikipedia article on this subject will give you an insight into the complexity that lies therein. Simple approximations such as those outlined above are probably sufficient for game purposes but will, it should be noted, be inclined to be 'streaky' from time to time.
You can use java.util.Random:
Random random = new Random(); // uses System.nanoTime() as seed
int enemies = random.nextInt(100);
Anyway, your approach is also fine, as it is in fact equivalent (behind the scene) with the above.
You can print a sequence of 100 random numbers generated your way and see for yourself that there isn't a problem.
What you use if perfectly fine.
In case you want something simplier you might like to use Random class like this:
Random generator = new Random(seed);
int number = generator.nextInt(100);
...and sometimes 77, sometimes 23, etc, as expected in a uniform distribution?
If you would like a normal distribution instead for your "enemies", so that extremes are less likely, it seems to be there in Java.

Categories

Resources