- 論壇徽章:
- 0
|
本帖最后由 zhshb8511 于 2011-10-10 15:12 編輯
采用下面兩種方式生成200個(gè)隨機(jī)4位數(shù),并存入文件中,
想知道那種實(shí)現(xiàn)方式比較好? 給出理由。
自己分析:第一種算法從時(shí)間復(fù)雜度上考慮,比較低效;
第二種算法比較耗內(nèi)存,尤其是數(shù)組內(nèi)容過大的時(shí)候
第三種是自己認(rèn)為最好的
請(qǐng)大家?guī)兔Ψ治,或不惜曬出更好的?shí)現(xiàn)方式
第一種實(shí)現(xiàn)方式:- #!/usr/bin/perl
- #use strict;
- use warnings;
- #生成200隨機(jī)數(shù)
- open(FH_200,">IN_all.txt") || die $!;
- for(my $total = 1; $total <= 200; $total++){
- my $single_4_word = 1000 * ((int rand(9)) + 1)
- + 100 * (int rand(10))
- + 10* (int rand(10))
- + (int rand(10));
- print FH_200 $single_4_word."\n";
- }
- close(FH_200);
復(fù)制代碼 第二種實(shí)現(xiàn)方式:- #!/usr/bin/perl
- #use strict;
- use warnings;
- my @all_number = (1000..9999);
- #9000個(gè)數(shù)據(jù),序號(hào)分別為0-8999
- #生成200隨機(jī)數(shù)
- open(FH_200,">IN_all.txt") || die $!;
- for(my $total = 1; $total <= 200; $total++){
- my $hello = int rand(9000);
- print FH_200 $all_number[$hello]."\n";
- }
- close(FH_200);
復(fù)制代碼 第三種實(shí)現(xiàn)方式:- #!/usr/bin/perl
- #use strict;
- use warnings;
- #生成200隨機(jī)數(shù)
- open(FH_200,">IN_all.txt") || die $!;
- for(my $total = 1; $total <= 200; $total++){
- my $hello = (int rand(9)+1).(int rand(10)).(int rand(10)).(int rand(10));
- print FH_200 $hello."\n";
- }
- close(FH_200);
復(fù)制代碼 |
|