LoginSignup
0
0

More than 3 years have passed since last update.

Bashで指定した範囲での乱数を出力する

Posted at

やりたいこと

35.5 ~ 36.9のあいだで乱数を出したい
0からxまでの乱数はかんたんだが、0以外からの乱数は難しかった。

コード

#!/usr/bin/env bash
list=($(seq 355 369))
declare -i out=0
while (( out == 0)); do
    out=$(printf "%s\n" "${list[@]}" | head -n $(( RANDOM % ${#list[@]})) | tail -n 1)
done
echo "scale=1; ${out} / 10" | bc

少数の扱いは面倒なので整数を最後に10で割った。
seqで出力してから、0から行数分までの乱数でランダムに1行取り出す
ただし乱数が0になると何も出力されないのでwhileで0以外になるようにループさせた。

最後に

絶対もっとかんたんで賢い方法がある。配列とか変数とか使っててめちゃくちゃ面倒。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0