Rafraîchissoir

By Shahed Nooshmand

The Weekly Challenge: week 76

Task #1

You are given a number $N. Write a script to find the minimum number of prime numbers required, whose summation gives you $N.

For the sake of this task, please assume 1 is not a prime number.

Since 1 isn’t a prime number, assuming it isn’t shouldn’t be too hard.

#!/usr/bin/env raku

say prime-sum 9;

sub prime-sum(Int $number where * ≥ 2) {
	return $number if $number.is-prime;

	my @primes = grep *.is-prime, 2, |(3, 5 ... $number);
	for 2..* -> $count {
		.return if .sum == $number for [X] @primes xx $count;
	}
}

It’s not the cleverest, but it gets the job done in a few lines.

Task #2

Write a script that takes two file names. The first file would contain word search grid as shown below. The second file contains list of words, one word per line. You could even use local dictionary file.

Print out a list of all words seen on the grid, looking both orthogonally and diagonally, backwards as well as forwards.

I liked this one:

#!/usr/bin/env raku

sub MAIN($grid-path, $words-path) {
	my @found = [];
	my @words = (slurp $words-path).fc.lines;

	my @grid = (slurp $grid-path).fc.lines».words;
	my @rows = @grid.map: *.cache.join;
	my @columns = ([Z] @grid).map: *.cache.join;
	my @diagonals;
	for ^4 {
		for ^@grid[0] {
			my $i = $_;
			@diagonals.push: [~] gather {
				take .[$i++] // last for @grid;
			}
		}
		@grid = ([Z] @grid)».reverse;
	}

	for @words -> $word {
		@found.push: $word if (@rows | @columns | @diagonals).grep: *.contains: $word | $word.flip;
	}

	.put for @found;
}

We rotate the grid four times to get all the diagonal strings. We start from one index in the first row of each rotation of the grid and take an index higher from the following row, incrementing as we go down. In the end, the grid is back where it started.