Skip to content

Instantly share code, notes, and snippets.

@martin-denizet
Created June 7, 2018 21:32
Show Gist options
  • Save martin-denizet/dd9bd8b824f62f63d9a841e4b95341c3 to your computer and use it in GitHub Desktop.
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
# 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