A word frequency counter. How often does each word show up in an array of words? Print out a report. (Hint: Use a hash to count of the number of appearances of each word.)
Just started to go through perl tutorial, and can't figure out the solution for this problem, help! Tnks?
Very simple using hash:
@words = ("hello" , "weary" , "dreary" , "weary");
%num = ();
foreach $word(@words) {
$num{$word} ++;
}
foreach $key(keys %num) {
print"$key appears $num{$key} times\n";
}
Explanation:
%num is a hash which maps a word to the number of times it appears in the array.
The number of occurrences is calculated by scanning the array and then incrementing the number mapped to the word.
$num {$word} = 0 by default and since there can only be one mapping per word we get a unique number per word.
The final loop goes through each key of the hash which we have defined as unique words in the array and printing out the number assigned to it.
More detail:
foreach $word(@words) {
$num{$word} ++;
}
First iteration sets $num{'hello'} = 0++ = 1;
Then $num{'weary'} = 1 and then $num{'dreary'} = 1;
Now we find the second instance of weary.
Since we have already defined a hash map of the word weary,
$num{'weary'} ++ = 1 + 1 =2 giving correct number of instances of weary.
foreach $key(keys %num) {
print"$key appears $num{$key} times\n";
}
This loops through each key of %num. We have defined each key as a unique word so $num($key) gives the number mapped to the word which is what we want.
Reply:It seems that you don't know what a hash is. It's a data structure that lets you associate a value with a string. This problem is hinting you to use a hash to associate an integer (the frequency) with a string (a word found in the array). Does that point you in the right direction? (No, I'm not going to give you the answer... 8-)
Reply:Go though the array from the first element and compare it with every other element if it matches than its the same word increment that words count by 1, and also delete the matching word, or put a Null in its place, this is so you dont count it again. Do this for every word in the array.
Im not sure how they want you to use a Hash, I guess you could hash every word in the array and then do the same thing.
sim cards
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment