Ok, the example doesn’t matter. I was just using it to put it in context. But basically i am wondering how to take a random value from an array/arraylist?
I tried using this: int random = (int)input[Math.floor(Math.random() * input.length)];
but it highlights potential loss of precision even though i’ve already cast it.
Have i cast it wrong?
The example is irrelevant really and i do accept answers to all my questions.
Initially i wanted to see a correct answer without influence from me to see if i was on the right track.
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:
A possible solution to your algorithm could be:
select 3, select 1, select 4, select 2, which will yield: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:
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 along, while you use it as anint(and you might theoretically lose data when doing so). However, it is not a problem in your case sinceMath.floor(Math.random() * input.lengthis guaranteed to be in the range of anintbecauseinput.lengthis an int andMath.random() < 1.