Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Created June 11, 2022 08:00
Show Gist options
  • Save zonuexe/b14709e730f231aefb80706e4afac667 to your computer and use it in GitHub Desktop.
Save zonuexe/b14709e730f231aefb80706e4afac667 to your computer and use it in GitHub Desktop.
nagoya.php
<?php
/**
某N市の地下鉄の料金は1区,2区,3区,...のように駅間の距離ポイントによって決まります。
【料金表】
距離 料金
1 210
2 240
3 270
4 300
たとえばある路線に A駅 - 1 - B駅 - 2 - C駅 のように駅が並んでいるとき、A駅からB駅は1区料金、B駅からC駅は2区料金、A駅からC駅は1+2=3区料金となります。
路線の距離ポイント定義をもとに、指定された出発駅から到着駅までの料金を求めるプログラムを書いてください。
路線の駅間の距離ポイントは A,1,B,2,C のように定義し、距離ポイント定義と出発駅と到着駅の間は | で区切られています。
*/
const PRICES = [
0,
210,
240,
270,
300,
];
$tests = [
['A,1,B,2,C|A|B', 210],
['A,1,B,2,C|A|C', 270],
['W,1,X,1,Y,2,Z|W|X', 210],
['W,1,X,1,Y,2,Z|W|Y', 240],
['W,1,X,1,Y,2,Z|Z|X', 270],
];
foreach ($tests as [$input, $expected]) {
echo test($input, $expected) ? 'good' : 'bad', "\n";
}
function test(string $input, int $expected)
{
[$route, $from, $to] = explode('|', $input, 3);
preg_match_all('/(?<station>[A-Z])/', $route, $matches, PREG_OFFSET_CAPTURE);
$stations = array_column($matches['station'], 1, 0);
if ($stations[$from] > $stations[$to]) {
[$from, $to] = [$to, $from];
}
$sub = substr($route, $stations[$from], $stations[$to]);
preg_match_all('/(?<distance>\d+)/', $sub, $matches);
$total_distance = array_sum($matches['distance']);
return PRICES[$total_distance] === $expected;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment