randint with range and float to int approximation

This commit is contained in:
Sam Hadow 2025-04-15 17:38:29 +02:00
parent 4debccf0cf
commit 91b79383e8
2 changed files with 8 additions and 11 deletions

View File

@ -3,7 +3,7 @@
My collection of useful shell scripts.
### randint.sh
usage: randint \<positive integer\> \[fast\]
usage: randint \<positive integer\>
print in the terminal a random integer x with $` 0 \leq x \leq \$1`$
### killwine.sh

View File

@ -1,6 +1,6 @@
#!/bin/bash
if ! [[ "$1" =~ ^[0-9]+$ ]]; then
echo "Usage: randint <positive integer> [fast]"
echo "Usage: randint <positive integer>"
exit 1
fi
number=$1
@ -8,13 +8,10 @@ ceiling=$(echo "l($number +1)/l(2)" | bc -l | awk '{
bits = ($1 == int($1)) ? $1 : int($1) + 1;
print int( (bits + 7) / 8 )
}')
if [[ "$2" == "fast" ]]; then
random_num=$(xxd -p -l $ceiling /dev/urandom | tr -d '\n' | awk -v num="$number+1" '{print strtonum("0x" $0) % num}')
else
while :; do
random_num=$(xxd -p -l $ceiling /dev/urandom | tr -d '\n' | awk '{print strtonum("0x" $0)}')
(( random_num < number )) && break
done
fi
random_num=$(xxd -p -l $ceiling /dev/urandom | tr -d '\n' | \
awk -v max="$number" -v scale="$ceiling" '{
val = strtonum("0x" $0);
range = 2**(scale*8);
print int(val * max / range)
}')
echo $random_num