开发者

How can I find the most frequently recurring item in an array?

开发者 https://www.devze.com 2023-01-22 15:44 出处:网络
What would be the best approach to create the function getMostFrequentlyOccurringItem() below? //should return \"paragraph\"

What would be the best approach to create the function getMostFrequentlyOccurringItem() below?

//should return "paragraph"
echo getMostFrequentlyOccurringItem(array('line', 'paragraph', 'paragraph'));

//should return "line"
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'line', 'line', 'line'));

//should return null
echo getMostFrequentlyOccurringItem(array('wholeNumber', 'wholeNumber', 'paragraph', 'paragraph'));

//should return "wholeNumber"
echo getMostFrequentlyOccurringItem(array('wholeNumber', '', '', ''));

function getMostFrequentlyOccurringItem($items) {
    //...
}

Answer:

Thanks Adam, here's my finished solution: http://tanguay.info/web/index.php?pg=codeExamples&id=3开发者_StackOverflow社区96


Start with array_count_values(), and massage the output to your liking.

php> =array_count_values(array('wholeNumber', 'line', 'line', 'line'))
array(
  "wholeNumber" => 1,
  "line" => 3,
)

arsort($counts, SORT_NUMERIC) will sort the array_count_values() output by most frequent first.


This is a candidate situation where you can apply the linear-time majority vote algorithm.

The link goes into a great explanation on how to apply this brilliantly simple algorithm. Note that if you indeed want to return null to indicate a tie, this will require two passes over the data instead of one.


How about implementing an associative array of key and counter.


Implode the array into a string separated by comma or space. Then use preg_match (http://au2.php.net/manual/en/function.preg-match.php) to find the number of occurrences of a specified string. The pattern can be customized to exact match or occurrence match!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号