irwan
irwan

Reputation: 51

generate random binary number in perl

I want to generate 64 iteration of non-repetitive 6 digits that only consist of 0 and 1 (eg. 111111, 101111, 000000) by using perl. I found code that can generate random hex and try to modify it but I think my code is all wrong. This is my code:

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}++;
}

Upvotes: 1

Views: 1596

Answers (3)

200_success
200_success

Reputation: 7582

Do you mean that you want 64 six-bit numbers, all distinct from each other? If so, then you should just shuffle the list (0, 1, 2, 3, …, 63), because there are exactly 64 six-bit numbers — you just want them in a random order.

And if you want to print them as base-two string, use the %06b format.

use List::Util;

my @list = List::Util::shuffle 0..63;
printf "%06b\n", $_ for @list;

Upvotes: 4

Sobrique
Sobrique

Reputation: 53478

From the comments:

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.

This is a horribly inefficent approach to take, thanks to random number collisons.

You get the same result with:

printf ( "%06b\n", $_ ) for 1..63;

If you're after a random order (although, you don't seem to suggest that you do):

use List::Util qw ( shuffle ); 
printf ( "%06b\n", $_ ) for shuffle (0..63);

Upvotes: 3

samgak
samgak

Reputation: 24417

If you want 64 x 6-bit integers you can call int(rand(64)); 64 times, there's no need to generate each bit separately.

Your code can be modified to work like this:

#!/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}++;
}

The results are stored in a array of integers. The %06b format specifier string prints out a 6 bit binary number.

Upvotes: 1

Related Questions