I need some help to change the following code.
I have a system with some workers, let's say 3. They can exchange some stuff between them, like work to do.
If worker1 decide to send some stuff to do to another worker, it has to see which worker has the minimun load of work,
asking to a coordinator which has the following method:
NB. index corresponds to the Id of the worker which has the minimum load.
What is my problem: in this way it may happen that a worker, let's say worker1,
want to send some stuff to do to another worker with the minimum load.
In that moment, worker1 has the minimum, load, so worker1 will send to itself
the stuff to do, and it is not correct.
So my question is: how to change to code above, to choose the worker with a minimum load,
without taking into account the worker which is asking for it?
Go through it very carefully with a pencil and paper, writing down the values, and what will happen under particular circumstances. Write down things like "if minimum load is greater than actual load . . . " Work out what the best starting value is to achieve this condition. Is it 0?
Take no notice of the above, which is all mistaken; I misread your original post.
I can see nothing wrong with that method. The problem is that you are not using it elsewhere. You should write a similar method to find the most loaded worker. You should also find their actual loads, so you can pass half the difference from one to another. Make no change to that method, but create a balanceLoad(int lightWorkerIndex, int overworkedWorkerIndex, int amountToTransfer) method and call that.
You can easily exclude the worker that is sending the load to another. You need to just pass the index of that worker to your method getLightest(). Just create a new array of worker excluding the worker that is sending the load and apply the same logic on this new array. e.g. I pass 'w' that the index of the worker.
Do not wait to strike till the iron is hot; but make it hot by striking....