1

What's a good, concise way to avoid sequential random value which are close? e.g., using rand in perl, but assuring a minimum 0.2x difference/distribution between any sequential values? I've tried a few ideas like re-sampling rand if the values are close, but then I need a script, and I don't know how to do this cleanly in a one-liner.

The context is that I'm doing a search-replace using the commandline with perl. The idea is that in each line, a string is replaced with a random value from an array.

echo ":z:z:z:" | tr ':' '\n' | perl -pe '@numbers=(1.2, 3.4, 5.6, 7.8); $number = $numbers[rand @numbers];  s/z/" : ".( $number )/ge'

The output is something like this:

: 3.4
: 5.6
: 5.6
: 1.2

See how the 5.6 repeats? I want to avoid that. In my use-case, the @numbers array contains ~100 elements. I want to adjust rand @numbers so that the selected array values are further apart.

1 Answers1

1

If you're sure there will always be fewer lines of input than array elements, you can shuffle the array once at the beginning and then remove a single element for every line:

$ echo -e 'foo\nbar\nbaz' | \
    perl -MList::Util=shuffle -lpe'
        BEGIN { @numbers = shuffle map { 1.2 * $_ } 1..4 }
        $_ = pop @numbers
    '
2.4
4.8
3.6
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110