Java Random: Seeding Problem - java

was wondering if you could help me out:
I have a method called initializeAll:
public final void initializeAll() {
//other stuff........
rand = new Random(353);
}
So I run the project and a GUI pops up, and some operations are carried out. When I press the "reset" button in my GUI, intializeAll is called again on the same class object. However, the operations that are carried out now are not the same as before, although they should be, since both times, a seed of 353 is being used on the newly created Random object. Why this difference? Am I doing something wrong?
EDIT: sorry, its not "some operations are carried out". its that some initialization of agent population takes place. and each time, the initialization is different, although the same seed is used.
private static int [][] initializePop(Random rand) {
int[][] temp = new int[ROWS][COLS];
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
temp[row][col] = rand.nextInt(12) - 5;
}
}
return temp;
}
SOLUTION:
sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. i'm redesigning the code now. so thanks again, and sorry for wasting your time.

Am I doing something wrong?
Yes, it seems so. The Random(long) should reset the seed to the provided value. What ever the error is, it will be impossible for us to help you without an SSCCE or at least more code.
Random rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
rand = new Random(353);
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
System.out.println(rand.nextInt(10));
Output:
7
5
5
7
5
5

sorry for taking your time guys. i figured out the problem. right now, my application is a mess of various threads, swingworkers, etc i.e. very "thready".. apparently the random is actually working fine. the problem is with the GUI display, which does some funny things and displays some interesting value. so this is more of a threading problem. so thanks again, and sorry for wasting your time.

Related

A counter that increases and decreases depending on other elements

Im trying to make a PlantsVSZombies game. The player has initially 50 suns in order to buy plants. I want to make a counter which decreases whenever I buy plants but also increases continously if I have sunflowers present. Any ideas how I could do it? And thank you.
In pseudocode:
int counter = 50;
if(....)
...
counter--;
else if (....)
...
counter++;
It would be easier for us if you displayed what code you have tried and what issues you encountered.
For the next time, try to add some information about your classes and how you are planning to write all your code. For this question and with this information you can try to just manage that with one Integer value:
int suns = 50;
public sunsCounter(bool increase){
if(increase){
this.suns +=1
}else{
this.suns -=1
}
I'ts just an idea and it's so basic, obviously, you have to create some classes to manage that and operate with this class objects.

Why is the emulator less random than my device?

I created a small app (as a project, with no plans to release it). Part of the code generates a grid of random numbers and and displays a grid using the sprite from a list with said number. It behaved as expected, at least on my Kindle Fire (and another device I tried it on).
The emulator, however, is a different story. I think the emulated device was a generic Samsung (4, maybe). The same code, when run on the emulator, fills about half the grid with one sprite, and half with a different sprite.
The grid might look like this on the emulator:
11177
11177
11777
11777
11777
instead of this on real devices:
64251
26253
87635
38415
28167
The relevant part of my code (yes, I should move new Random() elsewhere):
import java.util.Random;
// ... ... ...
for (int i = 0; i < GRID; i++) {
for (int j = 0; j < GRID; j++) {
paint.setColor(Color.parseColor("#FBB117"));
Random rand=new Random();
int num=rand.nextInt(8);
canvas.drawBitmap(bmp,frames[num],calcGridSpot(i,j),
paint);
//... Eventually closing braces:
}
}
I have had issues in the past, in Java, with Random deciding to be less random (I believe it might be due to optimizations).
Why is the emulator behaving less randomly? (And how do I fix it?)
I suspect your "yes, I should move new Random() elsewhere" remark is more accurate than you think.
You can find the source for Android's java.util.Random class; note the kitkat and lollipop/marshmallow versions are different.
kitkat:
public Random() {
// Note: Using identityHashCode() to be hermetic wrt subclasses.
setSeed(System.currentTimeMillis() + System.identityHashCode(this));
}
marshmallow:
public Random() {
// Note: Don't use identityHashCode(this) since that causes the monitor to
// get inflated when we synchronize.
setSeed(System.nanoTime() + seedBase);
++seedBase;
}
Note the change from millisecond-granularity time to nanosecond-granularity time. However, this change is only relevant if the emulated device actually has a clock that granular. Some emulators may have very coarse clocks, which means that System.nanoTime() could be returning the same value on every iteration of a reasonably fast loop.
You're creating new random number generators each loop, seeding them with N, N+1, N+2, and so on. Because the seeds are nearly identical, most of the bits in the first number output are identical.
If you pull the "new Random" out of the loop, not only will it be more efficient, it will allow the pseudo-random number generator to progress through its full sequence and give you better results.

How to add array list with Doubles

My assignment asks for me to add items to a shopping cart, asking the user for input. We are to use the add method but I keep getting an error. I have tried this for days, I have also searched the web and can't find an answer I understand.
List<Double> shoppingCart = new ArrayList<Double>();
shoppingCart.add(" ");
double shoppingCartItem;
shoppingCartItem = numberReader.nextDouble();
for (int counter = 0; counter <shoppingCart.size(); counter++) {
System.out.print("Item");
}
Any help would be greatly appreciated. Also, I am extremely new to java.
I realized what I was trying to do may not have been clear. This is how the completed program should look. I have been working on this for days. Any direction would be so appreciated. I am at a lost, everything I've done has made this worst.
![enter image1
The add(obj) function will add the given object to the list. So you should add your double variable to it. You don't need to add an 'empty' element beforehand (which is what I assume you were tying to do with the empty string?)
E.g
ArrayList<Double> shoppingCart = new ArrayList<Double>();
double shoppingCartItem;
shoppingCartItem = numberReader.nextDouble();
shoppingCart.add(shoppingCartItem);
for (int counter = 0; counter <shoppingCart.size(); counter++) {
System.out.print("Item");
}
Although it might be intimidating at first, its always a good idea to have a read of the docs when working with Classes and functions you arn't familiar with. For example here is information about the add() method.
And I'm guessing you'll probably want to use the retrieve the doubles in your list at some point, so have a read of the get() method.

Java - farkle (greed) game (die and player arrays, multiple classes)

I am trying to write code for a command like game of Farkle (greed). This is an Intro to computer science class. In a nutshell, you roll 6 die, and scores are based off of what you roll. Then you are required to remove the die that were used -> display score from that roll -> display total score -> ask if they would like to roll again. First player to a score determined by the user is the winner.
I have a bunch of code written for the model, and I am working on the view. I am struggling with the view, which makes it harder to advance on my model code. We are required to use the Die and Player classes (we were given those). I use the Die quickly, not quite sure how to apply the Player class.
When I try to run my command line, I am getting out of bounds errors on my rollCheck() array and other issues in my model that were not coming up when I simply was testing in main. I apologize for the amount of code posted, but I figure seeing everything makes it easier to solve (goes without saying really).
If anyone can give me pushes in the right direction to solving and making my program work, that would be great! Thank you.
Without being able to run the program to be sure its hard to be certain (I need the top of GreedGame) but i'd be fairly confident its the following:
in rollDie die is set to an array of ints on size remainingDie
this.die = new int [remainingDie];
later, within rollCheck the contents of the die array up to and including remainingDie, going over the array by 1
for (int i = 0; i <= remainingDie; i++) { // Count up quantity of die (6 set to remaining die)
if (die[i] == 1) {
this.numFreq[0] += 1;
}
....
....
}
So in short I believe i <= remainingDie; should be i < remainingDie; because an array with 6 entries has "boxes" 0,1,2,3,4,5

I would like the Arrays to remember it all

This is about my assignment so I would appreciate generic answers with explanation.
I have a for-loop which I have to make for an online ordering system. The for-loop and ordering all works fine but if the same item is put in twice, then it forgets the previous order for the same item and only remembers the latest one. I am required to use simple arrays and for-loops so I would appreciate if the solution/help was also of this basic level.
My code looks something like this (NOTE: The following is just an example of what part of the loop looks like--this is not a complete program):
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
int price = quantity[i] + itemcode;
}
}
To explain further, this loop and the if statement work perfectly if a certain item is only ordered once. But if the user enters, say, an order for a computer once and then after 3 more orders, orders another computer, then the output does not add the previous order in the new order but only remembers the latest one.
I would appreciate any work around suggested for this but again, since this is for my studies, I would appreciate explanations rather than direct solutions.
Please ask me questions in case this is not clear.
"Forgets" suggests that you are overwriting something in your code rather than, say, just incrementing. Go through your code, see what parts of it gets reset when you place a new order. For instance, if you are doing
quantity[1] = getNumberFromUser("How many apples?");
then this would obviously erase the old value each time. If you want to merely increment the number of apples, do something like
quantity[1] += getNumberFromUser("How many apples?");
Another general advice is to use print statements to debug your code. That way you can see for yourself what really happens. Learning to use a real debugger would also be of great benefit.
if you have two or more typres of products and want to calculate the price for all the orders together then you can try the following code,, i think thats very simple,,
int price=0;
for (int i = 0; i < 3; i++) { //I changed the loop so there's no confusion about
//what I am actually asking about.
if (order.equalsIgnoreCase(computer) {
price += quantity[i] + itemcode; //use the previous value of price
}
}
or else if you want to have history for each product separately then you have to try the same with a array of price for each product type..
If you cant get the answer then comment here,,

Categories

Resources