Another “classic” programming interview question.
The Question
Given user input of a series of numbers, find the minimum value of said input.
The Answer
This question is simple if you understand the concept behind arrays (which you can see the basics of in the “Reverse a Sentence” post).
The basic idea is to read the user input into an array with each number in the input separated into its own element in the array (the read -a numbers_array line).
Once the numbers are in the array, we want to iterate through each of the elements and check if the current element is smaller than the current minimum element. If it is, then we want to override the previous minimum with the new minimum. Note that it is important that the initial minimum value is either not specified or set as one of the elements in the array at the start. This prevents errors if the user number list range does not encompass the initial minimum value.
If you comment out the lines (#echo “Current number/min) near the bottom, you can watch as the script compared the numbers and sets the minimum value.
#!/bin/bash
#set -xv
read -a numbers_array <<< "$1"
min_value="${numbers_array[1]}"
for (( i=0; i<"${#numbers_array[@]}"; i++ ))
do
if (( "${numbers_array[i]}" < "$min_value" ))
then
min_value="${numbers_array[i]}"
fi
#echo "Current number: ${numbers_array[i]}"
#echo "Current min: $min_value"
done
echo "Min value is: $min_value"
The output of the script will be as follows.
$ ./minimum_value "1 3 543 439293 11 12303403 3 3 2 8 4 2 2 6 7 7 043032 23 3 3 23 6 2 1 -543 1 -2 2 3 4 -2 3 321 756" Min value is: -543