【问题标题】:How to increment and decrement between two values如何在两个值之间递增和递减
【发布时间】:2011-01-09 04:08:41
【问题描述】:

这很尴尬,但是:

假设我想将 1 加到 x 直到它达到 100。然后我想从 x 中减去 1 直到它达到 1。然后我想将 1 加到 x 直到它达到 100,依此类推。

有人可以为这个让我感到特别愚蠢的问题提供一些简单的伪代码。

谢谢:)


编辑 1

抱歉!我的例子太简单了。实际上,我会在每次迭代时使用随机数递增,因此需要 (x == 100) 的响应将不起作用,因为 x 肯定会高于 100 并低于 1。

【问题讨论】:

  • 您能举例说明您的编辑吗?

标签: algorithm iteration pseudocode


【解决方案1】:

这是数学方法:

for(int i=0;i<10000000;i++)
  print(abs(i%200-100))

算法的方式:

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()));
}

【讨论】:

  • 对于第一个,你得到序列 100->0->100->... 而不是 1->100->1->...
【解决方案2】:
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;
}

【讨论】:

    【解决方案3】:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多