Nemo's bash challenge for the day
Michael Still
mikal at stillhq.com
Sat Mar 30 09:02:49 EST 2002
On Fri, 29 Mar 2002, Nemo - earth native wrote:
[cc'ed to CLUG]
> # . weighted randomness. ie, a preference for the first items in the
>
> ...weighted randomness is the one I want - so I can `touch` a file when
> I use it, then the next time I need to choose a file randomly, I can
> sort by reverse date order and thus have the system weighted against the
> more recently used images :)
It is probable that this can be improved, but here we go...
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
#!/bin/bash
# In this case, Nemo wants to be able to specify a list of items, with
# weights associated with them...
# $1 is the list with weights, in the form:
# "1 frog 2 banana 3 hamster"
# Scary assumption number one, people hand me correctly formatted lists
# Incidentally, this will break with numbers exist in the items I am handed
# e.g. Banana42 will break this
NUMBERS=`echo $1 | sed 's/[^0-9 ]//g'`
WORDS=`echo $1 | sed 's/[0-9]//g'`
WEIGHTED=""
# Build the list of options, including the weights
for NUM in $NUMBERS
do
WORD=`echo $WORDS | sed 's/ .*$//'`
WORDS=`echo $WORDS | sed "s/^$WORD *//"`
COUNT=0
while [ $COUNT -lt $NUM ]
do
WEIGHTED=`echo "$WEIGHTED $WORD"`
COUNT=$(( $COUNT + 1 ))
done
done
# Get the random number
LOBOUND=1
HIBOUND=`echo $WEIGHTED | wc -w`
RANDMAX=32767
BINUMBER=$(( $LOBOUND + ($HIBOUND * $RANDOM) / ($RANDMAX + 1) ))
# Get the item -- I can't use shift, because it is not on the command line
COUNT=1
while [ $COUNT -lt $BINUMBER ]
do
WEIGHTED=`echo $WEIGHTED | sed 's/^[^ ]*//'`
COUNT=$(( $COUNT + 1 ))
done
# The first word should be magic selected one
echo $WEIGHTED | sed 's/ .*$//'
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Cheers,
Mikal
--
Michael Still (mikal at stillhq.com) UMT+11hrs
More information about the linux
mailing list