I have a math question which I try to solve with a Delphi function. I am trying to split up an integer into (nearly) equal pieces. Example:
You have 10 testcases and you want to execute them in 3 parts. So the best way to balance the workload would be to execute 3, 3, and 4 rather than 1, 1 and 8.
procedure calc_stream_numbers;
var div_res,rest:double;
total,streams:integer;
begin
total := 10;
streams := 3;
div_res := total DIV streams;
rest := total MOD streams;
showmessage('Items: ' +IntToStr(total)+#13#10+
'Streams: '+IntToStr(streams)+#13#10+
'Result: '+FloatToStr(div_res)+
'Rest: '+FloatToStr(rest));
end;
This gives me the division result of 10 / 3 = 3 (Rest 1) So I could execute 3 x 3 Testcases which makes 9 in total. To execute all 10 of them, I have to add the remaining one to any of the 3 streams. But If you have a more complicated example..
I am sure there is a mathematical expression for this but I must admit, I have noe clue. Maybe you are able to enlighten me how such a division is called and if there is any built-in delphi function.
You can code it like this:
You have
Total
units to split up intoCount
parts. We start withTotal div Count
for the first item. Then we haveTotal - (Total div Count)
units left which need to be split intoCount - 1
parts. Continue in this way until there's nothing left to do.This algorithm could easily be written in a recursive way, but the iterative approach above somehow seems simpler to me.
Your entire approach assumes that you can predict ahead of time how long each task will take. But what if, for whatever reason, some tasks take longer than others? Then your approach will not be efficient. A better approach is to have a threadsafe queue of tasks. Let each consumer pull tasks off the queue and process them until there are no tasks left.