2016-07-23 37 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

是的 - 如果 - 符號不是先行的,所以它會加上+符號 – 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"