May 2019 Archives

Square Numbers

Find the fist square number with at least five distinct digits.

The word “distinct” is translated to “hash” in Perl. Just iterate over the square numbers and count the distinct digits (thanks holli for pointing out starting from 1 makes little sense):

``````#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

sub distinct_digits {
my (\$n) = @_;
my %d;
undef @d{split //, \$n};
return keys %d
}

my \$n = int sqrt 10234;
while (distinct_digits(\$n ** 2) < 5) {
++\$n;
}
say \$n ** 2;``````

Perl Weekly Challenge 008: Perfect Numbers and Centring

This time, the first challenge was more difficult than the second one. So, let’s start with the easier one.

Centring

To centre an array of lines, just find the longest one, and prolong each line on both sides so its length is the same as the maximal one. When printing, we don’t have to prolong the right hand sides of the lines, prefixing the spaces to the left is enough.

``````#!/usr/bin/perl
use warnings;
use strict;

use Path::Tiny;
use List::Util qw{ max };

sub center {
my @lines = @_;
my \$max_length = max(map length, @lines);
return map +(' ' x ((\$max_length - length) / 2)) . \$_, @lines
}

my @lines = path(shift)->lines;
print for center(@lines);
``````

Perl Weekly Challenge 007: Niven Numbers and a Word Ladder

I know I’m late with my blog post. I had the solutions ready in time, but I suffered a dental abscess and spent the rest of the week either praying for the painkillers to kick in or sleeping when they did.