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!
精彩评论