Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I do have a interesting problem that I am trying to tackle but I am yet unable to do so.

Let suppose that I have 2 arrays.

Array One:

1 -2 3 -2 2 -4

Array Two:

-2 -3 4 5 2 -5

I want to be able to actually compare the i-th value of both Array one and Array two:

  • If both are negative then I would input in Array Three 0
  • If they are both positive I will add a 1
  • If they are opposites I need to insert a 2

Output:

2 0 1 2 1 0 

How can I do that ?

share|improve this question
    
What have you tried so far? – Kusalananda 2 days ago
    
What if an element is zero? – Kusalananda 2 days ago
    
Hello, a element can never be 0 since the two arrays are actually stock values so if both are up together then there is a relation down as well so the value can never be 0 am very new to bash – JavaFreak 2 days ago
    
Really, don't use bash for this. Use Python or Perl, not bash. – cat 2 days ago
up vote 6 down vote accepted

If you're familiar with C, C++ or Java, then you'll find this variant of bash's for-loop quite familiar too. bash does arithmetic evaluation with (( ... )) so we'll use that when comparing values:

array1=(  1 -2  3 -2  2 -4 )
array2=( -2 -3  4  5  2 -5 )

array3=( )

for (( i=0; i < ${#array1[@]}; ++i )); do
    if (( array1[i] < 0 && array2[i] < 0 )); then
        array3[$i]=0
    elif (( array1[i] > 0 && array2[i] > 0 )); then
        array3[$i]=1
    else
        array3[$i]=2
    fi
done

echo "${array3[@]}"

This also works well with the ksh93 shell, from which bash got many of its features.

share|improve this answer

A straight way:

arr1=(1 -2 3 -2 2 -4)
arr2=(-2 -3 4 5 2 -5)

i=0

while [[ "$i" -lt "${#arr1[@]}" ]]; do
  a=$(( ${arr1[$i]} * ${arr2[$i]} ))
  if [[ "$a" -lt 0 ]]; then
    echo 2
  else
    if [[ "${arr1[$i]}" -gt 0 ]]; then
      echo 1
    else
      echo 0
    fi
  fi
  : "$((i = i + 1))"
done | paste -sd ' ' -
share|improve this answer
1  
Slightly obfuscated in a backhand trick shot kind of way, but +1 for creative use of paste and :. – Kusalananda 2 days ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.