这很令人尴尬,但是:
假设我要将x加1直到达到100.此时我想从x中减去1直到达到1.然后我想将1加到x直到达到100,依此类推。
有人可以为这个问题提供一些简单的伪代码,让我觉得特别愚蠢。
谢谢:)
编辑1
道歉!我的例子太简单了。我实际上将在每次迭代时使用随机数递增,因此需要(x == 100)的响应将不起作用,因为x肯定会超过100且低于1.
答案 0 :(得分:2)
这是数学方式:
for(int i=0;i<10000000;i++)
print(abs(i%200-100))
Algo的方式:
int i = 1;
while(1)
{
while(i<100)print(i++);
while(i>1)print(--i);
}
随机更新:
int i = 1;
while(1)
{
while(i<100)print(i=min(100,i+random()));
while(i>1)print(i=max(1,i-random()));
}
答案 1 :(得分:0)
<强> C#:强>
Random rnd = new Random();
int someVarToIncreaseDecrease = 0;
bool increasing = true;
while(true) {
int addSubtractInt = rnd.Next(someUpperBound);
if (increasing && (someVarToIncreaseDecrease + addSubtractInt >= 100))
increasing = false;
else if (!increasing && (someVarToIncreaseDecrease - addSubtractInt < 0))
increasing = true;
if (increasing) {
someVarToIncreaseDecrease += addSubtractInt;
}
else {
someVarToIncreaseDecrease -= addSubtractInt;
}
}
答案 2 :(得分:0)
int ceiling = 100;
int floor = 1;
int x = 1;
int step = GetRandomNumber(); //assume this isn't 0
while(someArbitraryCuttoffOrAlwaysTrueIDK) {
while(x + step <= ceiling) {
x += step;
}
while(x - step >= floor) {
x -= step;
}
}
或者,更简洁(存在不太明确的风险):
while(someArbitraryCuttoffOrAlwaysTrueIDK) {
while((step > 0 && x + step <= ceiling) || (step < 0 && x + step >= floor))
{
x += step;
}
step = step * -1;
}
可替换地:
while(someArbitraryCuttoffOrAlwaysTrueIDK) {
if((step > 0 && x + step > ceiling) || (step < 0 && x + step < floor))
{
step = step * -1;
}
x += step;
}