Last active
October 3, 2018 09:51
-
-
Save forkbombe/e67ea5cdb2113fb57369d714034a3e8f to your computer and use it in GitHub Desktop.
I was asked in a job interview to count all words in a string ignoring capitals and special characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$str = "About nine o'clock the moon was sufficiently bright for me to proceed on my way and I had no difficulty in following the trail at a fast walk, and in some places at a brisk trot until, about midnight, I reached the water hole where Powell had expected to camp. I came upon the spot unexpectedly, finding it entirely deserted, with no signs of having been recently occupied as a camp. | |
I was interested to note that the tracks of the pursuing horsemen, for such I was now convinced they must be, continued after Powell with only a brief stop at the hole for water; and always at the same rate of speed as his. | |
I was positive now that the trailers were Apaches and that they wished to capture Powell alive for the fiendish pleasure of the torture, so I urged my horse onward at a most dan1gerous pace, hoping against hope that I would catch up with the red rascals before they attacked him. | |
Further speculation was suddenly cut short by the faint report of two shots far ahead of me. I knew that Powell would need me now if ever, and I instantly urged my horse to his topmost speed up the narrow and difficult moun!tain trail."; | |
/** | |
* YOUR CODE GOES HERE | |
*/ | |
function countWords($str) { | |
// Ensure all lowercase | |
$str = strtolower($str); | |
// Strip carriage return from string and replace with space | |
$str = str_replace("\n", ' ', $str); | |
// Remove all non alphanumeric chars | |
$str = preg_replace("/[^A-Za-z0-9 ]/", '', $str); | |
// Create array | |
$arr = explode(' ', $str); | |
// Count values | |
$arr = array_count_values($arr); | |
// Sort high - low | |
arsort($arr); | |
return $arr; | |
} | |
print_r(countWords($str)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment