By Shahed Nooshmand

The Weekly Challenge: week 77

Task #1

You are given a positive integer $N.

Write a script to find out all possible combination of Fibonacci Numbers required to get $N on addition.

You are NOT allowed to repeat a number. Print 0 if none found.

Fibonacci is always a good demo in Raku:

raku -e 'say "@*ARGS[0] = {.join(" + ")}" for (1, 2, * + * ...^ * > @*ARGS[0]).combinations.grep(*.sum == @*ARGS[0])'

$N is passed as a command line argument.

There’s no need to print 0 if none found, because every positive integer is the sum of distinct Fibonacci numbers.

There’s also no need to check repetition, because we’re manually starting the second 1 in the sequence (it’s 1, 2, 3 ... instead of 0, 1, 1, 2, 3 ...).

Task #2

You are given m x n character matrix consists of O and X only.

Write a script to count the total number of X surrounded by O only. Print 0 if none found.

Here’s what I came up with:

#!/usr/bin/env raku

my @matrix =
	<O O X O>,
	<X O O O>,
	<X O O X>,
	<O X O O>;

.say for (^@matrix X ^@matrix[0]).grep: -> ($i, $j) {
	@matrix[$i; $j] eq 'X' and not (<1 0 -1> X <1 0 -1>).grep: -> ($x, $y) {
		$x | $y and do $_ eq 'X' with @matrix[$i + $x; $j + $y]

Which prints:

(0 2)
(2 3)

The outer grep searches all indices for those that hold X and aren’t surrounded by more X. The inner grep basically searches each index’s neighbourhood for another index that also holds X. If the inner grep returns an empty list, the condition for the outer grep becomes true (assuming the current index does hold X) and a “lonely X” has been found.

One more thing: it doesn’t print 0 if none found.