# Math: Splitting amounts

How can I split amounts into smaller parts, avoiding float numbers, while maintaining the unaltered total amount?

Eg:
Splitting 47 into 2 parts

Part 1: 24
Part 2: 23

This case preserves the total value while dividing it into smaller parts.

In my case, value splitting differs from division in that it does not guarantee that all parts will receive the same value, but that the integrity of the total value is maintained while having no float numbers.

Not sure whether I completely understand what you want since the banana allegory is mildly confusing. If you just want to find a way of equally dividing a number into n parts with a possible remainder:

``````local num = 47
local n = 2

local div = math.floor(num/n)
local remainder = num%div
local int = 1

local tab = {}

for i=1,n,1 do
if remainder==0 then
int = 0
end
tab[i] = div+int
remainder-=1
end``````

The value returned is the same as when using the math.ceil() function, 48.
As I mentioned, I cannot allow any loss or gain in the total value, but thank you for trying to help me.

``````local function Split(stack: number, pieces: number): {number}
local floor = math.floor(stack / pieces)
local Result = {}

repeat
stack -= floor
table.insert(Result, floor)
until (stack < floor) or stack == 0
if stack ~= 0 then
Result[#Result] += stack
end

return Result
end

print(unpack(Split(47, 2))) -- 23 24
print(unpack(Split(64, 16))) -- 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4
print(unpack(Split(50, 3))) -- 16, 16, 18
``````
1 Like

I posted pseudo code, so could have errors. Though I tested the code and it worked for me.

``````print(tab) --where n is 5
{
[1] = 10,
[2] = 10,
[3] = 9,
[4] = 9,
[5] = 9
}
-- total = 47
``````

This is true, I was mistaken, probably because I had just woken up. Thank you for the help.

For anyone who has the same problem as I did, i â€śbeautifiedâ€ť his code for you all.

Code:

``````function divideQuantity(quantity, times)
local division = math.floor(quantity/times)
local remainder = quantity%division

local int = 1
local table = {}

for i = 1, times, 1 do
if remainder == 0 then
int = 0
end
table[i] = division+int
remainder = remainder -1
end

return table
end

local test = divideQuantity(47,5)
local total = 0

for i,v in pairs(test) do
total = total +v
print(i,v)
end

print("Total: "..total)
``````

Output:

``````{
[1] = 10,
[2] = 10,
[3] = 9,
[4] = 9,
[5] = 9
}
Total: 47
``````

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