Letter frequency: Difference between revisions

Content added Content deleted
(→‎{{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>
# Input: an array of strings.
# This function uses an object as a hash table for integers.
# Output: an object with the strings as keys,
# 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.
# the values of which are the corresponding frequencies.
def count:
def counter:
reduce .[] as $item ( {}; .[$item] += 1 ) ;
map( [.] | implode )
| reduce .[] as $item ( {}; .[$item] += 1 ) ;


# For neatness we sort the keys:
# For neatness we sort the keys:
explode | count | . as $counts | keys | sort[] | [., $counts[.] ]
explode | map( [.] | implode ) | counter | . as $counter
| keys | sort[] | [., $counter[.] ]

</lang>
</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>