How can I find the closest value in an array to a given integer in Bash?

0
0
Asked By TechyTurtle99 On

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

Answered By SandySands123 On

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!

BashBunny88 -

This is a neat way to approach it! I like how you handle the absolute difference to determine the closest value.

CodeWizard42 -

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.

Answered By DetailOrientedDolphin On

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!

Answered By AnalyticalAnt29 On

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!

Answered By CleverCactus77 On

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!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.