Created
January 16, 2020 01:04
-
-
Save mathew-fleisch/75ed333c34d92bec67d4cfdb7ddd3dee to your computer and use it in GitHub Desktop.
Get Sum Target Index Thing
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
# Given an array of integers, return indices of the two numbers | |
# such that they add up to a specific target. | |
# You may assume that each input would have exactly one solution, | |
# and you may not use the same element twice. | |
# Example: [1,2,3,4], 7 -> 2,3 | |
# chmod +x get-sum-target-index-thing.sh && ./get-sum-target-index-thing.sh 7 1 2 3 4 | |
if [ -z "$1" ]; then | |
echo "Must provide a target" | |
exit 1 | |
fi | |
TARGET="$1" | |
echo "Target: $TARGET" | |
STACK_FILENAME="stack.txt" | |
rm -rf "$STACK_FILENAME" | |
touch "$STACK_FILENAME" | |
for value in "$@"; do | |
if [ "$value" != "$TARGET" ]; then | |
echo "$value" >> "$STACK_FILENAME" | |
fi | |
done | |
SUM_CHECK=0 | |
TOTAL=$(cat $STACK_FILENAME | wc -l) | |
for x in $(cat $STACK_FILENAME); do | |
INDEX=$(cat $STACK_FILENAME | grep -n ${x} - | awk -F: '{print $1}') | |
NEXT=$(expr $TOTAL - $INDEX) | |
for y in $(cat $STACK_FILENAME | tail -${NEXT}); do | |
YINDEX=$(cat $STACK_FILENAME | grep -n ${y} - | awk -F: '{print $1}') | |
SUM_CHECK=$((x + y)) | |
if [ "$SUM_CHECK" -eq "$TARGET" ]; then | |
echo "This is the way: ($INDEX,$YINDEX)" | |
exit 0 | |
fi | |
done | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment