Logic for processing 2 arrays


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Logic for processing 2 arrays
# 1  
Old 10-12-2012
Logic for processing 2 arrays

Hi,

I need a logic for processing 2 arrays at a same time.

x=a,b,c
y=d,e

now the sequence to be followed is (a,d) , (b,e) , (c,d) , (a,e) , (b,d) , (c,e)

and again...(a,d)

The sequence should be maintained.

Thanks
# 2  
Old 10-12-2012
In ksh93/bash:
Code:
x=(a b c)
y=(d e)
times=$((${#x[*]} * ${#y[*]}))
((xi=yi=0))
for((i=1;i<=times;i++,xi++,yi++))
do
 if((xi>${#x[*]}-1));then xi=0;fi
 if((yi>${#y[*]}-1));then yi=0;fi
 print ${x[$xi]},${y[$yi]}
done

producing
Code:
a,d
b,e
c,d
a,e
b,d
c,e

Does that help you?
This User Gave Thanks to elixir_sinari For This Post:
# 3  
Old 10-15-2012
works like a charm...can you please explain the script.
# 4  
Old 10-15-2012
Code:
x=(a b c)
y=(d e)
times=$((${#x[*]} * ${#y[*]}))    ### times = (length of array x)*(length of array y)=3*2=6
((xi=yi=0))                       ### xi - index for accessing elements of array x (in the loop)
                                  ### yi - index for accessing elements of array y (in the loop)
for((i=1;i<=times;i++,xi++,yi++)) ### loop "times" (6) times
do                                ### Remember, for indexed arrays, indexing starts at 0.
 if((xi>${#x[*]}-1));then xi=0;fi ### reset xi if it goes over the value of (length of array x - 1)
 if((yi>${#y[*]}-1));then yi=0;fi ### reset yi if it goes over the value of (length of array y - 1)
 print ${x[$xi]},${y[$yi]}        ### print elements from x and y indexed by xi and yi, respectively
done

Login or Register to Ask a Question

Previous Thread | Next Thread

1 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Processing with AWK and Arrays

Done, thanks for the help - worked. (1 Reply)
Discussion started by: fusionX
1 Replies
Login or Register to Ask a Question