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:
- Array and Target Initialization:
NUMS=(1 3 7 9 2)
: This line initializes an array namedNUMS
with the numbers 1, 3, 7, 9, and 2.NUMS_LEN=${#NUMS[@]}
: This calculates the length of theNUMS
array and stores it inNUMS_LEN
.TARGET_NUMS=11
: Sets the target sum to 11.
- Function Declaration –
func_find_pair
:- The function
func_find_pair
is declared to find the pair. - A variable
found
is initialized tofalse
. This is used to track whether a pair that sums up to the target number has been found.
- The function
- 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.
- The script uses a nested loop to iterate over pairs of numbers in the
- 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]
andNUMS[j]
) equals the target number (TARGET_NUMS
). - If a pair is found, it prints the pair and sets
found
totrue
.
- Inside the inner loop, there’s an
- 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”.
- After both loops complete, the script checks if a pair was found with
- Function Call:
- Finally,
func_find_pair
is called withfunc_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 variablesNUMS
andTARGET_NUMS
. This should be simplyfunc_find_pair
.
- Finally,
For those who are curious about the original post, here’s the link to it.