The Weekly Challenge 043

Olympic Rings Puzzle and Self-Descriptive Numbers

Solutions on GitHub

Task 1: Olympic Rings Puzzle

There are 5 rings: Blue, Black, Red, Yellow, Green. Determine placing numbers from 1 to 9 (excluding some already placed) such that the sum of numbers in each ring is 11.

Example Output

Found solutions: Blue: 8, Black: 2, Red: 1, Yellow: 3, Green: 7...

Logic

Generate all permutations of the available numbers. Check each permutation to ensure that the sum of values within each overlapping ring system (e.g. b + k + r == 11 and r + y + g == 11) equals 11.

Perl Solution

ch-1.pl

my $iter = permutations( \@available ); while ( my $p = $iter->next ) { my ( $b, $k, $r, $y, $g ) = @$p; next if ( $b == $k || $b == $r || $b == $y || $b == $g ); next if ( $k == $r || $k == $y || $k == $g ); next if ( $r == $y || $r == $g ); next if ( $y == $g ); if ( $b + $k + $r == 11 && $r + $y + $g == 11 ) { # Save the solution... } }

Python Solution

ch-1.py

from itertools import permutations for b, k, r, y, g in permutations(available): if b == k or b == r or b == y or b == g: continue if k == r or k == y or k == g: continue if r == y or r == g: continue if y == g: continue if b + k + r == 11 and r + y + g == 11: # Save solution...

Task 2: Self-Descriptive Numbers

Write a script to generate self-descriptive numbers in a given base. A self-descriptive number is an integer in which each digit counts the occurrences of that digit's index in the number.

Example Output

Base 10: 6210001000

Logic

Iterate through candidate integers. For each number, count the occurrences of each digit. Join these counts together as a new number string and compare it back to the original number. If they are equal, the number is self-descriptive.

Perl Solution

ch-2.pl

sub sd { my ( $n, $base ) = @_; my @digits = split //, $n; my @counts = (0) x $base; for my $d (@digits) { $counts[$d]++; } return join( '', @counts ) == $n; }

Python Solution

ch-2.py

def self_descriptive(base): def sd(n): digits = [int(d) for d in str(n)] counts = [0] * base for d in digits: counts[d] += 1 return int("".join(map(str, counts))) == n # generator loop...