-2

Attempting to solve the "Lonely Integer" problem

HackerRank problem statement: enter image description here

My solution

declare -i n
read n
declare -a numbers
read numbers
n=${#numbers[@]}-1
while [ $n -ge 0 ]; do echo "${numbers[$n]}\n"; ((n--)); done | sort -n | uniq -u

Except the bash on the HackerRank IDE which is 5.2.32 ( tested with bash --version ) throws the following error

enter image description here

P.S. ( When I tested the script on my end I used the shebang #!/bin/bash, the IDE does not require that, please don't say that is the solution )

13
  • 2
    [ doesn't do arithmetic. 1-1 isn't a valid number. Commented Oct 8 at 21:17
  • 2
    read numbers will not read each number into a different element of the array. See stackoverflow.com/questions/9293887/… Commented Oct 8 at 21:23
  • 2
    You can use n=$((${#numbers[@]}-1)) to perform arithmetic in bash. Commented Oct 8 at 21:24
  • 1
    Ah, I guess you're using a newer Bash whose declare -i causes n=1-1 to do arithmetic evaluation, but the target system does not. More minimal example: declare -i n; n=1-1; echo $n. I think you can reduce this question greatly (and get rid of the images). Commented Oct 9 at 9:19
  • 2
    @Barmar, assignment does do arithmetic, when declare -i has been used. Commented Oct 9 at 9:35

1 Answer 1

2

I think the target shell isn't behaving according to Bash documentation, and that can be demonstrated more simply:

#!/usr/bin/bash
declare -i n
n=1-1
echo $n

declare -i is documented as:

The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION above) is performed when the variable is assigned a value.

You can make the code portable/resilient by explicitly asking for arithmetic expansion:

n=$((1-1))

In your program, you don't need n though, since you just want to expand the entire array:

read  # ignore first line
read -a numbers
printf '%d\n' "${numbers[@]}" | sort -n | uniq -u
Sign up to request clarification or add additional context in comments.

1 Comment

Ty -- I tried to get printf to work that way but it was not printing it out in different lines in the target shell i.e. HackerRank IDE -- also some of my solutions were failing but when I tried the exact same solution again by literally running the code saved on the IDE, which was failing earlier somehow, it passed; so I believe the hacker rank IDE is just extremely buggy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.