开发者

Equilibrium index in bash

开发者 https://www.devze.com 2023-02-04 16:00 出处:网络
I need to calculate an equilib开发者_运维问答rium index in bash. An equilibrium index of a sequence is

I need to calculate an equilib开发者_运维问答rium index in bash.

An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.

Consider the following input data:

-7#1#5#
2#-4#3#0

I first use the following sed command to change # into newlines and to calculate the number of elements:

`sed 's/#/\n/g' input.txt | wc -l`

This gives me the following output:

-7
1
5
2
-4
3

How can I display the value of array element after the index number, e.g.:

table[0] => -7
table[1] => 1
.
.
.
table[5] => 3


Use

IFS='#'
table=( $(< input.txt) )

then each element can be accessed by

${table[0]}
${table[1]}
...


From what you currently have, you could use tail +n to drop n first lines from a stream. Then you can read the next via head -n1.


Problem solved. Thank You guys for help.

#!/bin/bash

cat input.txt | awk '{if($0~/^>/){print"\n"$0;next}else{printf("%s",$0)}}' > output.txt

IFS='#';table=( $( < output.txt ) );count=${#table[@]}

idx=$(( $count-1 ))

right=0

for (( i=0;i<=$idx;i++ ))
do  
    (( left+=${table[i]} ))
    if [ $left == $right ] 
      then
      echo "( EQ INDEX: $i, EQ VALUE: ${table[i]} )"
    fi
    (( right-=${table[i]} ))
done
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号