Monday, 11 June 2012

Portable random number generator

A couple of days ago, I was asked for a way to generate random numbers within a certain range (e.g. the interval [1,10]). But there was a catch: we had an Android system with ash only and no bc.

If we had bash, we could do:
echo $[ ( $RANDOM % 10 ) + 1 ]

With ash but with bc, we could go:
echo "$RANDOM % 10 + 1" | bc

Fortunately we had awk:
echo|awk "{ print $RANDOM % 10 + 1 }"

No comments:

Post a Comment