major edit: 100% solved! it’s called Modular arithmetic thanks Peter!!
i need to add two numbers with a fixed min/max value.
i want my numbers behave like java’s int/byte/short (overflowing to its opposite value and continuing the operation)
System.out.println((byte) (Byte.MAX_VALUE)); // 127
System.out.println((byte)(Byte.MAX_VALUE + 1)); // -128
System.out.println((byte)(Byte.MAX_VALUE + 2)); // -127
System.out.println((byte)(Byte.MAX_VALUE + 3)); // -126
but with a fixed .MAX_VALUE and .MIN_VALUE. if a number’s value is 3 and it’s maxValue is 5 and minValue is 2, then when i add 4 to it (3+4=should be 7) it overflows
so 3+4: 3 -> 4 -> 5 -> 2 -> 3
example:
int value = 0, minValue = -2, maxValue = 1;
MyNumber n = new MyNumber(value, minValue, maxValue);
// possible values: -2 -1 0 1 -2 -1 0 1 -2 -1 0 1 ..
n.add(2); // 0+2 = -2
n.add(-2); // -2-2 = 0
n.add(5); // 0+5 = 1
n.add(-5); // 1-5 = 0
n.add(-5); // 0-5 = -1
n.add(-1); // -1-1 = -2
n.add(11); // -2+11 = 1
this is what i did:
class MyNumber {
int value;
final int minValue, maxValue;
public MyNumber(int value, int minValue, int maxValue) {
if (value < minValue || value > maxValue || maxValue < minValue) {
throw new RuntimeException();
}
this.value = value;
this.minValue = minValue;
this.maxValue = maxValue;
}
void add(int amount) {
int step = 1;
if (amount < 0) {
step = -1;
amount = -amount;
}
while (amount-- > 0) {
value += step;
if (value < minValue)
value = maxValue; // overflows
if (value > maxValue)
value = minValue; // overflows
}
}
}
it works but i don’t want to iterate the whole addition since i’m going to work with big numbers
i think it has something to do with MOD… (i am terrible at maths)
nearly randomly i made this:
void add(int amount) {
value = (value + amount) % (maxValue - minValue + 1);
}
i was so close but it fails at
n = new MyNumber(-2, -4, -1);
n.add(2); // -2+2 shows 0 instead of -4 (-2.. -1.. *overflow*.. -4)
i surrender
I would try to make things as clear as possible. e.g
If you want clock arithmetic you can do
If you wanted bounded arithmetic.