#!/bin/bash

# Shell script that solves the NYT Letterboxed puzzle in two words
# By Graham Lazorchak, 2021

# Each side of the box is a separate argument:

CHARS=$1$2$3$4

# You may need to replace "/usr/share/dict/words" with
# a different path if you are not on a Unix-like system
# or you would like to use a dictionary stored in a
# different location.

egrep "^[$CHARS]+$" /usr/share/dict/words | sed -E "/[$1]{2}/d" | sed -E "/[$2]{2}/d" | sed -E "/[$3]{2}/d" | sed -E "/[$4]{2}/d" | awk '{ print length(), $0 | "sort -n -r" }' | cut -d ' ' -f2- > tmp

for i in $(cat ./tmp); do
    char="${i: -1}"
    egrep "^$char" tmp > sol
    for j in $(cat ./sol); do
        count=0
        for ((k=0; k<${#CHARS}; k++)); do
            if [[ $i$j == *${CHARS:$k:1}* ]]; then
              let "count++"
            fi
        done
        if [[ $count == ${#CHARS} ]]; then      
            echo "$i $j"
        fi
    done
done
echo "Done."