tags:

views:

75

answers:

4

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=396

A: 

How about implementing an associative array of key and counter.

Gunner
+8  A: 

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.

Adam Backstrom
Mh, ksort() does sort by key and the keys are the words, so, wouldn´t it be better to use the sort() function to sort the words by occurence?
Max
`sort()` will clobber the indexes, so you won't be able to identify the frequent words. I did pick the wrong function, though; I wanted `arsort()` to sort an associative array in reverse order, maintaining key/value pairs.
Adam Backstrom
Now that makes more sense, +1 for your solution :-)
Max
A: 

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.

Mark Rushakoff
+0. OP isn't asking for majority but, rather, plurality.
webbiedave
@webbie: I had to look up the difference. If anyone else is wondering, [Wikipedia has the answer](http://en.wikipedia.org/wiki/Plurality_%28voting%29), as usual.
Mark Rushakoff
A: 

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!

deepsat