Page 1 of 1
[Solved] Math.random creates a weird pattern
Posted: Tue Jan 26, 2016 7:12 pm
by ZodaInk
I have no idea how this happens or even if this is a problem with Löve. While the pattern is almost random, it is not the kind of random I want.
Tell me if it works fine for you or if you find something in the code that is wrong.
The .love file creates a grid and every tile in that grid has a 90%(ish) chance of being a box, instead it creates this pattern...
The orange boxes are love.math.random(), the blue boxes are the regular math.random().
This is what it looks like when I run it:
I am genuinely confused...
Re: Math.random creates a weird pattern
Posted: Tue Jan 26, 2016 7:52 pm
by airstruck
Why are you storing the random locations in 2d arrays? Wouldn't it be much simpler to store coordinate pairs in a 1d array?
Code: Select all
for x = 0, math.floor(window.w / size) do
for y = 0, math.floor(window.h / size) do
if math.random() < 0.9 then
index[#index + 1] = { x = x, y = y }
end
end
end
Code: Select all
for _, pos in ipairs(index) do
love.graphics.rectangle("line",
pos.x * size + 2, pos.y * size + 2, size - 4, size - 4)
end
Re: Math.random creates a weird pattern
Posted: Tue Jan 26, 2016 8:00 pm
by ZodaInk
I usually would, don't know why I did it like this, but that is beside the point.
The point is that it doesn't create a noise-ish array of boxes, it's not even filling up anywhere near 90% of it.
Code: Select all
if math.random() < 0.9 then --[[code]] end
That should be true roughly 90% of the time, yet in my case it isn't.
Re: Math.random creates a weird pattern
Posted: Tue Jan 26, 2016 8:03 pm
by airstruck
It's not beside the point, though. If you write code that's simple and easy to understand, it's probably going to work and you don't have to spend time trying to figure out why it doesn't work.
- ss.png (13.51 KiB) Viewed 3109 times
Re: Math.random creates a weird pattern
Posted: Tue Jan 26, 2016 8:15 pm
by ZodaInk
That did fix it...
Now I am even more confused, why would this fix it?
Re: Math.random creates a weird pattern
Posted: Tue Jan 26, 2016 8:17 pm
by Xugro
Your idea of saving a sparse matrix is flawed. I just saved the full matrix and it works (see attached code). If you fill in 90% of the boxes then it is better to store the complete matrix.
Edit:
Rici Lake wrote:ipairs iterates over integer keys, starting from 1, until it finds one which is not in the table.
Source:
http://lua-users.org/lists/lua-l/2004-12/msg00311.html
And since you have a table where not all rows are present your drawing function will stop at that row and does not print the boxes below.