The Bear's Den

Enter at your own risk

Non-Repeating Mutations

Task 1: Largest Interval

Submitted by: Ali Moradi


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.

Solution

The length of an interval is one more than the number of skipped numbers therein, i.e any skipped number enlarges a possible interval by one. As an interval (in this task) needs a number as its end that has not been skipped, the size of an interval is not known before a following number is being kept.

Whenever an interval is closed, we find the corresponding length and we may take the maximum over all lengths. At the same time we need to restart counting from zero.

It would be tedious to loop over all numbers from 1 to \(n\). The number of checks may be significantly reduced by the following considerations:

Perl

use strict;
use warnings;
use experimental qw(signatures vlb);
use POSIX 'Inf';

# integer decadic logarithm
sub ldi {
    length(shift) - 1;
}

# number of trailing zeroes
sub ntz {
    shift =~ /0*$/;
    $+[0] - $-[0];
}

# detect and process duplicate digits:
# - provide increment if duplicates
# - provide next value if unique
# force termination when $i exceeds the
# largest possible number having no duplicate digits
sub dupl ($i) {
    if ($i =~ /(.)(?<=(?=\1).{2,10})/) {
        return (1, 10**(ldi($i) - $-[1]))
    } else {
        my $transition = 11 * 10**(ldi($i) - 1);
        my $next = $i < $transition ?
            $transition : 10 ** (ldi($i) + 1);
        my $s = 0;
        $s = $s * 10 + $_ for 1 .. ntz($next) - 1;
        $next -= $s;
        $next = Inf if $next > 9876543210;
        return (0, $next);
    }
}

sub largest_interval ($n, $verbose=undef) {
    my ($i, $run, $max) = (11, 0, 0);
    while ($i <= $n) {
        my ($skip, $x) = dupl($i);
        if ($skip) {
            $run += $x;
            $i += $x;
        } else {
            $max = $run;
            printf "[%d, %d]: %d\n", $i - $run, $i - 1, $run if $verbose;
            $run = 0;
            $i = $x;
        }
    }
    $max + 1;
}

Using the -test option, all maximum intervals are shown:

$ perl/ch-1.pl -t
1..2
ok 1 - skip examples
# Subtest: tests
    1..1
[11, 11]: 1
[99, 101]: 3
[110, 119]: 10
[988, 1022]: 35
[1099, 1202]: 104
[9877, 10233]: 357
[10988, 12033]: 1046
[98766, 102344]: 3579
[109877, 120344]: 10468
[987655, 1023455]: 35801
[1098766, 1203455]: 104690
[9876544, 10234566]: 358023
[10987655, 12034566]: 1046912
[98765433, 102345677]: 3580245
[109876544, 120345677]: 10469134
[987654322, 1023456788]: 35802467
[1098765433, 1203456788]: 104691356
    ok 1 - no tests
ok 2 - Subtest: tests

These numbers can also be found as A398514, A398515 and A398513 in The On-Line Encyclopedia of Integer Sequences. Here the final number from A398514 (9876543211) does not show up because in sub dupl it is set to Inf as a stop condition. Internally it does appear!

The J solution comes with a trace that shows the algorithm in action.

See the full solution to task 1.

J

In its logic, this script is identical to the Perl version.

This script requires J9.8.

NB. find the largest interval(s) of numbers having duplicate digits
NB. usage: "limit (mode intervals) start, 0, 0"
NB. where:
NB. - limit is the upper limit for the number
NB. - mode is "_." for the largest interval or "a:" for all (largest) intervals
NB. - start is the starting number
intervals =: adverb define
  NB. argument getter
  '`i run max' =. (0&{@])`(1&{@])`(2&{@])

  NB. inplace value setter
  '`si srun smax' =. (0 })`(1 })`(2 })

  NB. select left operand depending on the
  NB. "uniq" component of "skip":
  if_uniq =. @.({.@[)

  NB. "target" component of "skip"
  targ =. {:@[

  NB. set or increment "i"
  ni =. targ`(targ + i) if_uniq

  NB. reset or increment "run"
  nrun =. (0:)`(targ + run) if_uniq

  NB. set or keep "max"
  nmax =. run`max if_uniq

  NB. integer decadic logarithm
  ldi =. <.@(10&^.)

  NB. find first repeated digit
  frd =. rxcomp '(.)(?<=(?=\1).{2,10})'

  NB. index of first repeated digit
  frdi =. (1 0)&{::

  NB. digits are unique if "frd" did not match
  is_uniq =. 0&> @ ((0 0)&{::) @ ]

  NB. return "(1, skip)" for duplicate digits
  dupl =. 1 , 10 ^  ldi@[ - frdi@]

  NB. the transition points
  tr1 =. 11 * 10 ^ 1 -~ ldi
  tr2 =. 10 ^ 1 + ldi

  NB. smallest next transition point
  ntr =. ] (tr2@[)`]@.(<) tr1

  NB. number to char array
  to_str =. 0&":@]

  NB. number of trailing zeroes
  ntz =. (0 1) {:: '0+$' rxmatch to_str

  NB. step back from transition point to smallest preceding duplicate
  back =. ] [`([ - 10 #. >: @ i. @ <: @ ])@.(1&<@]) ntz

  NB. digits are always duplicate beyond this value
  stop =. _:^:(9876543210&<)

  NB. return "(0, target)" for unique digits
  uniq =. 0 , stop @ back @ ntr @ [

  NB. distinguish duplicate / unique:
  NB. returns pair "(uniq, target)"
  skip =. (] dupl`uniq@.is_uniq frd rxmatch to_str)@i

  NB. loop over u while x is greater/equal "i" component of y 
  NB. return final result for n = _. or all for n = a:
  while_ge_i =. conjunction def 'u^:([ >: i)^:n'

  (skip (nmax smax nrun srun ni si ]) ]) while_ge_i m f: 'private' 
)

NB. Find the largest interval starting from 11 up to y and
NB. increment its element count.
largest_interval =: ([: >: 2 { ] (_. intervals) (11 0 0)"_) : [:
Trace

The adverb intervals may create a verb that produces a trace over the loop. Here are the intermediate results (i, run, max) starting from 6543:

   10654 (a: intervals) 6543 0 0
 6543   0   0
 9877   0   0
 9878   1   0
 9879   2   0
 9880   3   0
 9890  13   0
 9900  23   0
10000 123   0
10100 223   0
10200 323   0
10210 333   0
10220 343   0
10230 353   0
10231 354   0
10232 355   0
10233 356   0
10234 357   0
10988   0 357

See the full solution.

Task 2: Minimum Genetic Mutation

Submitted by: Mohammad Sajid Anwar


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"
Path 2 (3 steps): "AACCGGTT" => "AACCGGTA" => "AACCGTAA" => "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.

Solution

The genes may be regarded as vertices of an undirected graph, where two vertices are connected with an edge if the corresponding genes differ in exactly one nucleobase.

We add corresponding edges between all of the start gene and the genes from the bank. In the resulting graph we search for the shortest path between the start and end genes.

Perl

Using the Graph package to represent the graph and to find the shortest path. The path length that is requested in this task corresponds to the number of edges in the path, but SP_Dijkstra provides the path’s edges. Therefore the size of the paths needs to be decremented for the correct result. When there is no path between the vertices, the function returns an empty list. Decrementing this size leads to the expected value of -1.

To find the difference between two gene strings, these may be “string xor’ed” (^.) and unpacked as unsigned chars. Every non-zero value signals a single difference.

use strict;
use warnings;
use experimental 'signatures';
use feature 'bitwise';
use Graph::Undirected;

sub mgm ($start, $end, $b) {
    my @b = ($start, @$b);
    my $g = Graph::Undirected->new(vertices => [$end, @$b]);
    while (my $x = shift @b) {
        1 == grep $_, unpack 'c*', $x ^. $_ and $g->add_edge($x, $_) for @b;
    }

    @{[$g->SP_Dijkstra($start, $end)]} - 1;
}

See the full solution to task 2.

J

Using an implementation of the Floyd-Warshall APSP algorithm from the J Wiki. This algorithm is not the best choice for this task, but was the easiest to be used I found in the Wiki.

To identify differences between gene strings these may simply be compared for “not equal”.

If the start and end gene both correspond to vertices in the graph but there is no path connecting them, the Floyd-Warshall algorithm will return “infinity”. Analogously, we set the distance to “infinity” if the end gene has no corresponding vertex. As the final step, infinity is transformed to minus one, covering both cases.

NB. minimum genetic mutation
NB. usage: "db mgm start, end"
mgm =: _(adverb define)
  NB. argument accessors
  '`start end db' =: (0&{@])`(1&{@])`[

  NB. Create an initial distance matrix for the genes:
  NB. - The distance between two genes is the number of
  NB.   divergent nucleobases for zero or one disagreements.
  NB. - infinity otherwise
  dist =. _:`]@.(1&>:) @ (+/) @: ~:"1 /~

  NB. Create the all pairs shortest path matrix
  NB. using the Floyd-Warshall algorithm.
  NB. See https://code.jsoftware.com/wiki/Essays/Floyd
  floyd =. 3 :('for_j. i.#y';'do. y=. y <. j ({"1 +/ {) y';'end.';'y')

  NB. Accessor for the distance between start and end gene
  NB. from the distance matrix:
  NB. Find the index "ei" of "end" within "(start, db)" and
  NB. select element "(0, ei)".
  NB. Provide infinity on out-of-bound access.
  dist_se =. ] ({::~ :: _) 0 , }:@[ i. {:@[

  NB. transform infinity to minus one
  inf2neg =. (_1:)^:(_&=)

  NB. - Create the distance matrix for the genes except end.
  NB. - Apply Floyd-Warshall to find the shortest paths.
  NB. - Find the distance between start and end gene.
  NB. - Handle infinity.
  [: : ([: ([: inf2neg ] dist_se [: floyd [: dist }:) start , db , end) f.
)

See the full solution.

[Update:]
There is an implementation of Dijkstra’s SSSP algorithm in the J Wiki, too. At first glance it seems not as easy to be used as the provided Floyd-Warshall implementation, but that is delusive.

It has two closely related advantages:

require 'dict'

NB. See https://code.jsoftware.com/wiki/Vocabulary/Dictionaries_(addon)#Shortest_paths_Dijkstra's_algorithm
dijkstra =: {{
q =. conew&'jdict' 'tree' ,&< ('keyshape' ; 2) ,: 'valueshape' ; 0
'ds ps' =. ($&_ ; $&_1)@# x  NB. Initialize distances and predecessors.
'' put__q 0 , y [ ds =. 0 y} ds  NB. Distance to source is 0.
while. count__q '' do.
  del__q 'd i' =. min__q ''  NB. Extract the minimum-distance vertex.
  if. d > i { ds do. continue. end.  NB. Skip outdated entry.
  'js ws' =. i { x  NB. Adjacent vertices and edge weights.
  NB. Filter out edges that do not improve shortest paths.
  'js ws' =. (#&js (~.@[ ; <.//.) #&ws) (d + ws) < js { ds
  ds =. ds js}~ d + ws  NB. Update distances.
  ps =. i js} ps  NB. Update predecessors.
  '' put__q js ,.~ d + ws  NB. Insert the updated distance–vertex pairs.
end.
destroy__q ''
ds ; ps
}}"2 0

NB. minimum genetic mutation
NB. usage: "db mgm start, end"
mgm =: _(adverb define)
  NB. argument accessors
  '`start end db' =: (0&{@])`(1&{@])`[

  NB. Create a graph from the genes:
  NB. - The neigbors of a vertex are the genes that disagree in
  NB.   exactly one nucleobase
  NB. - all edges have a weight of 1
  NB. - the graph is terminated with an empty neighbor list
  graph =. (] ,. 1"0 L:0) @ (a: ,~ <@I. @: ((1&=)@ (+/) @: ~:"1 /~))

  NB. Accessor for the distance between start and end gene
  NB. from the distance vector:
  NB. Pick the element at the index of "end" within "(start, db)" and
  NB. provide infinity on out-of-bound access.
  dist_e =. ] ({::~ :: _) 0 ; }:@[ i. {:@[

  NB. transform infinity to minus one
  inf2neg =. (_1:)^:(_&=)

  NB. graph =. ] ,. 1"0 L:0
  NB. - Create the distance matrix for the genes except end.
  NB. - Apply Floyd-Warshall to find the shortest paths.
  NB. - Find the distance between start and end gene.
  NB. - Handle infinity.
  [: : ([: ([: inf2neg ] dist_e 0 dijkstra~ [: graph }:) start, db, end) f.
)