在perl中生成随机二进制数
generate random binary number in perl
我想使用 perl 生成仅由 0 和 1 组成的不重复的 6 位数字(例如 111111、101111、000000)的 64 次迭代。
我找到了可以生成随机十六进制的代码并尝试修改它,但我认为我的代码全错了。这是我的代码:
use strict;
use warnings;
my %a;
foreach (1 .. 64) {
my $r;
do {
$r = int(rand(2));
}
until (!exists($a{$r}));
printf "%06d\n", $r;
$a{$r}++;
}
如果您想要 64 x 6 位整数,您可以调用 int(rand(64));
64 次,无需单独生成每一位。
您的代码可以修改为这样工作:
#!/usr/bin/perl
# your code goes here
use strict;
use warnings;
my %a;
foreach (1 .. 64) {
my $r;
do
{
$r = int(rand(64));
} until (!exists($a{$r}));
printf "%06b\n", $r;
$a{$r}++;
}
结果存储在整数数组中。 %06b
格式说明符字符串打印出一个 6 位二进制数。
你的意思是你想要 64 个六位数字,每个数字都互不相同?如果是这样,那么您应该只打乱列表 (0, 1, 2, 3, …, 63)
,因为正好有 64 个六位数字 — 您只需要它们随机排列即可。
如果您想将它们打印为以二为基数的字符串,请使用 %06b
格式。
use List::Util;
my @list = List::Util::shuffle 0..63;
printf "%06b\n", $_ for @list;
来自评论:
I am actually want to generate all possible 6-bit binary number. Since writing all the possible combination by hand is cumbersome and prone to human error, I think it will be good idea to just generate it by using rand() with no repetition and store it into array.
由于随机数冲突,这是一种非常低效的方法。
你得到相同的结果:
printf ( "%06b\n", $_ ) for 1..63;
如果您想要随机订购(尽管您似乎没有建议您这样做):
use List::Util qw ( shuffle );
printf ( "%06b\n", $_ ) for shuffle (0..63);
我想使用 perl 生成仅由 0 和 1 组成的不重复的 6 位数字(例如 111111、101111、000000)的 64 次迭代。 我找到了可以生成随机十六进制的代码并尝试修改它,但我认为我的代码全错了。这是我的代码:
use strict;
use warnings;
my %a;
foreach (1 .. 64) {
my $r;
do {
$r = int(rand(2));
}
until (!exists($a{$r}));
printf "%06d\n", $r;
$a{$r}++;
}
如果您想要 64 x 6 位整数,您可以调用 int(rand(64));
64 次,无需单独生成每一位。
您的代码可以修改为这样工作:
#!/usr/bin/perl
# your code goes here
use strict;
use warnings;
my %a;
foreach (1 .. 64) {
my $r;
do
{
$r = int(rand(64));
} until (!exists($a{$r}));
printf "%06b\n", $r;
$a{$r}++;
}
结果存储在整数数组中。 %06b
格式说明符字符串打印出一个 6 位二进制数。
你的意思是你想要 64 个六位数字,每个数字都互不相同?如果是这样,那么您应该只打乱列表 (0, 1, 2, 3, …, 63)
,因为正好有 64 个六位数字 — 您只需要它们随机排列即可。
如果您想将它们打印为以二为基数的字符串,请使用 %06b
格式。
use List::Util;
my @list = List::Util::shuffle 0..63;
printf "%06b\n", $_ for @list;
来自评论:
I am actually want to generate all possible 6-bit binary number. Since writing all the possible combination by hand is cumbersome and prone to human error, I think it will be good idea to just generate it by using rand() with no repetition and store it into array.
由于随机数冲突,这是一种非常低效的方法。
你得到相同的结果:
printf ( "%06b\n", $_ ) for 1..63;
如果您想要随机订购(尽管您似乎没有建议您这样做):
use List::Util qw ( shuffle );
printf ( "%06b\n", $_ ) for shuffle (0..63);