Skip to content

Instantly share code, notes, and snippets.

@evert0n
Created November 10, 2012 07:38
Show Gist options
  • Save evert0n/4050315 to your computer and use it in GitHub Desktop.
Save evert0n/4050315 to your computer and use it in GitHub Desktop.
<?php
/*
The problem.
Input is a string—a paragraph of text. One of the paragraphs above would be fine.
Output is a report listing how many words there are with X letters, like:
10 words with 1 letter
20 words with 2 letters
7 words with 3 letters
15 words with 4 letters, etc.
*/
$strings = array(
'Time yourself.',
'Write this code in any language you want. Use your best language. If you can do many, PHP, Python and Javascript are preferred.',
'Write it out longhand or in a simple text editor.',
'I don’t care much about syntax. You can fix whether it’s isArray or is_Array later. If it has some obvious bug you’d fix in a second, fine.',
'This is not a trick question.',
'I’m not asking for some imaginary “best answer” that does everything in one line of self-writing code, or whatever.'
);
$counts = array();
foreach($strings as $string) {
$words = str_word_count($string, 1);
foreach($words as $word) {
$lenght = strlen($word);
if (isset($counts[$lenght])) {
$counts[$lenght]++;
} else {
$counts[$lenght] = 1;
}
}
}
ksort($counts);
foreach($counts as $num=>$words) {
echo $num .' word';
echo ($num > 1) ? 's' : null;
echo ' with ';
echo $words .' letter';
echo ($words > 1) ? 's' : null;
echo PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment