<html><body style="font-size:32px; line-height:32px;"> <?php // set color $colors = array("red", "blue", "yellow", "green", "black"); // draw 16x16 for ($i = 0; $i < 256; $i++){ $r = rand(0, count($colors)-1); $c = $colors[$r]; echo "<span style='color:$c'>■</span>"; if ($i % 16 == 15) echo "<br>"; } ?></body></html>
Month: August 2016
usortで安定ソート
$data = [ ['name'=>'Arai', 'score'=>30], ['name'=>'Inoue', 'score'=>40], ['name'=>'Utada', 'score'=>30], ['name'=>'Okuda', 'score'=>40], ['name'=>'Kato', 'score'=>23] ]; // record for ($i = 0; $i < count($data); i++){ $data[$i]["id"] = $i + 1; } usort($data, function($a, $b){ if ($a['score'] == $b['score']){ return ($a['id'] > $b['id']) ? 1 : -1; }); foreach ($data as $u){ echo $u['id'].":".$u['name'].":".$u['score']."\n"; }
usort()関数
// setting data $arr = [ ['name']=>'Kan', 'point'=>4], ['name']=>'Kenji', 'point'=>5], ['name']=>'Akai', 'point'=>3], ['name']=>'Genta', 'point'=>4], ['name']=>'Shizuka', 'point'=>8], ]; $point_cmp = function ($a, $b) { return ($a['point'] < $b['point']) ? -1 : 1; }; usort($arr, $point_cmp); //result foreach ($arr as $u) { echo $u['name'].":".$u['point']."\n"; }
クイックソート
// quick sort function quick_sort(&$arr){ if (count($arr) < 2) return $arr; $left = $right = array(); $pivot = array_shift($arr); foreach ($arr as $v) { if ($v < $pivot){ $left[] = $v; } else { right[] = $v; } } quick_sort($left); quick_sort($right); $arr = array_merge($left, array($pivot), $right); } $arr = array(1,100,24,40,12,4); quick_sort($arr); echo implode(', ', $arr)."\n";
マージンソート
コムソート
1 || $swap){ if ($gap > 1) { $gap = floor($gap / 1.25); if ($gap == 9 || $gap == 10) $gap = 11; } $swap = false; $i = 0; while($i + $gap < size) { if ($arr[$i] > $arr[$i + $gap]){ $tmp = $arr[$i]; $arr[$i] = $arr[$i + $gap]; $arr[$i + $gap] = $tmp; $swap = true; } $i++; } } } } $arr = array(100, 3, 30, 20, 44, 32); comb_sort($arr); echo implode(", ", $arr)."\n"