溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP如何實(shí)現(xiàn)螞蟻爬桿路徑算法

發(fā)布時(shí)間:2021-06-25 14:04:41 來(lái)源:億速云 閱讀:97 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了PHP如何實(shí)現(xiàn)螞蟻爬桿路徑算法,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

具體如下:

<?php
/**
 * 有一根27厘米的細(xì)木桿,在第3厘米、7厘米、11厘米、17厘米、23厘米這五個(gè)位置上各有一只螞蟻。
 * 木桿很細(xì),不能同時(shí)通過(guò)一只螞蟻。開(kāi)始 時(shí),螞蟻的頭朝左還是朝右是任意的,它們只會(huì)朝前走或調(diào)頭,
 * 但不會(huì)后退。當(dāng)任意兩只螞蟻碰頭時(shí),兩只螞蟻會(huì)同時(shí)調(diào)頭朝反方向走。假設(shè)螞蟻們每秒鐘可以走一厘米的距離。
 * 編寫(xiě)程序,求所有螞蟻都離開(kāi)木桿 的最小時(shí)間和最大時(shí)間。
 */
function add2($directionArr, $count, $i) {
 if(0 > $i) { // 超出計(jì)算范圍
  return $directionArr;
 }
 if(0 == $directionArr[$i]) { // 當(dāng)前位加1
  $directionArr[$i] = 1;
  return $directionArr;
 }
 $directionArr[$i] = 0;
 return add2($directionArr, $count, $i - 1); // 進(jìn)位
}
$positionArr = array( // 所在位置
 3,
 7,
 11,
 17,
 23
);
function path($positionArr) { // 生成測(cè)試路徑
 $pathCalculate = array();
 $count = count($positionArr);
 $directionArr = array_fill(0, $count, 0); // 朝向
 $end = str_repeat('1', $count);
 while (true) {
  $path = implode('', $directionArr);
  $pathArray = array_combine($positionArr, $directionArr);
  $total = calculate($positionArr, $directionArr);
  $pathCalculate['P'.$path] = $total;
  if($end == $path) { // 遍歷完成
   break;
  }
  $directionArr = add2($directionArr, $count, $count - 1);
 }
 return $pathCalculate;
}
function calculate($positionArr, $directionArr) {
 $total = 0; // 總用時(shí)
 $length = 27; // 木桿長(zhǎng)度
 while ($positionArr) {
  $total++; // 步增耗時(shí)
  $nextArr = array(); // 下一步位置
  foreach ($positionArr as $key => $value) {
   if(0 == $directionArr[$key]) {
    $next = $value - 1; // 向0方向走一步
   } else {
    $next = $value + 1; // 向1方向走一步
   }
   if(0 == $next) { // 在0方向走出
    continue;
   }
   if($length == $next) { // 在1方向走出
    continue;
   }
   $nextArr[$key] = $next;
  }
  $positionArr = $nextArr; // 將$positionArr置為臨時(shí)被查找數(shù)組
  foreach ($nextArr as $key => $value) {
   $findArr = array_keys($positionArr, $value);
   if(count($findArr) < 2) { // 沒(méi)有重合的位置
    continue ;
   } 
   foreach ($findArr as $findIndex) {
    $directionArr[$findIndex] = $directionArr[$findIndex] ? 0 : 1; // 反向處理
    unset($positionArr[$findIndex]); // 防止重復(fù)查找計(jì)算
   }
  }
  $positionArr = $nextArr; // 將$positionArr置為下一步結(jié)果數(shù)組
 }
 return $total;
}
$pathCalculate = path($positionArr);
echo '<pre>calculate-';
print_r($pathCalculate);
echo 'sort-';
asort($pathCalculate);
print_r($pathCalculate);

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“PHP如何實(shí)現(xiàn)螞蟻爬桿路徑算法”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI