#!/usr/bin/env bash TOWEL_FILE=$1 DESIGN_FILE=$2 read -r -a TOWELS <<< "$( < "$TOWEL_FILE" tr ',' ' ' | paste -s -d " " )" read -r -a DESIGNS <<< "$( < "$DESIGN_FILE" paste -s -d " " )" # Check if towel is a viable match match_towel () { TOWEL=$1 MATCH=$2 FULL_DESIGN=$3 TO_MATCH="$MATCH$TOWEL" PARTIAL_DESIGN=${FULL_DESIGN::${#TO_MATCH}} if [[ $PARTIAL_DESIGN == "$TO_MATCH" ]] then return 0 else return 1 fi } TOTAL_VALID=0 # Loop through designs for DESIGN in "${DESIGNS[@]}" do # The idea is for each design, keep a sum of combinations # for each index position of the DESIGN string # Since the branches "multiply", just take the sum # at the starting index, and add it to the end # of the "combined" index # for each possible combination. printf "Starting design : %s\n" "$DESIGN" declare -A POINTER_LIST POINTER_LIST[0]=1 POINTER_END=$(( ${#DESIGN} )) while true do POINTER=${#DESIGN} # Pick lowest pointer value for P in "${!POINTER_LIST[@]}" do if [[ $P -lt $POINTER ]] then POINTER=$P fi done POINTER_VALUE=${POINTER_LIST[$POINTER]} # Check if end has reached if [[ $POINTER -eq $POINTER_END ]] then break fi # Loop through towels and remove earliest pointer for TOWEL in "${TOWELS[@]}" do TOWEL_LEN=${#TOWEL} END=$(( POINTER + TOWEL_LEN )) if [[ ${DESIGN:$POINTER:$TOWEL_LEN} == "$TOWEL" ]] then POINTER_LIST[$END]=$(( ${POINTER_LIST[$END]} + POINTER_VALUE )) fi done # Done looping through for specific point unset "POINTER_LIST[$POINTER]" done printf "Total matches for %s is %s.\n" "$DESIGN" "${POINTER_LIST[$POINTER_END]}" TOTAL_VALID=$(( TOTAL_VALID + POINTER_LIST[$POINTER_END] )) unset "POINTER_LIST" done printf "Total valid designs: %s\n" "$TOTAL_VALID"