Letter frequency: Difference between revisions
Content added Content deleted
(jq) |
(→{{header|jq}}: use an object as a hash) |
||
Line 1,010: | Line 1,010: | ||
=={{header|jq}}== |
=={{header|jq}}== |
||
The following program will report the frequency of all characters in the input file, including newlines, returns, etc, provided the file will fit in memory.<lang jq> |
The following program will report the frequency of all characters in the input file, including newlines, returns, etc, provided the file will fit in memory.<lang jq> |
||
# This function uses an object as a hash table for integers. |
|||
# Input: an array |
|||
# |
# The input is an array of int; |
||
# the output is an object with the imploded values as keys, |
|||
⚫ | |||
# the values of which are the corresponding frequencies. |
|||
reduce .[] as $item |
|||
⚫ | |||
( []; |
|||
map( [.] | implode ) |
|||
if . == [] then [ [ $item, 1] ] |
|||
| reduce .[] as $item ( {}; .[$item] += 1 ) ; |
|||
| if $last[0] == $item |
|||
then (.[0:length-1] + [ [$item, $last[1] + 1] ] ) |
|||
else . + [[$item, 1]] |
|||
end |
|||
end ) ; |
|||
# For neatness we sort the keys: |
|||
explode | sort | runs | map( [ ( [.[0]] | implode) , .[1] ] ) | .[]</lang> |
|||
explode | count | . as $counts | keys | sort[] | [., $counts[.] ] |
|||
</lang> |
|||
Example:<lang sh>jq -s -R -c -f Letter_frequency.jq somefile.txt</lang> |
Example:<lang sh>jq -s -R -c -f Letter_frequency.jq somefile.txt</lang> |
||
{{Out}} |
{{Out}} |