2

次のことを行う関数が必要です。

このような文字列がある場合、"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>';
}
4

1 に答える 1

1

おそらく、これは文字列を解析するためのさまざまな方法を提供するという点で役立つでしょう。

$str="2 1 3 6 5 4 8 7";
$sar=explode(' ',$str);
for($i=1;$i<count($sar);$i++)
  if($sar[$i-1]<$sar[$i])
    print substr_replace($str,'-',2*($i-1)+1,1) . "\n";

このコードは、文字列に 1 桁の数字のみを想定していることに注意してください。

コードは、文字列が例に従ってフォーマットされていることを期待していることに注意してください。いくつかの健全性チェックを追加するとよいでしょう (複数のスペースを折りたたむ、先頭/末尾の空白を取り除く/トリムする)。

文字列内のすべてのスペースを検索し、それらを使用して比較のために部分文字列にインデックスを付けることで、これを改善できます。ただし、1 つのスペースのみが隣接する数値を区切っていると仮定します。

<?php
$str="21 11 31 61 51 41 81 71";
$letter=' ';
#This finds the locations of all the spaces in the strings
$spaces = array_keys(array_intersect(str_split($str),array($letter)));

#This function takes a start-space and an end-space and finds the number between them.
#It also takes into account the special cases that we are considering the first or 
#last space in the string
function ssubstr($str,$spaces,$start,$end){
    if($start<0)
        return substr($str,0,$spaces[$end]);
    if($end==count($spaces))
        return substr($str,$spaces[$start],strlen($str)-$spaces[$start]);
    return substr($str,$spaces[$start],$spaces[$end]-$spaces[$start]);
}

#This loops through all the spaces in the string, extracting the numbers on either side for comparison
for($i=0;$i<count($spaces);$i++){
    $firstnum=ssubstr($str,$spaces,$i-1,$i);
    $secondnum=ssubstr($str,$spaces,$i,$i+1) . "\n";
    if(intval($firstnum)<intval($secondnum))
        print substr_replace($str,'-',$spaces[$i],1) . "\n";
}

?>

辞書式の比較を避けるために、整数への明示的な変換に注意してください。

于 2012-10-13T09:15:06.703 に答える