Peter’s blog ✴ Week 312 ✴ 10 March 2025

THE WEEKLY CHALLENGE
Time box

The Perl Camel

Task 2

Balls and boxes

There are n balls of mixed colours: red, blue or green. They are all distributed in 10 boxes labelled 0-9. You are given a $string describing the location of balls. Write a script to find the number of boxes containing all three colours. Return 0 if none found.

Examples


Example 1
Input: $str = "G0B1R2R0B0"
Output: 1
The given string describes there are 5 balls as below:
Box 0: Green(G0), Red(R0), Blue(B0) => 3 balls
Box 1: Blue(B1) => 1 ball
Box 2: Red(R2) => 1 ball

Example 2
Input: $str = "G1R3R6B3G6B1B6R1G3"
Output: 3
The given string describes there are 9 balls as below:
Box 1: Red(R1), Blue(B1), Green(G1) => 3 balls
Box 3: Red(R3), Blue(B3), Green(G3) => 3 balls
Box 6: Red(R6), Blue(B6), Green(G6) => 3 balls

Example 3
Input: $str = "B3B2G1B3"
Output: 0
Box 1: Green(G1) => 1 ball
Box 2: Blue(B2)  => 1 ball
Box 3: Blue(B3)  => 2 balls

Analysis

What is needed is to count the number of colours in each box.

I do that by setting up an array @box and ORing the value of $box[$i] by 1 if it contains a red ball, by 2 if it contains a green ball and by 4 if it contains a blue ball.

The answer is then the count of members of @box which equal 4 + 2 + 1 = 7.

The task description states that there are 10 boxes: my solution will also work if there are more (eg 'R12G12B12')

Perl Weekly’s review

from PW issue 712

I like the simplistic approach, without any gimmicks. The task analysis is not to be missed. Well done and keep it up.

This review may cover either or both challenges for this week.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: R5G6B7R6G7R7

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2025-03-10
use utf8;     # Week 312 - task 2 - Balls and boxes
use warnings; # Peter Campbell Smith
no warnings 'uninitialized';
binmode STDOUT, ':utf8';

balls_and_boxes('G0B1R2R0B0');
balls_and_boxes('G1R3R6B3G6B1B6R1G3');
balls_and_boxes('B3B2G1B3');

sub balls_and_boxes {
    
    my (%colours, $string, @box, $count);
    
    # initialise
    $string = shift;
    %colours = (R => 1, G => 2, B => 4);

    # count which colours seen
    $box[$2] |= $colours{$1} while $string =~ m|(.)(\d+)|g;
    
    # count full boxes
    $count = $count + ($_ == 7 ? 1 : 0) for @box;   
    
    say qq[\nInput:  \$string = '$string'];
    say qq[Output: ] . ($count + 0);
}

8 lines of code

Output from script


Input:  $string = 'G0B1R2R0B0'
Output: 1

Input:  $string = 'G1R3R6B3G6B1B6R1G3'
Output: 3

Input:  $string = 'B3B2G1B3'
Output: 0

 

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