Jump to content

Letter frequency: Difference between revisions

→‎{{header|jq}}: use an object as a hash
(jq)
(→‎{{header|jq}}: use an object as a hash)
Line 1,010:
=={{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>
# This function uses an object as a hash table for integers.
# Input: an array
# Output:The input is an array of [item, count] for each runint;
# the output is an object with the imploded values as keys,
def runs:
# the values of which are the corresponding frequencies.
reduce .[] as $item
def runscount:
( [];
map( [.] | implode )
if . == [] then [ [ $item, 1] ]
| reduce .[] as else$item ( {}; .[-1$item] as+= $last1 ) ;
| 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>
{{Out}}
2,502

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.