Ceiun
Ceiun

Reputation: 73

How do I compare whether two numbers have 1 number of difference between them?

Explaining my algorithm:

I'm trying to find out whether My current job for e.g. Write(W) is the same as my previous job, if my current job (W) is the same as my previous job (W) then check whether there's 1 integer of difference between them, for e.g. if the previous job was W9 and my current job is either W8 or W10, then append 0 to my seek array.

I've tried almost every way I could find on the internet to compare integers but none of them work, I continue to receive an invalid arithmetic syntax error when trying to compare current and previous job.

Any ideas?

# Jobs
lastJob=""
currentJob=""
lastNumber=0
currentNumber=0

# Arrays 
seek=()
RW=()
shift 3
# Reads final into array
while IFS= read -r line
do
        Job+=($line)
done < ./sim.job

#-----------------------------------
# Single HDD Algorithm
#-----------------------------------
for (( i=0; i<=${#Job[@]}; i++ ));
do 
        currentString="${Job[$i]}"
        currentJob=${currentString:0:1}
        currentNumber=${currentString:1:3}

        if [[ $currentJob == $lastJob ]]
        then    
                if [[ $currentNumber -eq $lastNumber-1 ]] || [[ $currentNumber -eq $lastNumber+1 ]]
                then
                        seek+=(0)
                        RW+=(60)
                else
                        seek+=(5)
                        RW+=(60)
                fi
        else
                        seek+=(5)
                        RW+=(60)  
        fi

        lastString="${Job[$i]}"
        lastJob=${lastString:0:1}
        lastNumber=${currentString:1:3}
done

This prints output:

#-----------------------------------
# Print Information
#-----------------------------------
for (( i=0; i<${#Job[@]}; i++ ));
do
        echo -e "${Job[$i]}:${seek[$i]}:${RW[$i]}"
done

Expected Output:

R9:5:60
W9:5:60
W10:0:60
R11:0:60
R13:5:60
R18:5:60
R19:0:60
R20:0:60
R21:0:60

Actual Output:

") syntax error: invalid arithmetic operator (error token is "
R9:5:60
W9:5:60
W10::
R11::
R13::
R18::
R19::
R20::
R21::

sim.job file (Input):

R9
W9
W10
R11
R13
R18
R19
R20
R21

Upvotes: 1

Views: 74

Answers (1)

Ceiun
Ceiun

Reputation: 73

rogue \r were found in my input file, to solve this I used the commands:

  1. To check if \r are in the file: od -c <filename> | tr ' ' '\n' | grep '\r'

  2. To remove rogue \r use: tr -d '\r' < filename

Thanks again @mark-fuso

Upvotes: 2

Related Questions