I have a list of items, each of which has a rank associated to it.
Item 1, Rank=1
Item 2, Rank=2
Item 3, Rank=3
Item 4, Rank=4
Item 5, Rank=5
I want to design a method which handles re-ranking of items with minimal or no changes to the ranks of other items.
One solution I thought of was to leverage decimals and use Java's double variable type. So for example if I move item5 between item2 and item3, this would be the output -
Item 1, Rank=1
Item 2, Rank=2
Item 5, Rank=2.5
Item 3, Rank=3
Item 4, Rank=4
And so on,
Item 1, Rank=1
Item 2, Rank=2
Item 4, Rank=2.25
Item 5, Rank=2.5
Item 3, Rank=3
This solutions works, but after some point (~55 moves at the same position, I reach the double variable limit and i will probably have to reset all ranks at that point)
I was just wondering if there is some better way to solve this problem?
A few things to keep in mind.
What about writing a small routine that evenly distributes the rank values of a range of elements in the array (or list or whatever)?
If you insert a new element at position x you pass the elements of range x-1 .. x+1
into the subroutine. the rank values at start and end position stay the same, the others are calculated with even distance. If successful, return true. Now, if the distance gets too small you return false, the caller extends the range to x-2 .. x+2
and goes into the subroutine again.
You'd have to take care about hitting array boundaries or even running out of value-space altogether.