100과 200 사이의 10 개의 난수를 생성하고 싶습니다 (둘 다 포함). 랜드로 어떻게 만드나요?
아니요, bash에서 실행하는 rand 명령을 의미합니다.
—
ignacio caviedes
100과 200 사이의 10 개의 난수를 생성하고 싶습니다 (둘 다 포함). 랜드로 어떻게 만드나요?
답변:
당신이 의미하는 경우 rand에서 패키지 (OpenSSL을에서 일 반대), 그것은 단지 상한, 하한 지원하지 않습니다. 당신이 할 수있는 일은 더 낮은 바운드-제로-다음 더 낮은 바운드 트릭입니다.rand
$ 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출력 의 상한이 되므로 ( 최대 - 최소 = 100)-e -d '\n'구분자를 줄 바꿈으로 설정합니다. 의 처리 편의성을위한 것 awk입니다.awk코드는 각 줄을 소요하고 여기에 100을 추가합니다.
펄 방식은 다음과 같습니다.
$ 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
와 shufGNU의로 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;
}
random라이브러리 : stackoverflow.com/a/19728404/2072269 , stackoverflow.com/a/19666713/2072269
rand?RANDOM변수?/dev/random?/dev/urandom?