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
# Output: an array of [item, count] for each run
# The input is an array of int;
# 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 count:
( [];
map( [.] | implode )
if . == [] then [ [ $item, 1] ]
else .[-1] as $last
| 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}}