Last active
June 7, 2018 15:11
-
-
Save martin-denizet/a85ab33bb746293cf7d507cc2c23d350 to your computer and use it in GitHub Desktop.
Identifies the closest strength between 2 horses. Codingame puzzle at https://www.codingame.com/ide/puzzle/horse-racing-duals
This file contains hidden or 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
read N | |
# An array of horses | |
declare -a horses | |
closest_strength=10000000 | |
# Initialize last to -1 because it's an invalid value | |
last=-1 | |
for (( i=0; i<N; i++ )); do | |
read horse | |
# We set the value as the key because it will be sorted automatically | |
horses[$horse]=1 | |
#echo "Added horse ${horse}" >&2 | |
done | |
# Show all keys of of the array (horses' strength) for debug | |
#echo "${!horses[@]}" >&2 | |
# If the array length is < N then at least 2 horses have the same strength | |
if [[ "${#horses[@]}" -ne N ]] || [[ "${#horses[@]}" -eq 0 ]]; then | |
closest_strength=0 | |
else | |
# For each key in array | |
for i in ${!horses[@]}; do | |
# If this is not the first loop (last not initialized with last value) | |
if [ "$last" -ne -1 ]; then | |
# Because the array is sorted, we know i>=last | |
diff=$((i - last)) | |
#echo "diff:${diff}, last:${last}, i:${i} closest:$closest_strength" >&2 | |
if [ "$diff" -lt "$closest_strength" ]; then | |
closest_strength=$diff | |
fi; | |
fi; | |
last=$i | |
done | |
fi; | |
echo "$closest_strength" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment