亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環遍歷一個序列并返回模數

循環遍歷一個序列并返回模數

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,它會在返回正確的索引之前“循環”序列六次,那就太好了。但這樣要求就太多了?,F在我將非常感謝您的指導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 關注
  • 139 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號