最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PHP實(shí)現(xiàn)的螞蟻爬桿路徑算法代碼

 更新時(shí)間:2015年12月03日 09:19:47   作者:lsjlnd  
這篇文章主要介紹了PHP實(shí)現(xiàn)的螞蟻爬桿路徑算法代碼,以完整實(shí)例形式分析了螞蟻爬桿路徑算法的原理與實(shí)現(xiàn)方法,涉及php數(shù)值計(jì)算與數(shù)組操作的相關(guān)技巧,需要的朋友可以參考下

本文實(shí)例講述了PHP實(shí)現(xiàn)的螞蟻爬桿路徑算法代碼。分享給大家供大家參考,具體如下:

<?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);

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

庆阳市| 林芝县| 错那县| 梅河口市| 华坪县| 聂拉木县| 台北市| 盐边县| 万宁市| 娄烦县| 盐边县| 湘潭市| 临邑县| 抚松县| 永川市| 乐昌市| 丹阳市| 织金县| 鄂托克旗| 晴隆县| 固安县| 鄄城县| 沙湾县| 霞浦县| 广东省| 衡阳市| 无锡市| 东兰县| 鱼台县| 寿光市| 兴仁县| 宣化县| 凤冈县| 晋宁县| 重庆市| 鄱阳县| 屏东市| 安康市| 紫阳县| 开封县| 易门县|