I'm working on a Bash script and I have an integer input that I want to compare to values in a specific array: `array=(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100)`. For example, if my input is 5, I want to identify it as closer to 4, while if my input is 87, it should be perceived as 88. I've tried using awk and it worked, but I'm looking for a pure Bash solution. Any help or suggestions would be appreciated!
4 Answers
You can achieve this with a straightforward loop. Here's a basic example of how to do it:
```
input="$1"
array=(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100)
closest_match=-1
min_diff=99999
for value in "${array[@]}"; do
diff=$(( input - value ))
diff=${diff#-}
if (( diff < min_diff )); then
min_diff=$diff
closest_match=$value
fi
done
echo "The closest value is: $closest_match"
```
This will loop through each value in your array, calculate the difference, and keep track of the closest match!
Consider tweaking the initial value for `min_diff` to suit your expected inputs better. It's true that if your input is far from the range, this could miss efficient checks.
When deciding on ties, you can customize your function to return either the lower or higher value based on your preference. Just add a simple condition when you find equal distances!
I've been thinking about how to handle potential tie situations. For example, if my number is exactly in the middle, should I choose the lower or upper value in the array? It would be great to clarify that!
Here's another approach you might like. It directly checks conditions to find the nearest value:
```
num="$1"
array=(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100)
if (( num = array[-1] )); then
nearest=${array[-1]}
else
for (( i=0; num >= array[i]; i++ )); do :; done
nearest=$(( num - array[i-1] < array[i] - num ? array[i-1] : array[i] ))
fi
echo "$nearest"
```
This checks boundaries first, then efficiently finds the nearest value!
This is a neat way to approach it! I like how you handle the absolute difference to determine the closest value.