Results 1 to 3 of 3
- 11-26-2012, 12:32 PM #1
Member
- Join Date
- Nov 2012
- Posts
- 1
- Rep Power
- 0
Generate random numbers that haven't been generated before.
Hello,
I'm relatively new to Java and programming, and I've come accross a problem.
I'm having a 2-dimensional array which holds an Object.
The DataItem class has only two variables a x and a y value.Java Code:public DataItem[][] dataTiles = new DataItem[tileWidth][tileHeight];
Each array index stands for a position in the world, so if you would have a DataItem with x = 4 and y=32 then it's place in the array would be: dataTiles[4][32].
The position of the dataItem is randomly generated:
However the problem is that there is a change that there are two data items at the same coördinates.Java Code:int randX = (int)(Math.random()*tileWidth); int randY = (int)(Math.random()*tileHeight); DataItem dat = new DataItem(randX, randY); dataTiles[randX][randY] = dat;
This is not allowed to happen, so these randX and randY variables can only be a empty place in the world.
Could anybody point me in the right direction of how to do such a thing?
P.S. I hope that I made the problem clear if not just ask :)Last edited by Dirk94; 11-26-2012 at 12:34 PM.
- 11-26-2012, 02:59 PM #2
Re: Generate random numbers that haven't been generated before.
Sounds like you're going to have to keep track of which coordinates you've already used, then check against it when creating a new one. Or you could go the other way around and start out with a collection of valid locations, then remove them or mark them as invalid as you place coordinates.
How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 11-26-2012, 04:07 PM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,484
- Rep Power
- 16
Re: Generate random numbers that haven't been generated before.
I think we've had something like this before, and one solution was a List<Coordinates> (in your case), and using Collections.shuffle().
Then simply iterate over the shuffled list, assigning DataItems to the coordinates.Please do not ask for code as refusal often offends.
Similar Threads
-
Store a random generated int value in an array.
By kcon90 in forum New To JavaReplies: 5Last Post: 10-26-2012, 09:31 PM -
Generate weighted random numbers, nextGaussian ()
By graympa in forum New To JavaReplies: 2Last Post: 03-25-2011, 09:36 PM -
generate pseudo random numbers in java
By csr81 in forum Advanced JavaReplies: 3Last Post: 03-01-2010, 07:08 AM -
How do I generate random numbers in a certain range using the random class?
By frasifrasi in forum New To JavaReplies: 8Last Post: 04-19-2009, 05:50 PM -
[SOLVED] auto generated numbers
By suprabha in forum Advanced JavaReplies: 10Last Post: 08-14-2008, 05:13 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks