Question

Say I have a limit of 5 meaning values from 0,1,2,3,4,5

The difference from (5 to 0) or (5 to 0) is 1
The difference from (5 to 1) or (1 to 5) is 2
The difference from (0 to 4) or (4 to 0) is 2

The way I seem to understand this is to only use the overwrap difference if the last value or the first value is used in any of the values. Other then that the normal ones that work with Math.abs should be fine

Such as Math.abs(1-3)
The difference from (1 to 3) is 2
The difference from (3 to 4) is 1

I can't seem to understand how to program the overwrap difference part.

I tried this but it's nothing special, I think something with modulus operator will work but I can't seem to figure it out

int value_one = 0;
int value_two = 5;

int answer = Math.abs(value_one - value_two);
answer = (((answer % 5) + 5) % 5) + 1;
System.out.println(answer);
int answer2 = (value_one + value_two) % 5;
System.out.println(answer2);
Was it helpful?

Solution

int v1 = Math.min(value_one, value_two);    
int v2 = Math.max(value_one, value_two);
int answer = Math.min(v2 - v1, v1 + values.length - v2);

where values.length is the length of {0, 1, 2, 3, 4, 5} which is 6.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top