Log In  

These are variations of the rnd() function, but these return integers. You can either give just a maximum value or an arbitrary minimum and maximum value. You can also choose whether you want the maximum value to be exclusive or inclusive.

--random int between 0,h
function rand(h) --exclusive
    return flr(rnd(h))
end
function randi(h) --inclusive
    return flr(rnd(h+1))
end

--random int between l,h
function randb(l,h) --exclusive
    return flr(rnd(h-l))+l
end
function randbi(l,h) --inclusive
    return flr(rnd(h+1-l))+l
end
P#41116 2017-05-29 17:48 ( Edited 2017-05-29 21:48)

Thank you! This was really helpful.

P#62004 2019-02-18 00:00

Excellent stuff @MBoffin - will definitely save having to think this out every time (and no-doubt fixing bugs coz I won't get it right first time!).
Thanks buddy! ;-)

P#62031 2019-02-18 14:57

Ha, wow. This is really old. :D Now that it's been about 2 years (!) since I posted this, I can honestly say the one of these four that I use the most by far is the inclusive random integer function. To the point where that's often the only variation I'll put in my code.

Glad these were useful. :)

P#62040 2019-02-18 17:07

May I publish some or all of your code, or derivatives, in https://github.com/sparr/pico8lib ?

P#72829 2020-02-06 20:38

@sparr Go for it.

P#72969 2020-02-10 17:40
2

Hi @MBoffin. Gold star for this information !

Here is a variation I use that ensures no matter the order the input, you still get the correct results.

-- return random # from a to b
function rand(a,b)
  if (a>b) a,b=b,a
  return a+flr(rnd(b-a+1))
end--rand(..)

INPUT: two numbers
RETURNS: integer number including and between both numbers.
USES:
print rand(1,6) ... dice
print rand(1,52) ... pick a card
print rand(9,-4) ... will pick # including and between negative 4 and positive 9.

P#72971 2020-02-10 19:14 ( Edited 2020-02-10 19:31)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-28 19:55:57 | 0.020s | Q:21