Skip to content

Instantly share code, notes, and snippets.

@dspinellis
Created April 24, 2021 15:25
Show Gist options
  • Save dspinellis/f81ea362a3cba7b61a493bd5a7073ef9 to your computer and use it in GitHub Desktop.
Save dspinellis/f81ea362a3cba7b61a493bd5a7073ef9 to your computer and use it in GitHub Desktop.
Find all anagrams in the system's dictionary
#!/bin/sh
#
# Find all anagrams in the system's dictionary by mapping the words
# into a product of prime numbers associated with each letter
#
# Process plain ASCII characters
export LC_ALL=C
# Create commands for the calculator bc
{
# Obtain numbers from 1 to 200
seq 1 200 |
# Factorize them to find primes
factor |
# Assign prime numbers to variables a-z
awk 'BEGIN { n = 97 } NF == 2 {printf("%c = %s\n", n++, $2)}' |
head -26
# Process system dictionary
sed -n '
# Obtain lowercase words
/^[a-z]*$/ {
# Save word
h
# Convert it into a bc command that will print it
s/.*/"& "/
p
# Retrieve word
g
# Convert word into variable multiplications, e.g. h * e * l * l * o
s/./ * &/g
s/..//
p
}' /usr/share/dict/words
} |
# Process commands with bc
bc |
# Save produced map from words into a product of primes
tee map |
# Obtain only the products
cut -d ' ' -f 2 |
# Sort them
sort |
# Obtain duplicate products
uniq -d |
# Find those products as words in the map
fgrep -wf - map |
# Order result by the product
sort -k 2n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment