Shell Algorithm – Array and Brute Force

Last year, when I initially wrote it, I shared a mechanism written in Java that involved an array and brute-force techniques. This time, I redeveloped the brute-force process in a shell script. What surprised me most was its syntactical similarity to Java, particularly in the sections with nested for-loops.

#!/bin/bash

NUMS=(1 3 7 9 2)
NUMS_LEN=${#NUMS[@]}
TARGET_NUMS=11

function func_find_pair() {
   found=false
   for (( i=0; i<$NUMS_LEN-1; i++)); do
        for (( j=i+1; j<$NUMS_LEN; j++ )); do
            if (( NUMS[i] + NUMS[j] == TARGET_NUMS )); then
                printf "Pair found (%d, %d)\n" "${NUMS[i]}" "${NUMS[j]}"
                found=true
            fi
        done
    done

    if [ "$found" == false ]; then
         printf "Pair not found"
    fi
}

func_find_pair $NUMS $TARGET_NUMS

Step-by-step explanation:

  1. Array and Target Initialization:
    • NUMS=(1 3 7 9 2): This line initializes an array named NUMS with the numbers 1, 3, 7, 9, and 2.
    • NUMS_LEN=${#NUMS[@]}: This calculates the length of the NUMS array and stores it in NUMS_LEN.
    • TARGET_NUMS=11: Sets the target sum to 11.
  2. Function Declaration – func_find_pair:
    • The function func_find_pair is declared to find the pair.
    • A variable found is initialized to false. This is used to track whether a pair that sums up to the target number has been found.
  3. Nested Loop for Finding Pairs:
    • The script uses a nested loop to iterate over pairs of numbers in the NUMS array.
    • for (( i=0; i<$NUMS_LEN-1; i++)): The outer loop goes from the first element to the second-to-last element.
    • for (( j=i+1; j<$NUMS_LEN; j++ )): The inner loop starts from the element right after the current element of the outer loop and goes to the last element. This ensures that every unique pair is checked without repetitions.
  4. Checking Pair Sum:
    • Inside the inner loop, there’s an if statement: if (( NUMS[i] + NUMS[j] == TARGET_NUMS )). This checks if the sum of the pair (NUMS[i] and NUMS[j]) equals the target number (TARGET_NUMS).
    • If a pair is found, it prints the pair and sets found to true.
  5. Final Check:
    • After both loops complete, the script checks if a pair was found with if [ "$found" == false ].
    • If no pair was found, it prints “Pair not found”.
  6. Function Call:
    • Finally, func_find_pair is called with func_find_pair $NUMS $TARGET_NUMS. However, this is a mistake in your script. The function doesn’t need $NUMS $TARGET_NUMS as arguments because it uses the global variables NUMS and TARGET_NUMS. This should be simply func_find_pair.

For those who are curious about the original post, here’s the link to it.

Road to Google

Leave a Reply