Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

Random flling the array - perl

I need to know how can I fill the array in perl randomly. For example: I want declare an array containing 10 elements smaller than 60. Can someone explain me how can I do it or send me any guide? I would be so grateful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm assuming you meant "ten non-negative integers less than 60".

With possibility of repeats:

my @rands = map { int(rand(60)) } 1..10;

For example,

$ perl -E'say join ",", map { int(rand(60)) } 1..10;'
0,28,6,49,26,19,56,32,56,16       <-- 56 is repeated

$ perl -E'say join ",", map { int(rand(60)) } 1..10;'
15,57,50,16,51,58,46,7,17,53

$ perl -E'say join ",", map { int(rand(60)) } 1..10;'
13,57,26,47,30,14,47,55,39,39     <-- 47 and 39 are repeated

Without possibility of repeats:

use List::Util qw( shuffle );

my @rands = (shuffle 0..59)[0..9];

For example,

$ perl -MList::Util=shuffle -E'say join ",", (shuffle 0..59)[0..9];'
13,50,8,21,11,24,28,51,55,38

$ perl -MList::Util=shuffle -E'say join ",", (shuffle 0..59)[0..9];'
1,0,58,46,47,49,52,33,5,13

$ perl -MList::Util=shuffle -E'say join ",", (shuffle 0..59)[0..9];'
19,43,45,49,23,53,2,38,59,35

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...