[General Java] Random.nextInt() having a very obvious pattern?

Hello,

I’ve been working on a system of randomly generating a level. The code can be found here. http://pastebin.com/4eddVXE8

The issue I’m having at the moment is illustrated in this screenshot. The generation appears to be happening in diagonal lines. How could this be fixed so that the generation is truly random?

Any help is greatly appreciated.

x + y * width and not x + y

If you meant that in the index for tiles[] in the getTile method, it throws an ArrayIndexOutOfBoundsException. int tiles[] is declared with a size of width * height.

                for(int x = 0; x < width; x++){
                        for(int y = 0; y < height; y++){

this will probably fix the array out of of bounds error when using what trollwarrior said.


int getTile(int x, int y){
     if(x < 0 || x >= width || y < 0 || y >= height) return 0;

     return tiles[x + y * width];
}

EDIT-
what liquid said should fix it.

That worked, thanks! :smiley:

you might find it easier using a 2d array for your map anyway… its generally more intuitive to work with.

There are generally very few reasons to “flatten” a 2D array into a 1D array. Damn, theCherno has taught a lot of people some bad coding practices… Just stick with 2D arrays.

There are lots of good reasons not to use 2D arrays, especially if they are small. You can easily abstract it all away with a point-to-index and a index-to-point function.

Fair enough, can you give me some reasons? From what I’ve read the differences (except for in large arrays) are negligible.

There was a recent discussion (including benchmarks, oh my) here: http://www.java-gaming.org/topics/is-there-a-logical-reason-to-stuff-2d-array-data-into-one/33042/view.html

Actually small arrays are affected the most, however they also take the least time to process, so yes, it’s usually only worthwhile to optimize large arrays.
It’s mostly a matter of cache-aware programming. Make of it what you will.

Thanks! Interesting stuff.

That thread was microbenchmarks and doesn’t consider generalized real access patterns in time. nD arrays are significantly slower in practice. The math tells you so. It also doesn’t consider the exponential increased burden on the GC which in turn effects overall (not localized) performance. If overall performance isn’t a concern it doesn’t matter so much.

(EDIT: Since this is a newbie post, something no mentioned in the linked thread is that in the microbenchmark the memory layouts of the 1D and 2D are virtually identical since the 2D array is allocated before any GCs occur).