Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Last active December 12, 2015 10:49
Show Gist options
  • Save ackintosh/4761915 to your computer and use it in GitHub Desktop.
Save ackintosh/4761915 to your computer and use it in GitHub Desktop.
アルゴリズムを学ぼう p48 の問題をPHPで。
<?php
$exec_num = 1000;
$ar = new SplFixedArray(10);
$cnt = 0;
for ($i = 0; $i < $exec_num; $i++) {
if ($ar->valid() === false) {
// 配列作成 & コピー
$ar = getArray($ar);
}
$ar[$i] = insert_value();
$ar->next();
}
// var_dump($ar);
var_dump($cnt);
function getArray($ar)
{
$new_ar = new SplFixedArray($ar->count() + 10);// 戦略1
// $new_ar = new SplFixedArray($ar->count() * 2); // 戦略2
foreach ($ar as $k => $v) {
$new_ar[$k] = insert_value();
$new_ar->next();
}
return $new_ar;
}
function insert_value()
{
global $cnt;
$cnt++;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment