Let's say that i have an array of int's in range 65-90. I'll randomly pick one of elements and add 10 to it. Is it possible that value, if cross range of 90 return to 65? For example - i take a 85 and add 10 to it. So it should be 95, but i want a 70.
假设我有一个范围为65-90的int数组。我将随机选择一个元素并添加10个元素。是否有可能值,如果90的交叉范围返回到65?例如 - 我拿一个85并加10。所以它应该是95,但我想要一个70。
2 个解决方案
#1
2
You can do it by placing your value in the interval [0, high - low]
by removing low
to your value, then add the number you want to it, take the modulo of the sum, and finally add low
back to get back in the range [low, high]
您可以通过将值放在区间[0,高 - 低]中来删除低到您的值,然后添加您想要的数字,取总和的模数,最后添加低回以重新进入范围[低,高]
public static void main(String[] args) {
int low = 65, high = 90;
System.out.println(addWithinInterval(85, 10, low, high));
}
private static int addWithinInterval(int value, int add, int low, int high) {
return (value - low + add) % (high - low + 1) + low;
}
#2
1
I'll randomly pick one of elements and add 10 to it. Is it possible that value, if cross range of 90 return to 65?
我将随机选择一个元素并添加10个元素。是否有可能值,如果90的交叉范围返回到65?
Sure, the remainder operator will do that for you:
当然,余数运算符会为您做到这一点:
n = (n - 65) % (90 - 65) + 65;
Example (live copy):
示例(实时复制):
int n = 85;
for (int x = 0; x < 10; ++x) {
n += 10;
n = (n - 65) % (90 - 65) + 65;
System.out.println(n);
}
Or here on site: Java and JavaScript are different, but their %
operators work the same, so:
或者在现场:Java和JavaScript不同,但它们的%运算符的工作方式相同,因此:
let n = 85;
for (let x = 0; x < 10; ++x) {
n += 10;
n = (n - 65) % (90 - 65) + 65;
console.log(n);
}
#1
2
You can do it by placing your value in the interval [0, high - low]
by removing low
to your value, then add the number you want to it, take the modulo of the sum, and finally add low
back to get back in the range [low, high]
您可以通过将值放在区间[0,高 - 低]中来删除低到您的值,然后添加您想要的数字,取总和的模数,最后添加低回以重新进入范围[低,高]
public static void main(String[] args) {
int low = 65, high = 90;
System.out.println(addWithinInterval(85, 10, low, high));
}
private static int addWithinInterval(int value, int add, int low, int high) {
return (value - low + add) % (high - low + 1) + low;
}
#2
1
I'll randomly pick one of elements and add 10 to it. Is it possible that value, if cross range of 90 return to 65?
我将随机选择一个元素并添加10个元素。是否有可能值,如果90的交叉范围返回到65?
Sure, the remainder operator will do that for you:
当然,余数运算符会为您做到这一点:
n = (n - 65) % (90 - 65) + 65;
Example (live copy):
示例(实时复制):
int n = 85;
for (int x = 0; x < 10; ++x) {
n += 10;
n = (n - 65) % (90 - 65) + 65;
System.out.println(n);
}
Or here on site: Java and JavaScript are different, but their %
operators work the same, so:
或者在现场:Java和JavaScript不同,但它们的%运算符的工作方式相同,因此:
let n = 85;
for (let x = 0; x < 10; ++x) {
n += 10;
n = (n - 65) % (90 - 65) + 65;
console.log(n);
}