I had an interview where I could use any language I wanted to in order to calculate how many times each word appeared in a text file.
I solved it in C by reading in each word and adding it to a tree structure – If the word was all ready in the structure, the algorithm would add one to a counter I added in the node.
Well the person said I had to much code and it was messy, and said I could do it in PHP with about 3 lines of code.
I started to use the explode() to separate the string into a array of words, but was stuck after that.
Does anybody know how this could be done in PHP with a couple lines of code?
An easy way to do this is to read the complete file in as a string with
file_get_contents(), split it up on whitespace, and run the resulting array througharray_count_values()Done!
However, this isn’t perfect, as punctuation can mess up your count. So, as Mark Baker points out, we can go back to my original method of getting all of the words in the file with
str_word_count(), then running that array througharray_count_values():