Peter’s blog ✴ Week 193 ✴ 28 November 2022

THE WEEKLY CHALLENGE
All the binaries and find the odd man out

The Perl Camel

Task 1

Binary string

You are given an integer, $n > 0. Write a script to find all possible binary numbers of size $n.

Examples


Example 1
Input: $n = 2
Output: 00, 11, 01, 10

Example 2
Input: $n = 3
Output: 000, 001, 010, 100, 111, 110, 101, 011

Analysis

We are asked to find all the binary numbers 'of length $n'. The examples show that means 'containing n digits' and that the desired solution includes those with leading zeroes.

The numbers are simply all the integers from 0 .. 2 ^ ($n - 1), and we can loop over that range, outputting the numbers in binary format using the binary option of sprintf. It looks a little odd:

sprintf("%0${n}b", $_)

but if, say $n == 4, that amounts to

sprintf("%04b", $_)

which means 4 binary digits with leading zeroes.

Perl Weekly’s review

from Perl Weekly issue 593

Interesting narration of task analysis. You should definitely check it out.

Try it 

Try running the script with any input:



example: 5 - No more than 10, please

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-11-28
# PWC 193 task 1

use v5.28;
use utf8;
use warnings;

my (@tests, $n, $j, $string);

@tests = (2, 3, 4, 6);

# loop over tests
for $n (@tests) {
    
    # format as binary
    $string = '';
    $string .= sprintf("%0${n}b", $_) . ', ' for (0 .. 2 ** $n - 1);
    
    # show output
    say qq[\nInput:  $n\nOutput: ] . substr($string, 0, -2);
}

9 lines of code

Output from script


Input:  2
Output: 00, 01, 10, 11

Input:  3
Output: 000, 001, 010, 011, 100, 101, 110, 111

Input:  4
Output: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 
  1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111

Input:  6
Output: 000000, 000001, 000010, 000011, 000100, 000101,
  000110, 000111, 001000, 001001, 001010, 001011, 001100,
  001101, 001110, 001111, 010000, 010001, 010010, 010011,
  010100, 010101, 010110, 010111, 011000, 011001, 011010,
  011011, 011100, 011101, 011110, 011111, 100000, 100001, 100010, 100011, 100100, 100101, 100110, 100111, 101000, 101001, 101010, 101011, 101100, 101101, 101110, 101111,
  110000, 110001, 110010, 110011, 110100, 110101, 110110,
  110111, 111000, 111001, 111010, 111011, 111100, 111101,
  111110, 111111

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain