How to resolve the algorithm ABC problem step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm ABC problem step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid).
There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:

Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.

The rules are simple:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm ABC problem step by step in the UNIX Shell programming language

Source code in the unix programming language

can_build_word() {
    if [[ $1 ]]; then
        can_build_word_rec "$1" BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM 
    else
        return 1
    fi
}

can_build_word_rec() {
    [[ -z $1 ]] && return 0

    local -u word=$1       # uppercase the first parameter
    shift
    local blocks=("$@")

    # see if we have a block for the first letter
    local letter=${word:0:1} indices=() i
    for (( i=0; i<${#blocks[@]}; i++ )); do
        if [[ ${blocks[i]} == *$letter* ]]; then
            indices+=($i)
        fi
    done
    (( ${#indices[@]} == 0 )) && return 1

    local tmp
    for i in ${indices[@]}; do
        tmp=( "${blocks[@]}" )
        unset "tmp[$i]"
        can_build_word_rec "${word:1}" "${tmp[@]}" && return 0
    done

    return 1
}

words=( "" A BARK Book treat COMMON Squad confuse )
for word in "${words[@]}"; do
    can_build_word "$word" "${blocks[@]}" && ans=yes || ans=no
    printf "%s\t%s\n" "$word" $ans
done

  

You may also check:How to resolve the algorithm Date format step by step in the Gambas programming language
You may also check:How to resolve the algorithm Nonoblock step by step in the Java programming language
You may also check:How to resolve the algorithm Matrix digital rain step by step in the Locomotive Basic programming language
You may also check:How to resolve the algorithm Copy a string step by step in the Erlang programming language
You may also check:How to resolve the algorithm Mandelbrot set step by step in the Simula programming language