I'm trying to find a way of allowing a user to re-order an array of integers without duplication of values.
If the array is of size n, the values will range from 1 to n and each value can only appear once. (At the moment n=4, but that is likely to increase)
So 1,2,3,4 and 4,2,1,3 are valid but 1,2,3,1 and 1,4,4,2 are not.
When the user presses button_x, array[x] increases by 1. If the result exists later in the array, the later values need to be adjusted accordingly, without being greater than n.
For example, changing array[2] from Start to New, the array would end up as Adjusted.
Start New Adjusted
1,2,3,4 1,3,3,4 1,3,4,2
The closest I've go so far is this.
const int max = 4;
int array[max] = {1,2,3,4};
for (int i=0; i < max; i++)
{
for (int j=i+1; j < max; j++)
{
if (array[i] == array[j])
{
array[j]++;
if (array[j] > max) array[j] = 1;
}
}
}
This seems to work fine for a lot of situations, but certain combinations still result in duplicaiton.
Initially I thought the problem was if a change resulted in a duplicate at consecutive indexes, but the last sequence {3,4,1,2}, disproved that.
Start New Adjusted
1,2,3,4 1,3,3,4 1,3,4,1
1,2,3,4 1,2,4,4 1,2,4,1
4,2,3,1 4,3,3,1 4,3,4,1
4,3,2,1 4,3,3,1 4,3,4,1
4,1,3,2 4,1,3,3 4,1,3,4
4,1,2,3 4,2,2,3 4,2,3,4
3,4,1,2 4,4,1,2 4,1,2,3 << disproves my theory