How do I randomly divide an integer into any amount of random parts?

I’m looking for a way to effeciently divide an integer into any number of random but similar parts.

For example, if my number was 1,000,000, I’d want a function that would look like this:

local function divideNumber(1000000, 8) -- argument 1 is number to divide, argument 2 is number of parts

That would return something like this:

{74325, 108432, 88532, 234803, 53892, 97104, 164273, 178639}

I’ll spare you the math, the sum of all those numbers is 1,000,000.

I think there may be a way to generate numbers this way, but sadly I don’t know what that is. Any help is appreciated. Thanks in advance

It’d be a hassle to retrieve my code for this, but I’m believing you can code a normalize function yourself.

Anyways, you multiply it by a random number from 0 to 1, put it in a table, and then normalize all the values. Then, you multiply it by the original value (in your case, 1e7) to get your normalized version, which should be what you want (but in decimal form).

I actually have no idea what normalize functions are (let alone know how to program one). Is there any other approach that can be taken?

Not that I know of. Luckily, I do have the resource available for you, at the cost of your soul nothing:

Code Snippet of my WeightService module:


function WeightService.normalize(weightTable)
	local sum = 0
	local normalized = {}
	for index, weight in ipairs(weightTable) do
		sum += weight
	end
	for index, weight in ipairs(weightTable) do
		local newWeight = weight / sum
		normalized[index] = newWeight
	end
	return normalized
end

weightTable is a table of weights, or numbers. In your case, you’d get a certain amount of random numbers like .2, .5, .9, .5353245, .999 (you get the point). Then, you’d normalize it, which would make it add up to one. With the normalized table, multiply the values by the original number, which in your case, is one million.

1 Like

Thank you! I was able to transform your code into what I was looking for.

function normalize(t)
	local sum = 0
	local normalized = {}
	for index, weight in ipairs(t) do
		sum += weight
	end
	for index, weight in ipairs(t) do
		local newWeight = weight / sum
		normalized[index] = newWeight
	end
	return normalized
end

function divideNumber(num, amount)
	local t = {}
	for i = 1,amount do
		table.insert(t,math.random(1,10000))
	end

	local randomNumbers = normalize(t)
	local result = {}
	for i = 1,#randomNumbers do
		table.insert(result,(randomNumbers[i] * num))
	end
	
	return result
end

print(divideNumber(1000000,8))

I’m sure there’s a more effecient way to multiply all the numbers in the tables, but that’s something I can figure out myself. Thanks again!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.