Page 1 of 1
Strange cell values in 2d array with the help of random
Posted: Mon May 11, 2015 6:11 pm
by Pixelwar
I wanted to fill a grid with about 50% true and 50% false. This I do with random(100). Then I draw the grid on the screen, so I think the grid was filled nearly with same amount of false and true, but every time I tested the code the amount of true was giant compared with the amount of false.
I tried very long to fix the problem, but I found no solution.
Re: Strange cell values in 2d array with the help of random
Posted: Mon May 11, 2015 6:28 pm
by Ranguna259
Everything looks alright except two things:
You don't need to do
There's no need to do that. And second, the problem is in your draw code, you are multiplying the sides of your rectangle by x and y, replace:
Code: Select all
love.graphics.rectangle("fill", 7 * (x - 1), 7 * (y - 1), 7 * x, 7 * y)
with:
Code: Select all
love.graphics.rectangle("fill", 7 * (x - 1), 7 * (y - 1), 7, 7)
FYI: You don't realy need to do math.random(100), all you need to do is math.random(0,1) this will output 0 or 1.
Here's a fixed love file:
Re: Strange cell values in 2d array with the help of random
Posted: Mon May 11, 2015 6:35 pm
by arampl
You can control the amount of random values using "shuffle" of pre-generated values. For example if you want 50% true and 50% false values you can achieve it like this:
Code: Select all
local rnd = {}
function shuffle(t)
local n = #t
while n >= 2 do
-- n is now the last pertinent index
local k = love.math.random(n) -- 1 <= k <= n
-- Quick swap
t[n], t[k] = t[k], t[n]
n = n - 1
end
end
function love.load()
for i = 1, 50 do
rnd[i] = true
end
for i = 51, 100 do
rnd[i] = false
end
end
function love.keypressed(key, isRepeat)
if key == "escape" then
love.event.quit()
elseif key == " " then
shuffle(rnd)
print("*****************************")
for i = 1, #rnd do
print(i, rnd[i])
end
end
end
Re: Strange cell values in 2d array with the help of random
Posted: Mon May 11, 2015 6:39 pm
by Pixelwar
Thanks, I'm stupid
, because I thought that the love.graphics.rectangle works after the pattern x1,y1,x2,y2 and not after x,y,width,height.
EDIT: And thanks for the tip @arampl