This is exactly the bin packing problem. It is also NP-Complete, and thus there is no known polynomial solution (and the general assumption is one does not exist, but it is not proven yet).
The problem is widely studied if you are looking for approximation algorithm, or a relatively efficient exact algorithm
PS - the random approach you suggest will get you a solution, but it won't be OPTIMAL.
Counter example:
arr = [2,3,4,1] , size=5
A possible solution to your algorithm could be: select 3, select 1, select 4, select 2
, which will yield:
[3,1],[4],[2]
While the optimal solution will be [3,2],[4,1]
(-) I believe a greedy approach (chose the highest, put it in an available bin - if it fits, and if it doesn't - "open" a new bin) will do better then the randomized solution but will still be not optimal, with the counter example:
arr = [5,4,4,3,2,2] size = 10
greedy will yield [5,4],[4,3,2],[2]
while optimal is [5,3,2],[4,4,2]
Regarding the loss pf precision - it happens because Math.floor(double)
yields a long
, while you use it as an int
(and you might theoretically lose data when doing so). However, it is not a problem in your case since Math.floor(Math.random() * input.length
is guaranteed to be in the range of an int
because input.length
is an int and Math.random() < 1
.