Taskintro
Count the letters of a text
Also called letter frequency, letter count, character frequency, count characters, histogram of letters, frequency table, count each letter.
Count each letter from a to z in a text, with case ignored: an array of 26 counters indexed by the letter, or a map such as Counter. Letters outside ASCII need a map and a case fold.
- Evidence
- Code in 10 languages
Task
The Rosetta Code task is short: "Open a text file and count the occurrences of each letter."1 It adds that "Some of these programs count all characters (including punctuation), but some only count letters A to Z."1 Letter counts are old tools. Wikipedia notes that "Letter frequency analysis dates back to the Arab mathematician Al-Kindi (c. AD 801–873), who formally developed the method to break ciphers."2
The function count_letters(text) returns a list of 26 counts. The count at index 0 is for a, the count at index 1 is for b, and so on to z at index 25. An upper case letter counts as its lower case letter, so AaAa gives 4 at index 0. Other characters, such as digits, spaces and punctuation, do not count. The contract uses ASCII text.
Solutions
The letters a to z have the codes 97 to 122 in ASCII, one after the other. So c - 'a' is the index of a lower case letter c, and an array of 26 counters is enough. For a text with letters outside ASCII, the set of letters is not known in advance, so the program uses a map from the letter to its count.
| Language | Counters | Index of a letter |
|---|---|---|
| Python | collections.Counter, then 26 counts in order |
string.ascii_lowercase gives the order |
| JavaScript, TypeScript | new Array(26).fill(0) |
c.charCodeAt(0) - 97 |
| Java | long[26] |
c - 'a' |
| C# | long[26] |
c - 'a' |
| Go | []int64 of length 26 |
b - 'a' on a byte |
| Rust | vec![0; 26] |
usize::from(b - b'a') on a byte |
| C | an array of 26 long long from the caller |
tolower(c) - 'a' |
| C++ | std::vector<long long>(26) |
std::tolower(c) - 'a' |
| Bash | an indexed array | $(( $(printf '%d' "'$c") - 97 )) |
- Python. The solution counts the letters with
Counterand reads the 26 counts in the order ofstring.ascii_lowercase. ACounterreturns 0 for a letter that it has not seen.most_commongives a list "from the most common to the least"3. "Elements with equal counts are ordered in the order first encountered"3. - JavaScript, TypeScript, Java and C#. The solution changes each
AtoZto lower case, and adds 1 to the counter atc - 'a'if the result is in the rangeatoz. - Go and Rust. The text is ASCII, so the solution reads bytes. Go uses
b | 0x20to change an upper case letter to lower case. - C. The caller gives an array of 26 counters, and the function fills it.
isalphaandtolowertake a value ofunsigned char. - Bash. A
forloop reads each character with${text:i:1}.printf '%d' "'$c"gives the code of the character, because a leading quote makesprintfprint the code. The function prints the 26 counts, one on each line.
Python, with Counter, most_common and a change of case that is not ASCII:
from collections import Counter
text = "The quick brown fox jumps over the lazy dog"
counts = Counter(c for c in text.lower() if c.isalpha())
print(len(counts), counts.most_common(3))
print("Straße".upper(), "ß".lower(), "ß".casefold())
composed, decomposed = "\u00e9", "e\u0301"
print(len(composed), len(decomposed), composed.isalpha(), decomposed.isalpha())
26 [('o', 4), ('e', 3), ('t', 2)]
STRASSE ß ss
1 2 True False
The sentence has all 26 letters. t, h, u and r all occur twice, and most_common lists t because it comes first in the text.
Edge cases
- Empty text. All 26 counts are 0. The result is still a list of 26 numbers, not an empty list.
- No letters.
123 !?gives 26 zeros too. - Case.
AaAagives 4 at index 0, not 2 and 2. - The first and the last letter.
aZgives 1 at index 0 and 1 at index 25. A bound written as< 'z'instead of<= 'z'missesz. - White space. Spaces, tabs and newlines do not count.
Pitfalls
- Letters outside A to Z.
Character.isLetterin Java "Determines if the specified character is a letter"4 in all of Unicode. With an array of 26 counters, the index of such a letter is out of range:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
int[] counts = new int[26];
try {
for (char c : "caf\u00e9".toCharArray()) {
if (Character.isLetter(c)) {
counts[Character.toLowerCase(c) - 'a']++;
}
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
Index 136 out of bounds for length 26
é has the code 233, and 233 - 97 is 136. In C, the same code writes outside the array, and that is undefined behavior. Test the range a to z, or use a map.
- Case in Unicode. One upper case letter can be two lower case letters, and the change can depend on the language.
casefoldin Python "is intended to remove all case distinctions in a string"5:ßstaysßwithlower, and becomessswithcasefold. For caseless counts of Unicode text, usecasefold, notlower. - Code points are not letters.
écan be one code point or two:eand the combining mark U+0301. The mark is not a letter, so a count of the decomposed form findseand noé. Normalize the text, for example to NFC, before you count. - Bytes are not letters. In C, Go and Rust, a loop over the bytes of UTF-8 text sees 2 bytes for
é. That is correct for ASCII only. - A sorted map for the output. A hash map has no fixed order. To print the counts in the order of the alphabet, sort the keys, or use an array as this task does.
Related tasks
- Count word frequencies: the same method for words.
- Detect anagrams: two texts with equal letter counts.
- Apply a Caesar or ROT13 cipher: a cipher that letter counts can break.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
import string
from collections import Counter
def count_letters(text: str) -> list[int]:
"""Return the counts of the letters a to z in text, in the order of the
alphabet. Upper case letters count as lower case letters."""
found = Counter(c for c in text.lower() if c in string.ascii_lowercase)
return [found[c] for c in string.ascii_lowercase]
if __name__ == "__main__":
print(count_letters("Hello, World!"))
test_letters.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
import pytest
from letters import count_letters
CASES = [
("hello", "hello", [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("pangram", "The quick brown fox jumps over the lazy dog", [1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1]),
("mississippi", "Mississippi", [0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]),
("empty", "", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("no-letters", "123 !?", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("mixed-case", "AaAa", [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("first-and-last", "aZ", [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
("only-z", "zzz", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3]),
("white-space", " \t\n", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("sentence", "Count Each Letter, once.", [1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0]),
]
@pytest.mark.parametrize(("name", "text", "want"), CASES, ids=[c[0] for c in CASES])
def test_count_letters(name, text, want):
assert count_letters(text) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
#ifndef LETTERS_HPP
#define LETTERS_HPP
#include <cctype>
#include <cstddef>
#include <string_view>
#include <vector>
// Returns the counts of the letters a to z in text, in the order of the
// alphabet. Upper case letters count as lower case letters.
inline std::vector<long long> count_letters(std::string_view text) {
std::vector<long long> counts(26);
for (const char ch : text) {
const auto c = static_cast<unsigned char>(ch);
if (std::isalpha(c) != 0) {
++counts[static_cast<std::size_t>(std::tolower(c) - 'a')];
}
}
return counts;
}
#endif
test_letters.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
#include <cstdio>
#include <vector>
#include "letters.hpp"
namespace {
struct test_case {
const char* name;
const char* text;
std::vector<long long> want;
};
const test_case cases[] = {
{"hello", "hello", {0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"pangram", "The quick brown fox jumps over the lazy dog", {1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1}},
{"mississippi", "Mississippi", {0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0}},
{"empty", "", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"no-letters", "123 !?", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"mixed-case", "AaAa", {4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"first-and-last", "aZ", {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}},
{"only-z", "zzz", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}},
{"white-space", " \t\n", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"sentence", "Count Each Letter, once.", {1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0}},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
if (count_letters(c.text) != c.want) {
std::printf("FAIL %s\n", c.name);
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
import java.util.Arrays;
/** Counts the letters a to z of a text. */
public final class Letters {
private Letters() {}
/**
* Returns the counts of the letters a to z in text, in the order of the
* alphabet. Upper case letters count as lower case letters. The test on
* the range keeps letters outside ASCII out of the array.
*/
public static long[] countLetters(String text) {
long[] counts = new long[26];
for (int k = 0; k < text.length(); k++) {
char c = text.charAt(k);
if (c >= 'A' && c <= 'Z') {
c = (char) (c - 'A' + 'a');
}
if (c >= 'a' && c <= 'z') {
counts[c - 'a']++;
}
}
return counts;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(countLetters("Hello, World!")));
}
}
LettersTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class LettersTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("hello", "hello", new long[]{0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
Arguments.of("pangram", "The quick brown fox jumps over the lazy dog", new long[]{1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1}),
Arguments.of("mississippi", "Mississippi", new long[]{0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0}),
Arguments.of("empty", "", new long[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
Arguments.of("no-letters", "123 !?", new long[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
Arguments.of("mixed-case", "AaAa", new long[]{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
Arguments.of("first-and-last", "aZ", new long[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}),
Arguments.of("only-z", "zzz", new long[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}),
Arguments.of("white-space", " \t\n", new long[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}),
Arguments.of("sentence", "Count Each Letter, once.", new long[]{1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0})
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void countLetters(String name, String text, long[] want) {
assertArrayEquals(want, Letters.countLetters(text));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
#include "letters.h"
#include <ctype.h>
void count_letters(const char *text, long long counts[26]) {
for (int i = 0; i < 26; i++) {
counts[i] = 0;
}
for (const char *p = text; *p != '\0'; p++) {
unsigned char c = (unsigned char)*p;
if (isalpha(c)) {
counts[tolower(c) - 'a']++;
}
}
}
letters.h 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
#ifndef LETTERS_H
#define LETTERS_H
// Writes the counts of the letters a to z in text to counts[0] to counts[25],
// in the order of the alphabet. Upper case letters count as lower case
// letters.
void count_letters(const char *text, long long counts[26]);
#endif
test_letters.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
#include "letters.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
const char *text;
long long want[26];
};
static const struct test_case cases[] = {
{"hello", "hello", {0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"pangram", "The quick brown fox jumps over the lazy dog", {1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1}},
{"mississippi", "Mississippi", {0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0}},
{"empty", "", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"no-letters", "123 !?", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"mixed-case", "AaAa", {4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"first-and-last", "aZ", {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}},
{"only-z", "zzz", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}},
{"white-space", " \t\n", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"sentence", "Count Each Letter, once.", {1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0}},
};
int main(void) {
int failures = 0;
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
long long got[26];
count_letters(cases[i].text, got);
if (memcmp(got, cases[i].want, sizeof got) != 0) {
printf("FAIL %s\n", cases[i].name);
failures++;
}
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
/// <summary>Counts the letters a to z of a text.</summary>
public static class Letters
{
/// <summary>
/// Returns the counts of the letters a to z in text, in the order of the
/// alphabet. Upper case letters count as lower case letters.
/// </summary>
public static long[] CountLetters(string text)
{
var counts = new long[26];
foreach (var ch in text)
{
if (char.IsAsciiLetter(ch))
{
counts[char.ToLowerInvariant(ch) - 'a']++;
}
}
return counts;
}
}
LettersTests.cs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
using Xunit;
public sealed class LettersTests
{
public static TheoryData<string, string, long[]> Cases => new()
{
{ "hello", "hello", new long[] { 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ "pangram", "The quick brown fox jumps over the lazy dog", new long[] { 1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1 } },
{ "mississippi", "Mississippi", new long[] { 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0 } },
{ "empty", "", new long[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ "no-letters", "123 !?", new long[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ "mixed-case", "AaAa", new long[] { 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ "first-and-last", "aZ", new long[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } },
{ "only-z", "zzz", new long[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3 } },
{ "white-space", " \t\n", new long[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ "sentence", "Count Each Letter, once.", new long[] { 1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void CountLetters(string name, string text, long[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Letters.CountLetters(text));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
/**
* Returns the counts of the letters a to z in text, in the order of the
* alphabet. Upper case letters count as lower case letters.
*/
export function countLetters(text) {
const counts = new Array(26).fill(0);
for (const c of text.toLowerCase()) {
const i = c.charCodeAt(0) - 97;
if (i >= 0 && i < 26) {
counts[i]++;
}
}
return counts;
}
letters.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { countLetters } from "./letters.js";
const cases = [
["hello", "hello", [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["pangram", "The quick brown fox jumps over the lazy dog", [1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1]],
["mississippi", "Mississippi", [0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]],
["empty", "", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["no-letters", "123 !?", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["mixed-case", "AaAa", [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["first-and-last", "aZ", [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]],
["only-z", "zzz", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3]],
["white-space", " \t\n", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["sentence", "Count Each Letter, once.", [1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0]],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.deepEqual(countLetters(text), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
/**
* Returns the counts of the letters a to z in text, in the order of the
* alphabet. Upper case letters count as lower case letters.
*/
export function countLetters(text: string): number[] {
const counts = new Array(26).fill(0);
for (const c of text.toLowerCase()) {
const i = c.charCodeAt(0) - 97;
if (i >= 0 && i < 26) {
counts[i]++;
}
}
return counts;
}
letters.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { countLetters } from "./letters.ts";
const cases: [string, string, number[]][] = [
["hello", "hello", [0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["pangram", "The quick brown fox jumps over the lazy dog", [1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1]],
["mississippi", "Mississippi", [0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]],
["empty", "", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["no-letters", "123 !?", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["mixed-case", "AaAa", [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["first-and-last", "aZ", [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]],
["only-z", "zzz", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3]],
["white-space", " \t\n", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]],
["sentence", "Count Each Letter, once.", [1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0]],
];
for (const [name, text, want] of cases) {
test(name, () => {
assert.deepEqual(countLetters(text), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
// Package letters counts the letters a to z of a text.
package letters
// CountLetters returns the counts of the letters a to z in text, in the order
// of the alphabet. Upper case letters count as lower case letters. The text
// is ASCII, so the function reads bytes.
func CountLetters(text string) []int64 {
counts := make([]int64, 26)
for i := 0; i < len(text); i++ {
if b := text[i] | 0x20; b >= 'a' && b <= 'z' {
counts[b-'a']++
}
}
return counts
}
letters_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
package letters
import (
"slices"
"testing"
)
var cases = []struct {
name string
text string
want []int64
}{
{"hello", "hello", []int64{0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"pangram", "The quick brown fox jumps over the lazy dog", []int64{1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1}},
{"mississippi", "Mississippi", []int64{0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0}},
{"empty", "", []int64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"no-letters", "123 !?", []int64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"mixed-case", "AaAa", []int64{4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"first-and-last", "aZ", []int64{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}},
{"only-z", "zzz", []int64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3}},
{"white-space", " \t\n", []int64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}},
{"sentence", "Count Each Letter, once.", []int64{1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0}},
}
func TestCountLetters(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := CountLetters(c.text); !slices.Equal(got, c.want) {
t.Fatalf("CountLetters(%q) = %v, want %v", c.text, got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
/// Returns the counts of the letters a to z in text, in the order of the
/// alphabet. Upper case letters count as lower case letters. The text is
/// ASCII, so the function reads bytes.
pub fn count_letters(text: &str) -> Vec<i64> {
let mut counts = vec![0; 26];
for b in text.bytes().filter(u8::is_ascii_alphabetic) {
counts[usize::from(b.to_ascii_lowercase() - b'a')] += 1;
}
counts
}
tests/letters_test.rs 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
use algo_count_the_letters_of_a_text::count_letters;
const CASES: &[(&str, &str, &[i64])] = &[
("hello", "hello", &[0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("pangram", "The quick brown fox jumps over the lazy dog", &[1, 1, 1, 1, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 4, 1, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1]),
("mississippi", "Mississippi", &[0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]),
("empty", "", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("no-letters", "123 !?", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("mixed-case", "AaAa", &[4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("first-and-last", "aZ", &[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
("only-z", "zzz", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3]),
("white-space", " \t\n", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
("sentence", "Count Each Letter, once.", &[1, 0, 3, 0, 4, 0, 0, 1, 0, 0, 0, 1, 0, 2, 2, 0, 0, 1, 0, 3, 1, 0, 0, 0, 0, 0]),
];
#[test]
fn cases() {
for &(name, text, want) in CASES {
assert_eq!(count_letters(text), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
# count_letters text: print the counts of the letters a to z in text, one on
# each line, in the order of the alphabet. Upper case letters count as lower
# case letters.
count_letters() {
local text=${1,,} c i
local -a counts=(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
for ((i = 0; i < ${#text}; i++)); do
c=${text:i:1}
if [[ $c == [abcdefghijklmnopqrstuvwxyz] ]]; then
((++counts[$(printf '%d' "'$c") - 97]))
fi
done
printf '%s\n' "${counts[@]}"
}
test_letters.bats 68 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/count-the-letters-of-a-text/.
setup() {
source "$BATS_TEST_DIRNAME/letters.sh"
}
@test "hello" {
run count_letters 'hello'
[ "$status" -eq 0 ]
[ "$output" = $'0\n0\n0\n0\n1\n0\n0\n1\n0\n0\n0\n2\n0\n0\n1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0' ]
}
@test "pangram" {
run count_letters 'The quick brown fox jumps over the lazy dog'
[ "$status" -eq 0 ]
[ "$output" = $'1\n1\n1\n1\n3\n1\n1\n2\n1\n1\n1\n1\n1\n1\n4\n1\n1\n2\n1\n2\n2\n1\n1\n1\n1\n1' ]
}
@test "mississippi" {
run count_letters 'Mississippi'
[ "$status" -eq 0 ]
[ "$output" = $'0\n0\n0\n0\n0\n0\n0\n0\n4\n0\n0\n0\n1\n0\n0\n2\n0\n0\n4\n0\n0\n0\n0\n0\n0\n0' ]
}
@test "empty" {
run count_letters ''
[ "$status" -eq 0 ]
[ "$output" = $'0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0' ]
}
@test "no-letters" {
run count_letters '123 !?'
[ "$status" -eq 0 ]
[ "$output" = $'0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0' ]
}
@test "mixed-case" {
run count_letters 'AaAa'
[ "$status" -eq 0 ]
[ "$output" = $'4\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0' ]
}
@test "first-and-last" {
run count_letters 'aZ'
[ "$status" -eq 0 ]
[ "$output" = $'1\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n1' ]
}
@test "only-z" {
run count_letters 'zzz'
[ "$status" -eq 0 ]
[ "$output" = $'0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n3' ]
}
@test "white-space" {
run count_letters '
'
[ "$status" -eq 0 ]
[ "$output" = $'0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0\n0' ]
}
@test "sentence" {
run count_letters 'Count Each Letter, once.'
[ "$status" -eq 0 ]
[ "$output" = $'1\n0\n3\n0\n4\n0\n0\n1\n0\n0\n0\n1\n0\n2\n2\n0\n0\n1\n0\n3\n1\n0\n0\n0\n0\n0' ]
}
References
- Rosetta Code, Letter frequency (task text, from acmeism/RosettaCodeData), task text
- Letter frequency, Wikipedia, Introduction
- collections, Container datatypes, Python documentation, Counter.most_common
- Character (Java SE 25 and JDK 25), Oracle, isLetter(char)
- Built-in Types, Python documentation, str.casefold
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag ACKW1C Edit this page History Report an error Markdown