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.