I have an array
X = ( -100 -90 -80 -70 -60 -50 -40 30 40 50 60 70 80 90 100 )
I want to find the place where values change from negative to positive.
I have an array
X = ( -100 -90 -80 -70 -60 -50 -40 30 40 50 60 70 80 90 100 )
I want to find the place where values change from negative to positive.
Which programming language are you using?
awk should be ok
echo '-100 -90 -80 -70 -60 -50 -40 30 40 50 60 70 80 90 100' | nawk '{for(i=1;i++<NF;) if($i*$(i+1)<0) {print i+1;next}}'
In case multiple changes should be handled:
awk 'BEGIN {
n = split("-100 -90 -80 -70 -60 -50 -40 30 40 50 60 70 80 90 100", x)
for (i = 0; ++i <= n;) {
if (i > 1)
(x > 0) == l || r = r ? r FS i : i
l = x > 0
}
print "+/- changes in position(s):", r
}'
For example:
% awk 'BEGIN {
n = split("100 -90 -80 -70 -60 -50 -40 30 40 -50 60 70 80 90 100", x)
for (i = 0; ++i <= n;) {
if (i > 1)
(x > 0) == l || r = r ? r FS i : i
l = x > 0
}
print "+/- changes in position(s):", r
}'
+/- changes in position(s): 2 8 10 11
yep, good idea:
echo '-100 -90 -80 4 5 6 -70 -60 -50 -40 30 40 50 60 70 80 90 100' | nawk '{l="";for(i=1;i++<NF;) if($i*$(i+1)<0) {l=l FS i+1} print "+/- changes in position(s):" l}'
Does this code work if the first element is 100 and not -100?
good catch - thanks!
echo '100 -90 -80 4 5 6 -70 -60 -50 -40 30 40 50 60 70 80 90 100' | nawk '{l="";for(i=1;i<=NF;i++) if($i*$(i+1)<0) {l=l FS i+1} print "+/- changes in position(s):" l}'
Forgot to mention that values are always ascending. So don't need it so great.