The weekly challenge 312 - Task 2: Balls and Boxes
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-312/#TASK2 3 # 4 # Task 2: Balls and Boxes 5 # ======================= 6 # 7 # There are $n balls of mixed colors: red, blue or green. They are all 8 # distributed in 10 boxes labelled 0-9. 9 # 10 # You are given a string describing the location of balls. 11 # 12 # Write a script to find the number of boxes containing all three colors. 13 # Return 0 if none found. 14 # 15 ## Example 1 16 ## 17 ## Input: $str = "G0B1R2R0B0" 18 ## Output: 1 19 ## 20 ## The given string describes there are 5 balls as below: 21 ## Box 0: Green(G0), Red(R0), Blue(B0) => 3 balls 22 ## Box 1: Blue(B1) => 1 ball 23 ## Box 2: Red(R2) => 1 ball 24 # 25 ## Example 2 26 ## 27 ## Input: $str = "G1R3R6B3G6B1B6R1G3" 28 ## Output: 3 29 ## 30 ## The given string describes there are 9 balls as below: 31 ## Box 1: Red(R1), Blue(B1), Green(G1) => 3 balls 32 ## Box 3: Red(R3), Blue(B3), Green(G3) => 3 balls 33 ## Box 6: Red(R6), Blue(B6), Green(G6) => 3 balls 34 # 35 ## Example 3 36 ## 37 ## Input: $str = "B3B2G1B3" 38 ## Output: 0 39 ## 40 ## Box 1: Green(G1) => 1 ball 41 ## Box 2: Blue(B2) => 1 ball 42 ## Box 3: Blue(B3) => 2 balls 43 # 44 ############################################################ 45 ## 46 ## discussion 47 ## 48 ############################################################ 49 # 50 # As long as we didn't use the full input yet, we pick the first 51 # two characters as color and box and take note of this pair. 52 # In the end, we check all boxes. Every box that has 3 different 53 # colors will be counted towards the result. 54 55 use v5.36; 56 57 balls_and_boxes("G0B1R2R0B0"); 58 balls_and_boxes("G1R3R6B3G6B1B6R1G3"); 59 balls_and_boxes("B3B2G1B3"); 60 61 sub balls_and_boxes($str) { 62 say "Input: \"$str\""; 63 my $boxes = {}; 64 while(length($str) > 1) { 65 my ($color, $box); 66 ($color, $box, $str) = split //, $str, 3; 67 $boxes->{$box}->{$color} = 1; 68 } 69 my $result = 0; 70 foreach my $box (keys %$boxes) { 71 my $count = keys %{$boxes->{$box}}; 72 $result++ if $count == 3; 73 } 74 say "Output: $result"; 75 }