Rafraîchissoir

By Shahed Nooshmand

Perl Weekly Challenge: week 64

Task #1

Given an m × n matrix with non-negative integers, write a script to find a path from top left to bottom right which minimizes the sum of all numbers along its path. You can only move either down or right at any point in time.

Classic. Here’s one solution:

#!/usr/bin/env raku

my @matrix = [1, 2, 3],
             [4, 5, 6],
             [7, 8, 9];
say "{.sum} ({.join: ' → '})" given min paths(@matrix, 0, 0), by => ∑


sub paths(@matrix, $i, $j) {
	my @paths;
	my $pivot = @matrix[$i][$j];
	my $right = @matrix[$i][$j+1];
	my $down  = @matrix[$i+1][$j];

	with $right {
		@paths.push: |paths(@matrix, $i, $j + 1).map: { $pivot, |$_ }
	}
	with $down {
		@paths.push: |paths(@matrix, $i + 1, $j).map: { $pivot, |$_ }
	}
	without $right // $down {
		return $pivot
	}

	return @paths
}

I’m not super happy with it, but at least it’s self-explanatory.

Task #2

You are given a string $S and an array of words @W.

Write a script to find out if $S can be split into sequence of one or more words as in the given @W.

Print the all the words if found otherwise print 0.

Speaking of self-explanatory:

say $S ~~ m«^(@W)+$» ?? $0 !! 0

Doesn’t get any simpler than this. (Does it?)