f77hack
February 13, 2016, 2:23pm
1
hello,
i need a bit of help on how to do this effectively in bash without a lot of extra looping or massive switch/case
i have a long array of M elements and a short array of N elements, so M > N always. M is not a multiple of N.
for case 1, I want to stretch N to fit M
arrayHuge
H = ( [0].... [M-1] ) has M elements
arraySmall
S= ( [0].... [N-1] ) has N elements
arraySmallRemapped
S_expanded= ( S[0] .... S[N-1]%2 ..... S[N-1]) has M elements
i can do this by checking the remainder with switch/case of if/then but am looking for a better way.
this code works
for (( i=1; i<${LengthM}+1; i++ ));
do
case $(( ($i*$arraySmall/$arrayHuge ) )) in
0) tmp="$arraySmall[0]";;
1) tmp="$arraySmall[1]";;
N-1]) tmp="$arraySmall[N-1]";;
*)tmp="$tmp";;
esac
S_expanded[$i]="$tmp"
done
RudiC
February 13, 2016, 3:47pm
2
Not too clear what you expect. How about
S=(0 1 2 3)
H=(A B C D E F G H I J K)
while [ ${#SX[@]} -lt ${#H[@]} ]; do SX=(${SX[@]} ${S[@]}); done
for ((i=${#H[@]}; i<=${#SX[@]}; i++)); do unset SX[$i]; done
echo ${SX[@]}, ${#SX[@]}, ${!SX[@]}, ${H[@]}
0 1 2 3 0 1 2 3 0 1 2, 11, 0 1 2 3 4 5 6 7 8 9 10, A B C D E F G H I J K
1 Like
f77hack
February 13, 2016, 4:34pm
3
rudic:
Not too clear what you expect. How about
S=(0 1 2 3)
H=(A B C D E F G H I J K)
while [ ${#SX[@]} -lt ${#H[@]} ]; do SX=(${SX[@]} ${S[@]}); done
for ((i=${#H[@]}; i<=${#SX[@]}; i++)); do unset SX[$i]; done
echo ${SX[@]}, ${#SX[@]}, ${!SX[@]}, ${H[@]}
0 1 2 3 0 1 2 3 0 1 2, 11, 0 1 2 3 4 5 6 7 8 9 10, A B C D E F G H I J K
Great. Didn't think of wrapping the small array like that. I knew someone would come up with good compact code. Thanks!
This is what I was looking for
while [ ${#SX[@]} -lt ${#H[@]} ]; do SX=(${SX[@]} ${S[@]}); done