Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Ryokuchaneko/5999798 to your computer and use it in GitHub Desktop.
Save Ryokuchaneko/5999798 to your computer and use it in GitHub Desktop.
ヒルクライムによる最小コストを求める関数。コスト関数を入れ替えれば、他の問題においても最小、最大値を求めることができる。
function hillclimb($domain, $origin, $people, $flights, $destination) {
$r = array();
for($s = 0; $s < count($domain); $s++) {
$r[] = rand($domain[$s][0], $domain[$s][1]);
}
while(1){
$neighbors = array();
for ($k = 0; $k < count($domain); $k++) {
if($r[$k] > $domain[$k][0]) {
$neighbors[] = array_replace($r, array($k => $r[$k]-1));
}
if($r[$k] < $domain[$k][1]) {
$neighbors[] = array_replace($r, array($k => $r[$k]+1));
}
}
$current = schedulecost($r, $origin, $people, $flights, $destination);
$best = $current;
for ($p = 0; $p < count($neighbors); $p++) {
$cost = schedulecost($neighbors[$p], $origin, $people, $flights, $destination);
if ( $cost < $best ) {
$best = $cost;
$r = $neighbors[$p];
}
}
if( $best == $current ) {
break;
}
}
return $r;
}
$result = hillclimb($domain, $origin, $people, $flights, $destination);
var_dump($result);
$cost = schedulecost($result, $origin, $people, $flights, $destination);
var_dump($cost);
$schedule = printschedule($result, $people, $flights, $destination);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment