最新国产好看的视频,伊人天堂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í)通過一只螞蟻。開始 時(shí),螞蟻的頭朝左還是朝右是任意的,它們只會(huì)朝前走或調(diào)頭,
 * 但不會(huì)后退。當(dāng)任意兩只螞蟻碰頭時(shí),兩只螞蟻會(huì)同時(shí)調(diào)頭朝反方向走。假設(shè)螞蟻們每秒鐘可以走一厘米的距離。
 * 編寫程序,求所有螞蟻都離開木桿 的最小時(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) { // 沒有重合的位置
    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)論

阳原县| 土默特左旗| 阜南县| 门头沟区| 罗江县| 商城县| 旺苍县| 洱源县| 新竹市| 东至县| 襄樊市| 许昌市| 广汉市| 哈巴河县| 河津市| 佛坪县| 祁东县| 明星| 泽州县| 肥西县| 五寨县| 宣武区| 宁陵县| 秦安县| 贵南县| 高安市| 邯郸市| 博罗县| 烟台市| 连城县| 武隆县| 新野县| 赫章县| 当涂县| 靖远县| 清苑县| 卢氏县| 娱乐| 新津县| 乌拉特中旗| 永善县|