2014-04-23 40 views
-1

我正在爲教育目的編寫一些代碼,我需要代碼來計算隨機生成的數組值的模式。陣列的模式

如果只有一個模式(例如在數據集:2,3,4,5,5,6,7),那麼這是很容易(見白象的回答這裏:How to find the mode of an array in PHP)。

但是我在使用其中存在多於一個的模式實例麻煩(如和在這個數據組:1,2,3,3,3,4,4,4, 5,6,6)。

如何做到這一點的邏輯似乎已經在Javascript(https://stackoverflow.com/a/3451640/1541165)和Java(https://stackoverflow.com/a/8858601/1541165)那裏,但我不知道這兩種語言之一。

有人可以幫助翻譯這到PHP也許?或者給出如何在PHP環境中解決這個問題的指導?

謝謝。

回答

1

口到PHP從https://stackoverflow.com/a/8858601/1541165

<?php 

$array = array(1,2,3,4,4,5,5,6,7,8,10); 

$modes = array(); 

$maxCount = 0; 
for($i = 0; $i < count($array); $i++){ 
     $count = 0; 
     for($j = 0; $j < count($array); $j++){ 
       if ($array[$j] == $array[$i]) $count++; 
     } 
     if($count > $maxCount){ 
       $maxCount = $count; 
       $modes = array(); 
       $modes[] = $array[$i]; 
     } else if ($count == $maxCount){ 
       $modes[] = $array[$i]; 
     } 
} 
$modes = array_unique($modes); 

print_r($modes); 


?> 
+0

的偉大工程。謝謝! – gtilflm