diff options
| -rw-r--r-- | challenge-098/abigail/README.md | 1 | ||||
| -rw-r--r-- | challenge-098/abigail/bash/ch-2.sh | 53 |
2 files changed, 54 insertions, 0 deletions
diff --git a/challenge-098/abigail/README.md b/challenge-098/abigail/README.md index d550cdd363..3b8c4e5800 100644 --- a/challenge-098/abigail/README.md +++ b/challenge-098/abigail/README.md @@ -103,6 +103,7 @@ anyway). ### Solutions +* [Bash](bash/ch-2.sh) * [Perl](perl/ch-2.pl) ### Blog diff --git a/challenge-098/abigail/bash/ch-2.sh b/challenge-098/abigail/bash/ch-2.sh new file mode 100644 index 0000000000..2a6158d1db --- /dev/null +++ b/challenge-098/abigail/bash/ch-2.sh @@ -0,0 +1,53 @@ +#!/bin/sh + +# +# See ../README.md +# + +# +# Run as: perl ch-2.sh < input-file +# +# Each line is a challenge: first number is the target number; +# the rest of the line is the array to search in. +# + +set -f + +while read -a numbers +do target=${numbers[0]} + # + # Try to find the target, counting from 1 + # + found=-1 + for ((i = 1; i < ${#numbers[@]}; i ++)) + do if (($target == ${numbers[$i]})) + then found=$((i - 1)) + break + fi + done + # + # If found, report the position and go to the next line + # + if (($found >= 0)) + then echo $found + continue + fi + + # + # Create a new array, by sorting numbers + # + IFS=$'\n' + numbers=($(sort -n <<< "${numbers[*]}")) + unset IFS + + # + # Search for the target again + # + for ((i = 0; i < ${#numbers[@]}; i ++)) + do if (($target == ${numbers[$i]})) + then found=$i + break + fi + done + echo $found +done |
