'Bash/shell script: create four random-length strings with fixed total length

I would like to create four strings, each with a random length, but their total length should be 10. So possible length combinations could be:

3    3    3    1

or

4    0    2    2

Which would then (respectively) result in strings like this:

111    222    333    4

or

1111    33    44

How could I do this?



Solution 1:[1]

Here is an algorithm:

Make first 3 strings with random length, which is not greater than sum of lenght (each time substract it). And rest of length - it's your last string.

Consider this:

sumlen=10
for i in {1..3}
do
   strlen=$(($RANDOM % $sumlen)); sumlen=$(($sumlen-$strlen)); echo $strlen
done
echo $sumlen

This will output your lengths, now you can create strings, suppose you know how

Solution 2:[2]

alternative awk solution

 awk 'function r(n) {return int(n*rand())} 
      BEGIN{srand(); s=10; 
            for(i=1;i<=3;i++) {a=r(s); s-=a; print a} 
            print s}'

3
5
1
1

srand() to set a randomized seed, otherwise will generate the same random numbers each time.

Here you can combine the next task of generating the strings into the same awk script

$ awk 'function r(n) {return int(n*rand())}; 
       function rep(n,t) {c="";for(i=1;i<=n;i++) c=c t; return c}
       BEGIN{srand(); s=10; 
             for(j=1;j<=3;j++) {a=r(s); s-=a; printf("%s ", rep(a,j))}
             printf("%s\n", rep(s,j))}'

generated

1111 2 3 4444

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergius
Solution 2