1.两个有序数组组合成一个新的有序数组
<?php
$arr1=array(2,5,7,9,12);
$arr2=array(3,4,6,8,10,11);
function merge_sort($arr1,$arr2){
$len1=count($arr1);
$len2=count($arr2);
$arr=array();
$i=$j=0;
while($i<$len1&&$j<$len2){
if($arr1[$i]<=$arr2[$j]){
$arr[]=$arr1[$i++];
}else{
$arr[]=$arr2[$j++];
}
}
while($i<$len1)
$arr[]=$arr1[$i++];
while($j<$len2)
$arr[]=$arr2[$j++]; return $arr;
} print_r(merge_sort($arr1,$arr2));
2.十进制转26进制(a-z表示)
function tento26($num){
$str='';
$chu=floor($num/26);
$yu=$num%26;
$str.="{".$yu."}";
if($chu>26){
$str.=tento26($chu);
}else{
$str.="{".$chu."}";
}
return $str;
} function numtoalph($match){
$alp=' abcdefghijklmnopqrstuvwxyz';
if($match[1]>=26){
return false;
}
return $alp[$match[1]];
}
$str= tento26(300); $str1=strrev(preg_replace_callback('#\{(\d+)\}#','numtoalph',$str));
echo $str1;
3.数组转json
<?php
function myjson_encode($arr){
$jsonstr='{';
foreach($arr as $k=>$v){
if(is_array($v)){
$jsonstr.='"'.$k.'":'.myjson_encode($v).',';
}else{
$jsonstr.='"'.$k.'":"'.$v.'",';
}
}
$jsonstr=trim($jsonstr,',');
$jsonstr.='}';
return $jsonstr;
}
4.二分查找
<?php
#二分查找
function binarySearch(Array $arr, $target) {
$low = 0;
$high = count($arr) - 1; while($low <= $high) {
$mid = floor(($low + $high) / 2);
#找到元素
if($arr[$mid] == $target) return $mid;
#中元素比目标大,查找左部
if($arr[$mid] > $target) $high = $mid - 1;
#重元素比目标小,查找右部
if($arr[$mid] < $target) $low = $mid + 1;
} #查找失败
return false;
} $arr = array(1, 3, 5, 7, 9, 11);
$inx = binarySearch($arr, 1);
var_dump($inx);
?>
5.钱币转换
<?php
error_reporting(0);
function cny($ns) {
static $cnums=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"),
$cnyunits=array("圆","角","分"),
$grees=array("拾","佰","仟","万","拾","佰","仟","亿");
list($ns1,$ns2)=explode(".",$ns,2);
$ns2=array_filter(array($ns2[1],$ns2[0])); $ret=array_merge($ns2,array(implode("",_cny_map_unit(str_split($ns1),$grees)),""));
$ret=implode("",array_reverse(_cny_map_unit($ret,$cnyunits)));
echo $ret;
echo "<br>";
return str_replace(array_keys($cnums),$cnums,$ret);
}
function _cny_map_unit($list,$units) {
$ul=count($units);
$xs=array();
foreach (array_reverse($list) as $x) {
$l=count($xs);
if ($x!="0" || !($l%4)){
$n=($x=='0'?'':$x).($units[($l-1)%$ul]);
} else{
$n=is_numeric($xs[0][0])?$x:'';
} array_unshift($xs,$n);
}
return $xs;
} echo cny(2305.32);
2仟3佰05圆3角2分
贰仟叁佰零伍圆叁角贰分
6.约瑟夫环
<?php
function ysf($arr,$current=0,$out=3){
$count=count($arr);
$num=1;
if($count==1){
echo $arr[0];
}else{
while($num++<$out){
$current++;
$current=$current%$count;
}
echo $arr[$current]."<br>";
array_splice($arr,$current,1);
ysf($arr,$current,$out);
} }
$arr=[1,2,3,4,5,6,7,8,9,10];
ysf($arr,0,4);