April 2019 Archives

Perl Weekly Challenge 006: Ranges and Ramanujan's Constant

This week, after having read the tasks, I decided to demonstrate the power of CPAN. There already are modules that solve the problems, so the only skill you need is the art of searching CPAN.

Perl Weekly Challenge 005: The Anagrams

When I read the definition of an anagram in Wikipedia, I knew I would need a combinatorics module. I first checked Math::Combinatorics and tried to generate all the anagrams using its next_permutation method. I could have used Algorithm::Combinatorics and its permutations, as well.

But there was a catch: if a letter is repeated in the input word, the anagrams won’t be unique. I didn’t want to reach for List::Util’s uniq as it needs to keep all the anagrams in memory while the iterator had much lower memory footprint. Fortunately, I knew that “unique” means “hash” in Perl.

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

use Math::Combinatorics;

my @letters = split //, shift;
my $iter = 'Math::Combinatorics'->new(data  => \@letters);
my %seen;
$seen{$_}++ or say $_ while $_ = join '', $iter->next_permutation;

About E. Choroba

user-pic I blog about Perl.