Created
June 7, 2018 21:32
-
-
Save martin-denizet/dd9bd8b824f62f63d9a841e4b95341c3 to your computer and use it in GitHub Desktop.
Codingame temperatures puzzle in BASH: https://www.codingame.com/ide/puzzle/temperatures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# n: the number of temperatures to analyse | |
read n | |
closest_to_zero=9999 | |
read temperatures | |
for t in $temperatures; do | |
# t: a temperature expressed as an integer ranging from -273 to 5526 | |
echo "New temperature: ${t} closest to 0 so far: ${closest_to_zero}" >&2 | |
# Compare absolute values | |
if [[ "${t#-}" -lt "${closest_to_zero#-}" ]]; then | |
closest_to_zero=$t | |
elif [[ "${t#-}" -eq "${closest_to_zero#-}" ]] && [[ "${t}" -gt "${closest_to_zero}" ]]; then | |
# Absolute values are equal, we keep the new value if it is positive | |
closest_to_zero=$t | |
fi | |
done | |
# No temperatures, we default to 0 | |
if [[ $closest_to_zero -eq 9999 ]]; then | |
closest_to_zero=0 | |
fi; | |
echo "${closest_to_zero}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment