我想生成10个介于100和200之间的随机数(均包含在内)。我要如何用rand做呢?
不,我只是指您从bash执行的rand命令。
—
伊格纳西奥·卡维德斯(Ignacio Caviedes)
我想生成10个介于100和200之间的随机数(均包含在内)。我要如何用rand做呢?
Answers:
如果你指的是rand从该rand包(而不是从OpenSSL的一个),它不支持的下界,只是一个上限。您可以做的是将下限绑定到零,然后添加下限技巧:
$ rand -N 10 -M 100 -e -d '\n' | awk '{$0 += 100}1'
170
180
192
168
169
170
117
180
167
142
-N 是您需要的随机数-M将是数字rand输出的上限,因此(max - min = 100)-e -d '\n'将定界符设置为换行符。这是为了方便处理awk。然后,awk代码将每一行加到100。
这是一种Perl方式:
$ perl -le 'print 100+int(rand(101)) for(1..10)'
129
197
127
167
116
134
143
134
122
117
Or, on the same line:
$ perl -e 'print 100+int(rand(101))." " for(1..10); print "\n"'
147 181 146 115 126 116 154 112 100 116
您还可以使用/dev/urandom(从此处改编):
$ for((i=0;i<=10;i++)); do
echo $(( 100+(`od -An -N2 -i /dev/urandom` )%(101)));
done
101
156
102
190
152
130
178
165
186
173
143
随着shuf从GNU的coreutils:
$ shuf -i 100-200 -n 10
159
112
192
140
166
121
135
120
198
139
您可以使用$RANDOM。
number=0 #initialize the number
FLOOR=100
RANGE=200
while [ "$number" -le $FLOOR ]
do
number=$RANDOM
let "number %= $RANGE" # Scales $number down within $RANGE.
done
echo "Random number between $FLOOR and $RANGE $number"
echo
没什么了不起的-用i计数器和计数器进行for循环的简单仿真while。范围是使用if . . . else . . .fi结构设置的。旁注:我的提示首先是工作目录,然后是输入区域,因此请不要对您看到的内容感到困惑
$ ./bashRadom.sh 100 200
190
111
101
158
171
197
199
147
142
125
bashRadom.sh:
#! /bin/bash
i=0;
while [ $i -lt 10 ]; do
NUM=$RANDOM;
if [ $NUM -gt $1 ] && [ $NUM -lt $2 ]; then
echo $NUM;
else continue;
fi;
i=$((i+1));
done
这是我在大学上C课时一直在使用的代码。我为满足此问题而添加的小修改是使用命令行参数(而不是将值硬编码到源代码中)
$ gcc randfunc.c
$ ./a.out 100 200
100
106
155
132
161
130
110
195
105
162
187
randfunc.c:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt (int, int);
void
main (int argc, char *argv[])
{
int min = atoi (argv[1]), max = atoi (argv[2]), i = 0;
srand (time (NULL));
for (i; i < 11; i++)
{
printf ("%d \n", randInt (min, max));
}
}
int
randInt (int a, int b)
{
int randValue;
randValue = a + (int) rand () % (b - a + 1);
return randValue;
}
rand?该RANDOM变量?/dev/random?/dev/urandom?