Perl Weekly Challenge: Week 400

Challenge 1:

Largest Interval

You are given a positive integer.

Write a script that generates a sequence of integers from 1 to given positive integer, filtering out any numbers that contain repeating digits (e.g., 11, 99, 100, and 101 are excluded) and return the biggest jump.

Example 1
Input: $int = 20
Output: 2

Biggest jump between 10 and 12.
Example 2
Input: $int = 110
Output: 4

Biggest jump between 98 and 102.
Example 3
Input: $int = 500
Output: 11

Biggest jump between:
a) 109 and 120 => 11
b) 219 and 230 => 11
c) 329 and 340 => 11
d) 439 and 450 => 11
Example 4
Input: $int = 2026
Output: 105

Biggest jump between 1098 and 1203.
Example 5
Input: $int = 10000
Output: 105

The largest gap is 105, between 1098 and 1203. And again between 8796 and 8901.

$biggestJump will store the eventual answer. Initially it is set to 0.

my $biggestJump = 0;

Then, from the range 1 to $int we use .grep() to keep all the numbers which do not contain repeating digits.

my @nonrepeating = (1 .. $int).grep({ $_ !~~ / (\d) .* $0 / });

Then from the second element (index 1) of @nonrepeating to the last, we subtract the preceding element from it and if this value is larger than $biggestJump it becomes the new value of $biggestJump.

for 1 .. @nonrepeating.end -> $i {
    $biggestJump = max($biggestJump, @nonrepeating[$i] - @nonrepeating[$i - 1]);
}

Finally we print $biggestJump.

say $biggestJump;

(Full code on Github.)

For the Perl version we need a replacement for .max().

my $biggestJump = 0;
my @nonrepeating = grep { $_ !~ / (\d) .* \1 /x } 1 .. $int;

for my $i (1 .. scalar @nonrepeating - 1) {
    $biggestJump = max($biggestJump, $nonrepeating[$i] - $nonrepeating[$i - 1]);
}

say $biggestJump;

(Full code on Github.)

Challenge 2:

Minimum Genetic Mutation

You are given start and end gene string along with gene bank.

Write a script to return the minimum number of mutations required to mutate from start to end gene. Return -1 if there is no such mutation. A gene must be in a bank to make it a valid gene string.

A gene string can be represented by an 8-character long string, with choices from ‘A’, ‘C’, ‘G’, and ‘T’.

Example 1
Input: $start_gene = "AACCGGTT"
    $end_gene   = "AACCGGTA"
    @gene_bank  = ("AACCGCTA", "AAACGGTA")
Output: -1

To reach end gene, every intermediate gene and the end gene itself must exist in bank.
Since "AACCGGTA" is missing from bank, it is impossible to complete the mutation sequence.
Example 2
Input: $start_gene = "AACCGGTT"
    $end_gene   = "AACCGGAA"
    @gene_bank  = ("AACCGGTA", "AACCGGAA", "AACCGCTA", "AACCCTAA", "AACCGTAA")
Output: 2

Path 1 (2 steps): "AACCGGTT" => "AACCGGTA" => "AACCGGAA"
Example 3
Input: $start_gene = "AAAAAAAA"
    $end_gene   = "AAAAACCC"
    @gene_bank  = ("CAAAAAAA", "CCAAAAAA", "AAAAAAAC")
Output: -1
Example 4
Input: $start_gene = "GAAAAAAA"
    $end_gene   = "GCCCCCCC"
    @gene_bank  = ("GCAAAAAA", "GCCAAAAA", "GCCCAAAA", "GCCCCAAA", "GCCCCCAA", "GCCCCCCA", "GCCCCCCC")
Output: 7

"GAAAAAAA" => "GCAAAAAA"
"GCAAAAAA" => "GCCAAAAA"
"GCCAAAAA" => "GCCCAAAA"
"GCCCAAAA" => "GCCCCAAA"
"GCCCCAAA" => "GCCCCCAA"
"GCCCCCAA" => "GCCCCCCA"
"GCCCCCCA" => "GCCCCCCC"
Example 5
Input: $start_gene = "AACCGGTT"
    $end_gene   = "AACCGGTT"
    @gene_bank = ("AACCGGTA")
Output: 0

The current genetic sequence already matches the desired end gene.
No mutations are necessary, so the result is 0.

This is another challenge which can be modelled as a tree on which we can perform a breadth-first search.

Before we begin, there is one scenario which avoids having to do any work at all; if the start gene and end gene are the same. In this case, no mutations are needed so we can just print 0 and exit.

if $start_gene eq $end_gene {
    say 0;
    return;
}

It is convenient to store the gene bank as a set for quick membership checks.

my Set $bank = @gene_bank;

If the end gene is not in the bank, it will never be reachable so we print -1 and bail out.

unless $end_gene ∈ $bank {
    say -1;
    return;
}

We nneed to track the shortest known distance to each gene while doing the breadth-first search so we create a hash %distance whose keys will be genes and values the distance to them. Initially, we populate it with the start gene which, naturally, has a distance of 0.

my %distance = $start_gene => 0;

Breadth-first search requires a queue of nodes to search and the node currently being searched (the $head of the queue.)

my @queue = $start_gene;
my $head = 0;

While we have nodes in the queue...

while $head < @queue.elems {

...we make the head node the current gene and also create a list of its' individual characters.

    my $currentGene = @queue[$head++];
    my @characters = $currentGene.comb;

We will try changing exactly one character at each possible position.

    for 0 .. @characters.end -> $position {
        my $originalBase = @characters[$position];

        for <A C G T> -> $nextBase {

If our selected character is the same as the original character we skip it and go on to the next one.

            if $nextBase eq $originalBase {
                next;
            }

Otherwise we construct a candidate gene with the selected character changed.

            @characters[$position] = $nextBase;
            my $nextGene = @characters.join(q{});
            @characters[$position] = $originalBase;

A mutation is valid only when the candidate exists in the bank so if it doesn't we move on to the next candidate.

            unless $nextGene ∈ $bank {
                next;
            }

We can also skip genes that have already been reached by a shorter route.

            if %distance{$nextGene}:exists {
                next;
            }

The distance to this next candidate gene is the distance to the current gene + 1.

            %distance{$nextGene} = %distance{$currentGene} + 1;

If the next gene is the same as the end gene, we have our answer. We print its' distance and exit.

            if $nextGene eq $end_gene {
                say %distance{$nextGene};
                return;
            }

Otherwise it gets added to the end of the breadth-first search queue.

            @queue.push($nextGene);
        }
    }
}

If the queue is completely exhausted and we have been unable to reach the end gene, we print -1.

say -1;

(Full code on Github.)

In Perl, we don't have a Set data type so we use a Hash as a workaround.

my ($start_gene, $end_gene, @gene_bank) = @ARGV;

if ($start_gene eq $end_gene) {
    say 0;
    exit;
}

my %bank = map { $_ => true } @gene_bank;

unless (exists $bank{$end_gene}) {
    say -1;
    exit;
}

my %distance;
$distance{$start_gene} = 0;
my @queue = $start_gene;
my $head = 0;

while ($head < scalar @queue) {
    my $currentGene = $queue[$head++];
    my @characters = split //, $currentGene;

    for my $position (0 .. scalar @characters - 1) {
        my $originalBase = $characters[$position];

        for my $nextBase (qw/ A C G T/) {
            if ($nextBase eq $originalBase) {
                next;
            }

            $characters[$position] = $nextBase;
            my $nextGene = join q{}, @characters;
            $characters[$position] = $originalBase;

            unless (exists $bank{$nextGene}) {
                next;
            }

            if (exists $distance{$nextGene}) {
                next;
            }

            $distance{$nextGene} = $distance{$currentGene} + 1;

            if ($nextGene eq $end_gene) {
                say $distance{$nextGene};
                exit;
            }

            push @queue, $nextGene;
        }
    }
}

say -1;

(Full code on Github.)