My problem is that I need to produce a random number, which is fine I've done that part, but then I need to use that random number to loop.
So for example if the random number was 13, then loop a piece of code 13 times.
I've had a mess around and haven't managed to get anything working and haven't been able to find anything online to help me.
Basically what I'm trying to find out if this is even possible?
thanks guys.
This is a simple for loop:
for (int i = new Random().nextInt(); i > 0; i--) {
// do stuff
}
This is pretty basic Java. You have a number that you get once you randomize. Just use it in a while loop or a for loop.
int x = GetRandomNumber(); //You have stated you have already done this...
for(int i = 0; i < x; i++){
//Do stuff here
}
Here you go:
Random random = new Random();
int a = random.nextInt(); // As you said, you got this so far...
while (a > 0) { // if you need your random number for something, just copy its value to new variable and place it here instead of a
// some code
a--;
}
Related
Hello everyone I have this command:
for (z = 0; z < utenti.length; z++) {
utenti[z] = rand.nextInt(1000) + 1;
}
After it's done generating random numbers between 1 and 1000 I want it to stop, the command is one of the functions in my program, but everytime i recall it the numbers generete randomly again. Is there a way to stop the random generation after the first time?
Is there a way to stop the random generation after the first time?
Yes. Don't execute that code after the first time. For example:
if (firstTime) {
for (z = 0; z < utenti.length; z++) {
utenti[z] = rand.nextInt(1000) + 1;
}
firstTime = false;
}
I you don't want to run the piece of code twice, then why are you calling it twice?
Since this piece of code is required to be executed just once, it probably is in the wrong place. It perhaps belongs in a constructor or something, depending on your program structure.
You might just do what Stephen C did in his answer, using a boolean to keep track of whether it's the first time or not. That might be the simplest option for you.
In addition to the other answer, also note that one the constructors of the Random class accepts a seed. If you keep the seed the same, the sequence of pseudo-random numbers will be the same. This saves you the memory usage of the utenti array, especially with large arrays.
private long seed;
private void determineSeed() {
long seed = new Random().nextLong();
}
And then use:
Random rand = new Random(this.seed);
for (int i = 0; i < utenti.length; i++) {
int number = rand.nextInt(1000) + 1);
// Don't save it to an array, do something with number
}
A drawback is that you cannot usage specific element of the sequence (for example, utenti[i]), you must use the random numbers in sequence.
I have six counters that need to be reset at a certain point of the program. I guess it is possible with a for loop? Thanks in advance
int counters[] = {score,count1,count2,count3,count4,count5};
for(int i=0; i<counters.length; i++) {
findViewById(counters[i]); //...and it resets them all?
}
score = R.id.score;
count1 = R.id.count1;
//etc.
If your integers has these numbers of resources, yes it is going to work.
So I'm working on a program which is supposed to randomly put people in 6 rooms (final input is the list of rooms with who is in each room). So I figured out how to do all that.
//this is the main sorting sequence:
for (int srtM = 0; srtM < Guys.length; srtM++) {
done = false;
People newMove = Guys[srtM]; //Guys is an array of People
while (!done) {
newMove.rndRoom(); //sets random number from 4 to 6
if (newMove.getRoom() == 4 && !room4.isFull()) {
room4.add(newMove); //adds person into the room4 object rList
done = true;
} else if (newMove.getRoom() == 5 && !room5.isFull()) {
room5.add(newMove);
done = true;
} else if (newMove.getRoom() == 6 && !room6.isFull()) {
room6.add(newMove);
done = true;
}
}
The problem now is that the code for reasons I don't completely understand (something with the way I wrote it here) is hardly random. It seems the same people are put into the same rooms almost every time I run the program. For example me, I'm almost always put by this program into room 6 together with another one friend (interestingly, we're both at the end of the Guys array). So how can I make it "truly" random? Or a lot more random than it is now?
Thanks in advance!
Forgot to mention that "rndRoom()" does indeed use the standard Random method (for 4-6) in the background:
public int rndRoom() {
if (this.gender == 'M') {
this.room = (rnd.nextInt((6 - 4) + 1)) + 4;
}
if (this.gender == 'F') {
this.room = (rnd.nextInt(((3 - 1) + 1))) + 1;
}
return this.room;
}
if you want it to be more random try doing something with the Random method, do something like this:
Random random = new Random();
for (int i = 0; i < 6; i++)
{
int roomChoice = random.nextInt(5) + 1;
roomChoice += 1;
}
of course this is not exactly the code you will want to use, this is just an example of how to use the Random method, change it to how you want to use it.
Also, the reason I did random.nextInt(5) + 1; is because if random.nextInt(5) + 1; gets you a random number from 0 to 5, so if you want a number from 1 to 6 you have to add 1, pretty self explanatory.
On another note, to get "truly" random is not as easy as it seems, when you generate a "random" number it will use something called Pseudo random number generation, this, is basically these programs produce endless strings of single-digit numbers, usually in base 10, known as the decimal system. When large samples of pseudo-random numbers are taken, each of the 10 digits in the set {0,1,2,3,4,5,6,7,8,9} occurs with equal frequency, even though they are not evenly distributed in the sequence.
There might be something wrong with code you didn't post.
I've build a working example with what your classes might be, and it is distributing pretty randomly:
http://pastebin.com/u8sZRxi6
OK so I figured out why the results don't seem very random. So the room sorter works based on an alphabetical people list of 18 guys. There are only 3 guy rooms (rooms 4, 5 and 6) So each guy has a 1 in 3 chance to be put in say, room 6. But each person could only possibly be in 2 of the 6 spots in each room (depending on where they are in the list).
The first two people for example, could each only be in either the first or second spot of each room. By "spot" I mean their place in the room list which is printed in the end. Me on the other hand am second last on the list, so at that point I could only be in either the last or second last spot of each room.
Sorry if it's confusing but I figured out this is the reason the generated room lists don't appear very random - it's because only the same few people could be put in each room spot every time. The lists are random though, it's just the order in which people appear in each list which is not random.
So in order to make the lists look more random I had to make people's positions in the room random too. So the way I solved this is by adding a shuffler action which mixes the Person arrays:
public static void shuffle(Person[] arr) {
Random rgen = new Random();
for (int i = 0; i < arr.length; i++) {
int randPos = rgen.nextInt(arr.length);
Person tmp = arr[i];
arr[i] = arr[randPos];
arr[randPos] = tmp;
}
}
TL;DR the generated room lists were random - but since the order of the people that got put into the rooms wasn't random the results didn't look very random. In order to solve this I shuffled the Person arrays.
static int n = -1;
private static int repeatBuffer[] = new int[10];
static {
repeatBuffer[0] = 0;
//and more
repeatBuffer[9] = 9;
}
static public void randomize() {
do {
Random r = new Random();
randomNumber = r.nextInt(20);
} while (!uniqueInt(randomNumber));
Log.e(TAG, "" + randomNumber); //here I need have a unique int
}
private static Boolean uniqueInt(int random) {
for (int i = 0; i < 9; i++) {
if (random == repeatBuffer[i]) {
return false;
}
}
if (++n > 9)
n = 0;
repeatBuffer[n] = random;
return true;
}
Sometimes I'm getting same int twice, I'm wondering where is the problem? And is it even work? I spend quite a lot of time on this, and I give up. I think I need some minor tweaks in code :)
An easier way to get a random int is to create a List of integers List<Integer>, adding it with numbers that you would like to have. Then shuffling the List using Collections.shuffle(list);. Now start reading from the beginning of the list and you will get a unique random int each time.
Just make sure that each time you "read" a number from the list, either remove it from the list or increase the index for where you read.
That's the normal behavior of a random number generator, it's correct to generate repeated numbers as long as the number distribution remains uniform.
If you need a set of unique random numbers, you can generate them inside a loop and ask at every iteration if the newly generated number is present in the set of generated numbers. If not, add it, if yes, keep iterating - until the set has the desired size.
Er, a unique random between 1 and 20? What happens when it runs the 21st time?
Try making a List of the Integers between 1 and 20. Use Collections.shuffle() to shuffle the list. Then pop the first item off the front of the list and use that.
Im trying to write a game of Yahtzee as part of an online course (not actually enrolled, just playing along at home) I have hit a bit of a wall manipulating values in the array that keeps track of the dice values. This is the section of code that seems to be causing trouble;
for (int i=0; i<N_DICE; i++){ //goes through each die.
if (display.isDieSelected(i) == false){ //checks if player wants to reroll the die.
dice [i] = dice[i];//problem line-should reassign the same value back to the die.
}
else {
dice [i] = rgen.nextInt(1, 6);
}
}
Assigning a new random number works, and if I roll all 5 dice every turn its happy.
I've changed the offending line to dice[i]=1 for testing purposes and while it takes some fun out of the game, the program works, so I'm thinking its something simple I'm doing wrong with that line.
I've tried assigning dice[i] to a temp variable (inside and out of the if loop) and then assigning temp back to dice[i].
I've tried just leaving the if loop empty.
I've tried setting it up as a multi dimesional array with a seperate array for each roll.
I've tried adding a cast (didnt think that'd do it but I was out of ideas).
All of these have had the same results.
Only been programming a few weeks, I'd be very gratefull if someone could tell me what I'm doing wrong.
Not sure what you're trying to do with that line:
dice[i] = dice[i];
Since it's a NOP, why not just omit it?
I don't really see the purpose of:
dice[i] = dice[i]
Can't you just use something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i)){
dice [i] = rgen.nextInt(1, 6);
}
}
The code looks completely correct, although I would write it a bit more compactly:
for (int i = 0; i < N_DICE; i++) {
if (display.isDieSelected(i)) {
dice[i] = rgen.nextInt(1, 6);
}
}
So your problem probably lies somewhere else. Is dice a new array, or is it always the same in the program? If it is a field in some class, it should have the final modifier, like this:
public class YahtzeeState {
private final int[] dice = new int[N_DICE];
}
This declaration makes sure that the dice array cannot be replaced later with a completely different array. The values in the array can still be changed though.
How is the dice-array initialized? I don't know your entire code but I could imagine that it doesn't work because the dice-array gets it values only in this loop?
Maybe you should try something like:
for (int i=0; i<N_DICE; i++){
if (display.isDieSelected(i) || dice[i] == null)
dice [i] = rgen.nextInt(1, 6);
}