为了账号安全,请及时绑定邮箱和手机立即绑定

循环遍历一个序列并返回模数

循环遍历一个序列并返回模数

PHP
温温酱 2023-10-15 15:22:51
我有一个从 1 到 7 的整数序列:(1, 2, 3, 4, 5, 6, 7这些实际上是数组键)我需要一个函数,它接受一个整数作为参数,并返回该序列中的下一个项目。它会“循环”该序列,或“迭代”该序列。不确定是否足够清楚,所以这里有一些例子:myNextNumber(3)会回来4,myNextNumber(7)会回来1,myNextNumber(1)会回来2我需要与之前的数字相同的内容:myPreviousNumber(3)会返回2,myPreviousNumber(7)会返回6,myPreviousNumber(1)会返回7,这 2 个函数是参数的 +1 或 -1 步长。如果我可以将这两个函数合并为一个可以接受第二个参数的函数,该参数将是 或+1或-1其他任何内容的步骤,例如+42,它会在返回正确的索引之前“循环”序列六次,那就太好了。但这样要求就太多了。现在我将非常感谢您的指导myNextNumber()。我很确定一个带有模运算符的非常简单的单行代码就满足了它的需要,但我无法让它工作。
查看完整描述

3 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

public int getNextNumber(int[] array, int index) {

    index = Math.floorMod(index, array.length) + 1;

    return array[index];

}

我不懂 PHP,但我想这是准确的:


function getNextNumber(&$array, int $index) {

    $index = fmod($index, count(array)) + 1

    return $array[$index]


查看完整回答
反对 回复 2023-10-15
?
SMILET

TA贡献1796条经验 获得超4个赞

代码


function getKey($current, $step): int

{

    $keys = [1,2,3,4,5,6,7];

    $currentKey = array_search($current, $keys);

    $size = count($keys);


    // normalize step offset

    $step = ($step % $size) + $size;

    //       ^-----------^  ^-----^

    //              │          └ move possible negative to positive

    //              └ get a value from -7 to +7

    

    // add offset for current key

    $newKey = ($currentKey + $step) % $size;

    //         ^-----------------^  ^-----^

    //                  │              └ wrap around in case we exceed $size

    //                  └ add normalized step offset to new element to current

    return $keys[$newKey];

}


// Tests


echo getKey(1,-1) . PHP_EOL;

echo getKey(3,1) . PHP_EOL;

echo getKey(7,1) . PHP_EOL;

echo getKey(7,15) . PHP_EOL; // same as +1

echo getKey(1,-8) . PHP_EOL; // same as -1

echo getKey(1,-15) . PHP_EOL; // same as -1

输出


7

4

1

1

7

7

工作示例



查看完整回答
反对 回复 2023-10-15
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

这个函数就可以解决问题,你应该使用 mod 来查找数字(对于 php 和 java 来说是“%”);


function myNextNumber($i){

     if($i>6){

       return ($i%7)+i;

     }

     return $i+1;

}



function myPreviousNumber($i){

    if($i>8){

       return $i%7-1;

    }

    if($i == 1){

      return 7;

    }

    return $i-1;

}


function myNextNumber($i, $param){

   if($param == 1){

     return myNextNumber($i);

   }


   if($param == -1){

     return myPreviousNumber($i);

   }

   

   return 'Invalit Param';

}


查看完整回答
反对 回复 2023-10-15
  • 3 回答
  • 0 关注
  • 70 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信