Thursday, 15 January 2015

lua - Divide n into x random parts -



lua - Divide n into x random parts -

what need accomplish x dice rolls = n sum backwards.

so let's create example:

the dice has rolled 5 times (min. sum 5, max. sum 30) means:

x = 5

let's in case sum rolled 23 means:

n = 23

so need of possible single dice roll combinations (e.g. 6, 4, 5, 3, 5)

what create in mind far is:

create 5 random numbers. add them , sum. now split every single random number sum , multiply wanted number 23. the result 5 random numbers equal wanted number 23.

the problem 1 returns random values (decimals, values below 1 , above 6) depending on random numbers. can not find way edit formula homecoming integers >= 1 or <= 6.

if don't need scale far easiest way re-randomize until right sum. takes milliseconds on modern cpu. not pretty tho.

#!/usr/local/bin/lua math.randomseed(os.time()) function divs(n,x) local = {} repeat local s = 0 i=1,x a[i] = math.random(6) s = s + a[i] end until s==n homecoming end = divs(23,5) k,v in pairs(a) print(k,v) end

random lua numbers dice divide

No comments:

Post a Comment