And then Nemo wanted weighted random numbers

  • Post author:
  • Post category:Bashrand

Nemo then wanted weighted random numbers, so this item has been added to this page. The following script selects a random element from a weight list of options... #!/bin/bash # Copyright (c) Michael Still 2002 # Released under the terms of the GNU GPL # 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…

Continue ReadingAnd then Nemo wanted weighted random numbers

The challenge and the result

  • Post author:
  • Post category:Bashrand

So, I was at a CLUG meeting last night, and one of the speakers had a whole bunch of bash scripts for XDM theming. Anyway, he was using a perl script to generate the random selection of the theme elements, and me and my big mouth offered that it could be done in bash itself. So here we are... Here's my post to the CLUG mailing list the next day: From mikal@stillhq.com Fri Mar 29 10:26:04 2002 Date: Fri, 29 Mar 2002 10:14:17 +1100 (EST) From: Michael Still To: Linux user group Subject: Nemo's bash challenge for the day Well, I said it could be done... The brief: Generate a random number, and then return that element from a list of elements, in bash The code: (Assuming that the arguements on the command line are the possible return options, and that the random number generator is running as a separate script) LOBOUND=0 HIBOUND=$# shift $(( $LOBOUND + ($HIBOUND * $RANDOM) / (32767 + 1) )) echo $1 See the attachments for some exploratory scripts I wrote while coming up with this truncated sh. There are 54 lines of comments / white spaces, to the 4 or so lines of actual…

Continue ReadingThe challenge and the result

End of content

No more pages to load