Created
April 24, 2021 15:25
-
-
Save dspinellis/f81ea362a3cba7b61a493bd5a7073ef9 to your computer and use it in GitHub Desktop.
Find all anagrams in the system's dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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