Skip to content

Instantly share code, notes, and snippets.

@drbr
Created November 27, 2023 05:44
Show Gist options
  • Save drbr/c0c32b01b1d14a17eb102e6fd3e04f52 to your computer and use it in GitHub Desktop.
Save drbr/c0c32b01b1d14a17eb102e6fd3e04f52 to your computer and use it in GitHub Desktop.
Bash script to solve the NYT Spelling Bee
#!/bin/bash
dictPath="/usr/share/dict/words"
middleLetter=$1
allLetters=$2
# The following argument validations must be true in order for the script to be correct
[[ -n "$middleLetter" && -n "$allLetters " ]] || { echo "Usage: ./spellingBee.sh <middle letter> <all letters>"; exit 0; }
[[ "$middleLetter" =~ ^[a-zA-z]$ ]] || { echo "Usage: Middle letter must be a single letter"; exit 0; }
[[ "$allLetters" =~ ^[a-zA-z]+$ ]] || { echo "Usage: Arguments must contain only letters"; exit 0; }
# First, filter to words that definitely contain the middle letter.
# Then, using extended grep syntax, filter to words containing only the allowed letters.
function validWordsCommand() {
middleLetter=$1
allLetters=$2
command="cat $dictPath | grep -i $middleLetter | grep -Ei '^[${allLetters}]+$' | less"
echo $command
}
# Find the pangram by adding greps at the end to make sure the word contains all of the letters.
# All seven letters should be passed as a single string argument.
function pangramCommand() {
letters=$1
lettersSeparate=$(echo $letters | grep -o .)
command="cat $dictPath | grep -Ei '^[${letters}]+$' "
for l in $lettersSeparate; do
command="${command} | grep -i $l"
done
echo $command
}
# Assemble the commands and print the output, with the pangram(s) at the end.
validWords=$(validWordsCommand $middleLetter $allLetters)
pangram=$(pangramCommand $allLetters)
{ eval $validWords; eval $pangram; } | less
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment