vendredi 30 décembre 2016

Random chose N items from array and update it in BASH SCRIPT

I am trying to random choose a number of items of an array and then update it to do it again till the last set:

#! /bin/bash

A=({1..27})
T=${#A[@]} #number of items in the array
N=3 #number of items to be chosen
V=$(($T/$N)) #number of times to loop
echo ${A[@]} " >> ${#A[@]}"
for ((n=0;n<$V;n++)); do 
    A1=()
    for I in `shuf --input-range=0-$(( ${#A[*]} - 1 )) | head -${N}`; do #random chooses N items random
        S=`echo ${A[$I]}` #the chosen items
        #echo $S
        A1+=("$S|") #creates an array with the chosen items 
        A=("${A[@]/$S}") #deletes the the chosen items from array 
    done
    echo ${A[@]} " >> ${#A[@]}"
    echo ${A1[@]} " >> ${#A1[@]}"
done

The type of output I am getting with this code is:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  >> 27
1 4 5 6 7 8 9 10 11 1 1 14 15 16 17 18 19 1 2 4 5 6 7  >> 27
20| 2| 3|  >> 3
4 6 7 8 9 0 1 4 6 7 8 9 2 4 6 7  >> 27
1| | 5|  >> 3
6 7 8 9 0 1 6 7 8 9 2 6 7  >> 27
| | 4|  >> 3
7 8 9 0 1 7 8 9 2 7  >> 27
6| | |  >> 3
7 8 9 0 1 7 8 9 7  >> 27
| | 2|  >> 3
7 9 0 1 7 9 7  >> 27
8| | |  >> 3
7 9 1 7 9 7  >> 27
| | 0|  >> 3
7 9 1 7 9 7  >> 27
| | |  >> 3
1  >> 27
9| 7| |  >> 3

Any ideas why it works fine in the start and fails in the end??




Aucun commentaire:

Enregistrer un commentaire