From 9ad3b511c7ff826bfeeb646f356bb17df7e50957 Mon Sep 17 00:00:00 2001 From: Abigail Date: Fri, 5 Feb 2021 02:04:24 +0100 Subject: Bash solution for week 98, part 2 --- challenge-098/abigail/README.md | 1 + challenge-098/abigail/bash/ch-2.sh | 53 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 challenge-098/abigail/bash/ch-2.sh 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 -- cgit