次のことを行う関数が必要です。
このような文字列がある場合、"2 1 3 6 5 4 8 7"
いくつかの規則に従って、数字のペアの間にダッシュを挿入する必要があります。
ルールは簡単です。
ペアの最初の数字がそれに続く数字よりも小さい場合は、2 つの数字の間にダッシュを挿入します。これのすべての可能な組み合わせを行い、ペアにすでにダッシュがある場合、その隣のスペースにダッシュを含めることはできません.
基本的に、上記の文字列の結果は次のようになります
2 1-3 6 5 4 8 7
2 1-3 6 5 4-8 7
2 1 3-6 5 4 8 7
2 1 3-6 5 4-8 7
2 1 3 6 5 4-8 7
私はこれを行う関数を作成しましたが、かなり遅いと考えており、あなたのアイデアを汚したくありません. 可能であれば、皆さんがこれについてどのように考えているかを知りたいです。疑似コードやコードでさえ素晴らしいでしょう。
編集1:これが私がこれまでに持っているコードです
$string = "2 1 3 6 5 4 8 7";
function dasher($string){
global $dasherarray;
$lockcodes = explode(' ', $string);
for($i = 0; $i < count($lockcodes) - 1; $i++){
if(strlen($string) > 2){
$left = $lockcodes[$i];
$right = $lockcodes[$i+1];
$x = $left . ' ' . $right;
$y = $left . '-' . $right;
if (strlen($left) == 1 && strlen($right) == 1 && (int)$left < (int)$right) {
$dashercombination = str_replace($x, $y, $string);
$dasherarray[] = $dashercombination;
dasher($dashercombination);
}
}
}
return array_unique($dasherarray);
}
foreach(dasher($string) as $combination) {
echo $combination. '<br>';
}