3

Hello I have the following array:

array=(1 2 3 4 5 7 8 9 12 13)

I execute this for loop:

    for w in ${!array[@]}
    do
        comp=$(echo "${array[w+1]} - ${array[w]} " | bc)
        if [ $comp = 1 ]; then
            /*???*/
        else
            /*???*/
        fi
    done

What I would like to do is to insert a value when the difference between two consecutive elements is not = 1

How can I do it?

Many thanks.

Mad Physicist
  • 76,709
  • 19
  • 122
  • 186
Andrea
  • 193
  • 3
  • 12

3 Answers3

3

Just create a loop from the minimum to the maximum values and fill the gaps:

array=(1 2 3 4 5 7 8 9 12 13)
min=${array[0]}
max=${array[-1]}

new_array=()
for ((i=min; i<=max; i++)); do
    if [[ " ${array[@]} " =~ " $i " ]]; then
        new_array+=($i)
    else
        new_array+=(0)
    fi
done

echo "${new_array[@]}"

This creates a new array $new_array with the values:

1 2 3 4 5 0 7 8 9 0 0 12 13

This uses the trick in Check if an array contains a value.

Community
  • 1
  • 1
fedorqui 'SO stop harming'
  • 228,878
  • 81
  • 465
  • 523
1

You can select parts of the original array with ${arr[@]:index:count}.
Select the start, insert a new element, add the end.

To insert an element after index i=5 (the fifth element)

 $ array=(1 2 3 4 5 7 8 9 12 13)
 $ i=5
 $ arr=("${array[@]:0:i}")         ### take the start of the array.
 $ arr+=( 0 )                      ### add a new value ( may use $((i+1)) )
 $ arr+=("${array[@]:i}")          ### copy the tail of the array.
 $ array=("${arr[@]}")             ### transfer the corrected array.
 $ printf '<%s>' "${array[@]}"; echo
 <1><2><3><4><5><6><7><8><9><12><13>

To process all the elements, just do a loop:

 #!/bin/bash

array=(1 2 3 4 5 7 8 9 12 13)

for (( i=1;i<${#array[@]};i++)); do

    if    (( array[i] != i+1 ));
    then  arr=("${array[@]:0:i}")           ### take the start of the array.
          arr+=( "0" )                      ### add a new value
          arr+=("${array[@]:i}")            ### copy the tail of the array.
          # echo "head $i ${array[@]:0:i}"  ### see the array.
          # echo "tail $i ${array[@]:i}"
          array=("${arr[@]}")               ### transfer the corrected array.
    fi
done
printf '<%s>' "${array[@]}"; echo

$ chmod u+x ./script.sh
$ ./script.sh
<1><2><3><4><5><0><7><8><9><10><0><0><13>
0

There does not seem to be a way to insert directly into an array. You can append elements to another array instead though:

result=()
for w in ${!array[@]}; do
    result+=("${array[w]}")
    comp=$(echo "${array[w+1]} - ${array[w]} " | bc)
    if [ $comp = 1 ]; then
        /* probably leave empty */
    else
        /* handle missing digits */
    fi
done

As a final step, you can assign result back to the original array.

Mad Physicist
  • 76,709
  • 19
  • 122
  • 186