【问题标题】:How could I have the index of an array 'roll over' when incrementing?递增时如何让数组的索引“翻转”?
【发布时间】:2011-10-13 04:47:00
【问题描述】:

所以我有一个长度为 4 的数组。当我将它增加 1 并且数字变得大于数组的长度时,我希望它翻转。

例如:

current_index = 3;
current_index++;
//current_index is now 0 again

current_index = 3;
current_index += 2;
//current_index would be 1

current_index = 0;
current_index--;
//current_index would be 3

我目前正在用这样的 if-else 解决它

if (current_index == textviewlist.length + 1)
     current_index = 0;
else if (current_index == textviewlist.length + 2)
     current_index = 1;
else if (current_index == -1)
     current_index = 3;

但我觉得这不是一个合适的解决方案,也不是“好”的代码。

编辑:我尝试了您的建议,但显然 java 对负数的行为很奇怪。 当我尝试

current_index = (current_index - 1) % textviewlist.length;

Java 获取索引“0”,将其减 1(“-1”),然后

 -1 % 4 = -1

我希望它是 3,请参阅 Wolfram Alpha: -1 mod 4 但显然java % 运算符与模运算符不一样?

编辑 2:我在这里找到了解决方案:Best way to make Java's modulus behave like it should with negative numbers? - Stack Overflow

我只能这样做:

current_index -= 1;
current_index = (current_index % textviewlist.length + textviewlist.length)  % textviewlist.length;

【问题讨论】:

    标签: java arrays indexing


    【解决方案1】:

    您可以使用模运算符。

    current_index = (current_index + n) % 4;
    

    【讨论】:

    • 非常感谢您的回答。 +1 :)
    • 因为 google 在搜索相同内容时将此页面排名最高,但在 JavaScript 中,这里是 JS 版本:current_index = (current_index + n + 4) % 4;
    • 上面的评论是#fakenews
    【解决方案2】:

    将递增的索引除以数组的长度:

    current_index = (current_index + n) % textviewlist.length
    

    【讨论】:

      【解决方案3】:

      你可以按如下方式使用mod:

      current_index = (current_index + i) % 4.
      

      【讨论】:

      • 非常感谢,我知道我错过了一些东西。
      【解决方案4】:

      只需将其设置为自身模 4 - 或者更确切地说,列表的长度 - 在每次递增之后。

      current_index += 2;
      current_index %= textviewlist.length;
      

      或组合:

      current_index = (current_index + 2) % textviewlist.length;
      

      你也可以这样做:

      current_index += n;
      while (current_index >= textviewlist.length) {
          current_index -= textviewlist.length;
      }
      

      虽然如果这不比模运算慢我会感到惊讶,特别是因为您的列表长度是 2 的幂。

      无论哪种方式,将所有这些都封装到 increment() 函数中可能是个好主意:

      int increment(int old_index, int n) {
          return (old_index + n) % textviewlist.length;
      }
      

      编辑:啊,我不知道你在用 Java 工作。 (我认为 C 的模运算符模仿了负数的数学定义)对您找到的解决方案的轻微改进是

      int increment(int old_index, int n) {
          return (old_index + n + textviewlist.length) % textviewlist.length;
      }
      

      【讨论】:

      • 感谢您的回答,我真的很喜欢 increment() 函数的想法。但是,负值会发生什么?我刚刚编辑了我的问题以反映这一点。
      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 2011-11-05
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 1970-01-01
      相关资源
      最近更新 更多