Created
June 26, 2018 18:47
-
-
Save jacobwyke/017e1def0c514d134031abb1f345f102 to your computer and use it in GitHub Desktop.
Question2
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 | |
/* | |
* File data: | |
* aaa jkj dfd qwerty | |
* fff aaa bbb qwerty | |
* jkj dfd bbb | |
* aaa aaa aaa qwerty | |
* | |
* Usage: php 2.php data.txt | |
* | |
* Output: | |
* 5 aaa | |
* 2 bbb | |
* 2 dfd | |
* 1 fff | |
* 2 jkj | |
* 3 qwerty | |
* | |
*/ | |
//ensure that a file name was given | |
if(empty($argv[1])){ | |
echo 'Please pass a file as first param.'.PHP_EOL; | |
exit; | |
} | |
//store file name | |
$strFile = $argv[1]; | |
//create array to hold words | |
$arrWords = []; | |
//read the file | |
$resFP = fopen($strFile, 'r'); | |
while($strLine = stream_get_line($resFP, 1024 * 1024, "\n")){ | |
//loop through each line and break into individual words | |
foreach(explode(' ', $strLine) as $strWord){ | |
//trim the words to clean up input | |
$strWord = trim($strWord); | |
if($strWord){ | |
if(isset($arrWords[$strWord])){ | |
//increment count | |
$arrWords[$strWord]++; | |
}else{ | |
//create first record of word | |
$arrWords[$strWord] = 1; | |
} | |
} | |
} | |
} | |
fclose($resFP); | |
//sort array into alphabetical order | |
ksort($arrWords); | |
//print results | |
foreach($arrWords as $strWord => $numCount){ | |
echo $numCount.' '.$strWord.PHP_EOL; | |
} |
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
aaa jkj dfd qwerty | |
fff aaa bbb qwerty | |
jkj dfd bbb | |
aaa aaa aaa qwerty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment