2016-07-23 7 views
1

によって文字列Polymonial式をソートするためにどのように私はPHPでこの文字列を持っている:PHP:指数

$equation = "-29x^3+1x^4-16x^1-9x^-1-6x^-3-6x^-4+2x^2-18-3x^6"; 

しかし、私は指数によってそれをソートしたい、正しい結果はこのようになります。

$result = "-3x^6+1x^4-29x^3+2x^2-16x^1-9x^-1-6x^-3-6x^-4-18"; 

どうすればいいですか?

私はusort、natsortを試してみましたが、あなたはこのようにそれを行うことができます

+0

を使用すると、式の形式で完全にコントロールを持っていますか?例えば、 '-29x^3'の代わりに' 29x^3'があれば、どのように書かれますか?先頭の '+ '記号は明示的に追加されますか? – Arnauld

+0

yes - 記号がprecenceでない場合、+記号が追加されます – juanpscotto

答えて

3
$pattern = '/(?:[+-]?\d+(?:x(?:\^[+-]?\d+))?)?\K/'; 
$equation = "-29x^3+1x^4-16x^1-9x^-1-6x^-3-6x^-4+2x^2-18-3x^6"; 
// Split an equation for items and remove empty result 
$result = array_filter(preg_split($pattern, $equation)); 
// sort descending of exponent 
usort($result, function($a, $b) 
       { 
        list(,$a) = explode('^', $a); 
        if($a === NULL) return 1; 
        list(,$b) = explode('^', $b); 
        if($b === NULL) return -1; 
        return $b-$a; 
       }); 
// Join to result string 
echo implode('', $result); // -3x^6+1x^4-29x^3+2x^2-16x^1-9x^-1-6x^-3-6x^-4-18 

test it here

+0

ありがとうございますが、定数-18は最後ではありません。 – juanpscotto

+0

答えを更新しました – splash58

+0

どのように正規表現を作成しますか? ?あなたは教祖か何かですか? – juanpscotto

2

を動作しません:

$equation = '-29x^3+1x^4-16x^1-9x^-1-6x^-3-6x^-4+2x^2-18-3x^6'; 
$result = ''; 

if (preg_match_all('~[+-]?\d*(?:x(?:\^([+-]?\d+))?)?~', $equation, $matches)) { 
    foreach ($matches[0] as $k=>$v) 
     if (substr($v, -1)=='x') $matches[1][$k] = 1; 

    arsort($matches[1]); // sort the keys by exponent values 

    foreach ($matches[1] as $k=>$v) 
     $result .= $matches[0][$k]; 
} 

echo $result, PHP_EOL; 
preg_split使用

その他の方法:

$parts = preg_split('~\b(?=[-+])~', $equation); 

if (!in_array(substr($parts[0], 0, 1), ['-','+'])) $parts[0] = '+' . $parts[0]; 

$assoc = []; 

foreach ($parts as $v) { 
    $tmp = explode('^', $v); 
    if (isset($tmp[1])) $assoc[$v] = $tmp[1]; 
    elseif (strpos($v, 'x')!==false) $assoc[$v] = 1; 
    else $assoc[$v] = ''; 
} 
arsort($assoc); 
$result = implode('', array_keys($assoc)); 
2

液を用いpreg_match_allusortpreg_replace機能:

$equation = "-29x^3+1x^4-16x^1-9x^-1-6x^-3-6x^-4+2x^2-18-3x^6"; 
preg_match_all("/[-+]?\d+?x\^[+-]?\d+?|[+-]\d+?(?=[+-])/", $equation, $matches); 

usort($matches[0], function ($a, $b){ 
    return (int) preg_replace("/^.*\^/", "", $b) 
      - (int) preg_replace("/^.*\^/", "", $a); 
}); 

$result = implode("", $matches[0]); 

print_r($result); // "-3x^6+1x^4-29x^3+2x^2-16x^1-9x^-1-6x^-3-6x^-4-18" 
関連する問題