Programming Search⌘K

Taskintro

Detect anagrams

Also called anagram, anagram check, are anagrams, valid anagram, group anagrams, anagram groups, same letters, letter multiset.

Check whether two texts use the same letters the same number of times, with case, spaces and punctuation ignored: count the letters, or sort them and compare. Group anagrams by their sorted letters.

Task

Wikipedia defines an anagram as "a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once"1. So listen and silent are anagrams, and so are Dormitory and dirty room. The Rosetta Code task says that words "composed of the same characters, but in a different order"2 are anagrams, and it asks for the largest sets of anagrams in a word list.

The function are_anagrams(a, b) returns true when the two texts hold each letter from a to z the same number of times. Upper case letters count as lower case letters. Spaces, punctuation and digits do not count. The contract uses ASCII text.

The definition counts each letter. It is not enough that the two texts use the same set of letters: aab and abb use the letters a and b, but they are not anagrams. Some puzzles also say that a word is not an anagram of itself. This task does not, so are_anagrams("stop", "stop") is true.

Solutions

There are two methods:

  • Count the letters. Keep 26 counters. Add 1 for each letter of a, and subtract 1 for each letter of b. The texts are anagrams if all counters are 0 at the end. This takes O(n) time, and the memory does not grow with the text.
  • Sort the letters. Keep the letters of each text, in lower case, sort them, and compare the two results. This takes O(n log n) time. The sorted letters are also the key that groups anagrams.
Language Method Counters or key
Python count collections.Counter, compared with ==
JavaScript, TypeScript count an array of 26 numbers
Java count int[26]
C# count Span<int> of 26, with stackalloc
Go count [26]int, compared with ==
Rust count [usize; 26], compared with ==
C count int[26]
C++ count std::array<int, 26>, compared with ==
Bash sort fold -w1, sort and tr -d
  • Python. "A Counter is a dict subclass for counting hashable objects"3. The solution builds one Counter of the letters of each text. Two counters compare equal when each element has the same count. "In equality tests, missing elements are treated as having zero counts"3.
  • Java, C#, JavaScript, TypeScript and C. One array of 26 counters. The index of a letter is c - 'a' after the change to lower case. The solution adds for a, subtracts for b, and checks that all counters are 0.
  • Go, Rust and C++. A helper counts the letters of one text into a fixed array. Arrays of the same type compare with == in these languages, so the result is counts(a) == counts(b).
  • Bash. A helper changes the text to lower case with ${1,,}, removes all characters except a to z, puts each letter on its own line with fold -w1, sorts the lines with LC_ALL=C sort, and joins them again with tr -d '\n'. Two texts are anagrams when the helper prints the same text for both.

To group the anagrams in a word list, as the Rosetta Code task asks, use a map. The key of a word is its letters in sorted order, and the value is the list of words with that key:

from collections import defaultdict


def group_anagrams(words):
    groups = defaultdict(list)
    for word in words:
        groups["".join(sorted(word.lower()))].append(word)
    return [group for group in groups.values() if len(group) > 1]


words = ["listen", "google", "silent", "enlist", "banana", "inlets", "elgoog"]
print(group_anagrams(words))
print(sorted("listen"), "".join(sorted("listen")))
Output
[['listen', 'silent', 'enlist', 'inlets'], ['google', 'elgoog']]
['e', 'i', 'l', 'n', 's', 't'] eilnst

Edge cases

  • Two empty texts. No letters on either side, so all counts are equal. The result is true.
  • One empty text. a and the empty text are not anagrams.
  • The same letters, other counts. aab and abb are not anagrams.
  • One letter more. abc and abcd are not anagrams.
  • Case. Listen and SILENT are anagrams.
  • The same word. stop and stop are anagrams under this contract.
  • Spaces and punctuation. The eyes! and They see. are anagrams. A text with only punctuation has no letters, so !? and ... give true.

Pitfalls

  • Comparing sets. A set keeps each letter once, so it loses the counts. A length check before the cleaning step is also wrong, because the spaces and the punctuation change the length:

This code runs but gives a wrong answer on purpose.

def are_anagrams_set(a, b):
    return set(a.lower()) == set(b.lower())


def are_anagrams_length(a, b):
    if len(a) != len(b):
        return False
    return sorted(a.lower()) == sorted(b.lower())


print(are_anagrams_set("aab", "abb"))
print(are_anagrams_length("Dormitory", "dirty room"))
Output
True
False

Both answers are wrong. Count the letters, and check lengths only after the cleaning step, if at all.

  • Letters of other scripts. Character.isLetter in Java "Determines if the specified character is a letter"4 in all of Unicode, not only A to Z. With an array of 26 counters, the index c - 'a' of such a letter is out of range. For Unicode text, use a map from code point to count, and normalize the text first.
  • The locale in a change of case. In Java, toLowerCase() without an argument uses the rules of the default locale, and "may produce unexpected results if used for strings that are intended to be interpreted locale independently"5. In a Turkish locale, I becomes a dotless ı, so I and i do not match. Use toLowerCase(Locale.ROOT), or change only A to Z.
  • A sort that copies. The sort method sorts the letters of both texts. For two long texts, the count method is faster and uses less memory.

Code

The build runs the native tests of each language in a pinned toolchain.

anagrams.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-anagrams/.

from collections import Counter


def letter_counts(text: str) -> Counter[str]:
    """Count the ASCII letters of text, with upper case as lower case."""
    return Counter(c.lower() for c in text if c.isascii() and c.isalpha())


def are_anagrams(a: str, b: str) -> bool:
    """Return True if a and b hold each letter the same number of times.
    Case, spaces, punctuation and digits do not count."""
    return letter_counts(a) == letter_counts(b)


if __name__ == "__main__":
    print(are_anagrams("Dormitory", "dirty room"))
test_anagrams.py 28 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-anagrams/.

import pytest

from anagrams import are_anagrams

CASES = [
    ("listen-silent", "listen", "silent", True),
    ("dormitory", "Dormitory", "dirty room", True),
    ("hello-world", "hello", "world", False),
    ("both-empty", "", "", True),
    ("one-empty", "a", "", False),
    ("same-set-other-counts", "aab", "abb", False),
    ("extra-letter", "abc", "abcd", False),
    ("same-length-other-letters", "abc", "abd", False),
    ("case", "Listen", "SILENT", True),
    ("same-word", "stop", "stop", True),
    ("gentleman", "a gentleman", "elegant man", True),
    ("they-see", "The eyes!", "They see.", True),
    ("punctuation-only", "!?", "...", True),
]


@pytest.mark.parametrize(("name", "a", "b", "want"), CASES, ids=[c[0] for c in CASES])
def test_are_anagrams(name, a, b, want):
    assert are_anagrams(a, b) is want
    assert are_anagrams(b, a) is want
anagrams.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

#ifndef ANAGRAMS_HPP
#define ANAGRAMS_HPP

#include <array>
#include <cctype>
#include <string_view>

// Returns the count of each ASCII letter of text, with upper case as lower case.
inline std::array<int, 26> letter_counts(std::string_view text) {
    std::array<int, 26> counts{};
    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;
}

// Returns true if a and b hold each letter from a to z the same number of
// times. Case, spaces, punctuation and digits do not count.
inline bool are_anagrams(std::string_view a, std::string_view b) {
    return letter_counts(a) == letter_counts(b);
}

#endif
test_anagrams.cpp 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

#include <cstdio>

#include "anagrams.hpp"

namespace {

struct test_case {
    const char* name;
    const char* a;
    const char* b;
    bool want;
};

const test_case cases[] = {
    {"listen-silent", "listen", "silent", true},
    {"dormitory", "Dormitory", "dirty room", true},
    {"hello-world", "hello", "world", false},
    {"both-empty", "", "", true},
    {"one-empty", "a", "", false},
    {"same-set-other-counts", "aab", "abb", false},
    {"extra-letter", "abc", "abcd", false},
    {"same-length-other-letters", "abc", "abd", false},
    {"case", "Listen", "SILENT", true},
    {"same-word", "stop", "stop", true},
    {"gentleman", "a gentleman", "elegant man", true},
    {"they-see", "The eyes!", "They see.", true},
    {"punctuation-only", "!?", "...", true},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        if (are_anagrams(c.a, c.b) != c.want || are_anagrams(c.b, c.a) != c.want) {
            std::printf("FAIL %s\n", c.name);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Anagrams.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

/** Checks whether two texts are anagrams. */
public final class Anagrams {
    private Anagrams() {}

    /** Returns the index 0 to 25 of an ASCII letter, or -1 for every other character. */
    private static int index(char c) {
        if (c >= 'a' && c <= 'z') {
            return c - 'a';
        }
        if (c >= 'A' && c <= 'Z') {
            return c - 'A';
        }
        return -1;
    }

    /**
     * Returns true if a and b hold each letter from a to z the same number of
     * times. Case, spaces, punctuation and digits do not count.
     */
    public static boolean areAnagrams(String a, String b) {
        int[] counts = new int[26];
        for (int k = 0; k < a.length(); k++) {
            int i = index(a.charAt(k));
            if (i >= 0) {
                counts[i]++;
            }
        }
        for (int k = 0; k < b.length(); k++) {
            int i = index(b.charAt(k));
            if (i >= 0) {
                counts[i]--;
            }
        }
        for (int n : counts) {
            if (n != 0) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(areAnagrams("Dormitory", "dirty room"));
    }
}
AnagramsTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

import static org.junit.jupiter.api.Assertions.assertEquals;

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 AnagramsTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("listen-silent", "listen", "silent", true),
                Arguments.of("dormitory", "Dormitory", "dirty room", true),
                Arguments.of("hello-world", "hello", "world", false),
                Arguments.of("both-empty", "", "", true),
                Arguments.of("one-empty", "a", "", false),
                Arguments.of("same-set-other-counts", "aab", "abb", false),
                Arguments.of("extra-letter", "abc", "abcd", false),
                Arguments.of("same-length-other-letters", "abc", "abd", false),
                Arguments.of("case", "Listen", "SILENT", true),
                Arguments.of("same-word", "stop", "stop", true),
                Arguments.of("gentleman", "a gentleman", "elegant man", true),
                Arguments.of("they-see", "The eyes!", "They see.", true),
                Arguments.of("punctuation-only", "!?", "...", true)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void areAnagrams(String name, String a, String b, boolean want) {
        assertEquals(want, Anagrams.areAnagrams(a, b));
        assertEquals(want, Anagrams.areAnagrams(b, a));
    }
}
anagrams.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

#include "anagrams.h"

#include <ctype.h>

// count adds step to the counter of each letter of text.
static void count(int counts[26], const char *text, int step) {
    for (const char *p = text; *p != '\0'; p++) {
        unsigned char c = (unsigned char)*p;
        if (isalpha(c)) {
            counts[tolower(c) - 'a'] += step;
        }
    }
}

bool are_anagrams(const char *a, const char *b) {
    int counts[26] = {0};
    count(counts, a, 1);
    count(counts, b, -1);
    for (int i = 0; i < 26; i++) {
        if (counts[i] != 0) {
            return false;
        }
    }
    return true;
}
anagrams.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

#ifndef ANAGRAMS_H
#define ANAGRAMS_H

#include <stdbool.h>

// Returns true if a and b hold each letter from a to z the same number of
// times. Case, spaces, punctuation and digits do not count.
bool are_anagrams(const char *a, const char *b);

#endif
test_anagrams.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

#include "anagrams.h"

#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    const char *a;
    const char *b;
    bool want;
};

static const struct test_case cases[] = {
    {"listen-silent", "listen", "silent", true},
    {"dormitory", "Dormitory", "dirty room", true},
    {"hello-world", "hello", "world", false},
    {"both-empty", "", "", true},
    {"one-empty", "a", "", false},
    {"same-set-other-counts", "aab", "abb", false},
    {"extra-letter", "abc", "abcd", false},
    {"same-length-other-letters", "abc", "abd", false},
    {"case", "Listen", "SILENT", true},
    {"same-word", "stop", "stop", true},
    {"gentleman", "a gentleman", "elegant man", true},
    {"they-see", "The eyes!", "They see.", true},
    {"punctuation-only", "!?", "...", true},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        if (are_anagrams(c->a, c->b) != c->want || are_anagrams(c->b, c->a) != c->want) {
            printf("FAIL %s\n", c->name);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Anagrams.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

using System;

/// <summary>Checks whether two texts are anagrams.</summary>
public static class Anagrams
{
    /// <summary>
    /// Returns true if a and b hold each letter from a to z the same number
    /// of times. Case, spaces, punctuation and digits do not count.
    /// </summary>
    public static bool AreAnagrams(string a, string b)
    {
        Span<int> counts = stackalloc int[26];
        foreach (var c in a)
        {
            if (char.IsAsciiLetter(c))
            {
                counts[char.ToLowerInvariant(c) - 'a']++;
            }
        }
        foreach (var c in b)
        {
            if (char.IsAsciiLetter(c))
            {
                counts[char.ToLowerInvariant(c) - 'a']--;
            }
        }
        foreach (var n in counts)
        {
            if (n != 0)
            {
                return false;
            }
        }
        return true;
    }
}
AnagramsTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

using Xunit;

public sealed class AnagramsTests
{
    public static TheoryData<string, string, string, bool> Cases => new()
    {
        { "listen-silent", "listen", "silent", true },
        { "dormitory", "Dormitory", "dirty room", true },
        { "hello-world", "hello", "world", false },
        { "both-empty", "", "", true },
        { "one-empty", "a", "", false },
        { "same-set-other-counts", "aab", "abb", false },
        { "extra-letter", "abc", "abcd", false },
        { "same-length-other-letters", "abc", "abd", false },
        { "case", "Listen", "SILENT", true },
        { "same-word", "stop", "stop", true },
        { "gentleman", "a gentleman", "elegant man", true },
        { "they-see", "The eyes!", "They see.", true },
        { "punctuation-only", "!?", "...", true },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void AreAnagrams(string name, string a, string b, bool want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Anagrams.AreAnagrams(a, b));
        Assert.Equal(want, Anagrams.AreAnagrams(b, a));
    }
}
anagrams.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

function count(counts, text, step) {
  for (const c of text.toLowerCase()) {
    const i = c.charCodeAt(0) - 97;
    if (i >= 0 && i < 26) {
      counts[i] += step;
    }
  }
}

/**
 * Returns true if a and b hold each letter from a to z the same number of
 * times. Case, spaces, punctuation and digits do not count.
 */
export function areAnagrams(a, b) {
  const counts = new Array(26).fill(0);
  count(counts, a, 1);
  count(counts, b, -1);
  return counts.every((n) => n === 0);
}
anagrams.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { areAnagrams } from "./anagrams.js";

const cases = [
  ["listen-silent", "listen", "silent", true],
  ["dormitory", "Dormitory", "dirty room", true],
  ["hello-world", "hello", "world", false],
  ["both-empty", "", "", true],
  ["one-empty", "a", "", false],
  ["same-set-other-counts", "aab", "abb", false],
  ["extra-letter", "abc", "abcd", false],
  ["same-length-other-letters", "abc", "abd", false],
  ["case", "Listen", "SILENT", true],
  ["same-word", "stop", "stop", true],
  ["gentleman", "a gentleman", "elegant man", true],
  ["they-see", "The eyes!", "They see.", true],
  ["punctuation-only", "!?", "...", true],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    assert.equal(areAnagrams(a, b), want);
    assert.equal(areAnagrams(b, a), want);
  });
}
anagrams.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

function count(counts: number[], text: string, step: number): void {
  for (const c of text.toLowerCase()) {
    const i = c.charCodeAt(0) - 97;
    if (i >= 0 && i < 26) {
      counts[i] += step;
    }
  }
}

/**
 * Returns true if a and b hold each letter from a to z the same number of
 * times. Case, spaces, punctuation and digits do not count.
 */
export function areAnagrams(a: string, b: string): boolean {
  const counts = new Array(26).fill(0);
  count(counts, a, 1);
  count(counts, b, -1);
  return counts.every((n) => n === 0);
}
anagrams.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { areAnagrams } from "./anagrams.ts";

const cases: [string, string, string, boolean][] = [
  ["listen-silent", "listen", "silent", true],
  ["dormitory", "Dormitory", "dirty room", true],
  ["hello-world", "hello", "world", false],
  ["both-empty", "", "", true],
  ["one-empty", "a", "", false],
  ["same-set-other-counts", "aab", "abb", false],
  ["extra-letter", "abc", "abcd", false],
  ["same-length-other-letters", "abc", "abd", false],
  ["case", "Listen", "SILENT", true],
  ["same-word", "stop", "stop", true],
  ["gentleman", "a gentleman", "elegant man", true],
  ["they-see", "The eyes!", "They see.", true],
  ["punctuation-only", "!?", "...", true],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    assert.equal(areAnagrams(a, b), want);
    assert.equal(areAnagrams(b, a), want);
  });
}
anagrams.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

// Package anagrams checks whether two texts are anagrams.
package anagrams

// counts returns the count of each ASCII letter of s, with upper case as
// lower case. b | 0x20 changes A to Z to a to z, and it moves no other byte
// into the range a to z.
func counts(s string) [26]int {
	var c [26]int
	for i := 0; i < len(s); i++ {
		if b := s[i] | 0x20; b >= 'a' && b <= 'z' {
			c[b-'a']++
		}
	}
	return c
}

// AreAnagrams reports whether a and b hold each letter from a to z the same
// number of times. Case, spaces, punctuation and digits do not count.
func AreAnagrams(a, b string) bool {
	return counts(a) == counts(b)
}
anagrams_test.go 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

package anagrams

import "testing"

var cases = []struct {
	name string
	a    string
	b    string
	want bool
}{
	{"listen-silent", "listen", "silent", true},
	{"dormitory", "Dormitory", "dirty room", true},
	{"hello-world", "hello", "world", false},
	{"both-empty", "", "", true},
	{"one-empty", "a", "", false},
	{"same-set-other-counts", "aab", "abb", false},
	{"extra-letter", "abc", "abcd", false},
	{"same-length-other-letters", "abc", "abd", false},
	{"case", "Listen", "SILENT", true},
	{"same-word", "stop", "stop", true},
	{"gentleman", "a gentleman", "elegant man", true},
	{"they-see", "The eyes!", "They see.", true},
	{"punctuation-only", "!?", "...", true},
}

func TestAreAnagrams(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := AreAnagrams(c.a, c.b); got != c.want {
				t.Fatalf("AreAnagrams(%q, %q) = %v, want %v", c.a, c.b, got, c.want)
			}
			if got := AreAnagrams(c.b, c.a); got != c.want {
				t.Fatalf("AreAnagrams(%q, %q) = %v, want %v", c.b, c.a, got, c.want)
			}
		})
	}
}
anagrams.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

/// Returns the count of each ASCII letter of text, with upper case as lower case.
fn counts(text: &str) -> [usize; 26] {
    let mut c = [0; 26];
    for b in text.bytes().filter(u8::is_ascii_alphabetic) {
        c[usize::from(b.to_ascii_lowercase() - b'a')] += 1;
    }
    c
}

/// Returns true if a and b hold each letter from a to z the same number of
/// times. Case, spaces, punctuation and digits do not count.
pub fn are_anagrams(a: &str, b: &str) -> bool {
    counts(a) == counts(b)
}
tests/anagrams_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-anagrams/.

use algo_detect_anagrams::are_anagrams;

const CASES: &[(&str, &str, &str, bool)] = &[
    ("listen-silent", "listen", "silent", true),
    ("dormitory", "Dormitory", "dirty room", true),
    ("hello-world", "hello", "world", false),
    ("both-empty", "", "", true),
    ("one-empty", "a", "", false),
    ("same-set-other-counts", "aab", "abb", false),
    ("extra-letter", "abc", "abcd", false),
    ("same-length-other-letters", "abc", "abd", false),
    ("case", "Listen", "SILENT", true),
    ("same-word", "stop", "stop", true),
    ("gentleman", "a gentleman", "elegant man", true),
    ("they-see", "The eyes!", "They see.", true),
    ("punctuation-only", "!?", "...", true),
];

#[test]
fn cases() {
    for &(name, a, b, want) in CASES {
        assert_eq!(are_anagrams(a, b), want, "{name}");
        assert_eq!(are_anagrams(b, a), want, "{name} swapped");
    }
}
anagrams.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-anagrams/.

# _anagram_key text: print the letters of text, in lower case, in sorted order.
_anagram_key() {
  local s=${1,,}
  s=${s//[^a-z]/}
  [[ -z $s ]] && return
  printf '%s' "$s" | fold -w1 | LC_ALL=C sort | tr -d '\n'
}

# are_anagrams a b: print true if a and b hold each letter from a to z the
# same number of times, and false if not. Case, spaces, punctuation and
# digits do not count.
are_anagrams() {
  if [[ $(_anagram_key "$1") == "$(_anagram_key "$2")" ]]; then
    echo true
  else
    echo false
  fi
}
test_anagrams.bats 111 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-anagrams/.

setup() {
  source "$BATS_TEST_DIRNAME/anagrams.sh"
}

@test "listen-silent" {
  run are_anagrams 'listen' 'silent'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams 'silent' 'listen'
  [ "$output" = true ]
}

@test "dormitory" {
  run are_anagrams 'Dormitory' 'dirty room'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams 'dirty room' 'Dormitory'
  [ "$output" = true ]
}

@test "hello-world" {
  run are_anagrams 'hello' 'world'
  [ "$status" -eq 0 ]
  [ "$output" = false ]
  run are_anagrams 'world' 'hello'
  [ "$output" = false ]
}

@test "both-empty" {
  run are_anagrams '' ''
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams '' ''
  [ "$output" = true ]
}

@test "one-empty" {
  run are_anagrams 'a' ''
  [ "$status" -eq 0 ]
  [ "$output" = false ]
  run are_anagrams '' 'a'
  [ "$output" = false ]
}

@test "same-set-other-counts" {
  run are_anagrams 'aab' 'abb'
  [ "$status" -eq 0 ]
  [ "$output" = false ]
  run are_anagrams 'abb' 'aab'
  [ "$output" = false ]
}

@test "extra-letter" {
  run are_anagrams 'abc' 'abcd'
  [ "$status" -eq 0 ]
  [ "$output" = false ]
  run are_anagrams 'abcd' 'abc'
  [ "$output" = false ]
}

@test "same-length-other-letters" {
  run are_anagrams 'abc' 'abd'
  [ "$status" -eq 0 ]
  [ "$output" = false ]
  run are_anagrams 'abd' 'abc'
  [ "$output" = false ]
}

@test "case" {
  run are_anagrams 'Listen' 'SILENT'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams 'SILENT' 'Listen'
  [ "$output" = true ]
}

@test "same-word" {
  run are_anagrams 'stop' 'stop'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams 'stop' 'stop'
  [ "$output" = true ]
}

@test "gentleman" {
  run are_anagrams 'a gentleman' 'elegant man'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams 'elegant man' 'a gentleman'
  [ "$output" = true ]
}

@test "they-see" {
  run are_anagrams 'The eyes!' 'They see.'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams 'They see.' 'The eyes!'
  [ "$output" = true ]
}

@test "punctuation-only" {
  run are_anagrams '!?' '...'
  [ "$status" -eq 0 ]
  [ "$output" = true ]
  run are_anagrams '...' '!?'
  [ "$output" = true ]
}

References

  1. Anagram, Wikipedia, Introduction
  2. Rosetta Code, Anagrams (task text, from acmeism/RosettaCodeData), task text
  3. collections, Container datatypes, Python documentation, Counter objects
  4. Character (Java SE 25 and JDK 25), Oracle, isLetter(char)
  5. String (Java SE 25 and JDK 25), Oracle, toLowerCase()

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source