You are given a matrix of size
M x N
having only0
s and1
s.Write a script to set the entire row and column to
0
if an element is0
.
Here’s my solution:
#!/usr/bin/env raku
my $M = 3;
my $N = 3;
my @matrix = [1, 0, 1],
[1, 1, 1],
[1, 0, 1];
my @result = [1 xx $N] xx $M;
@result[$_] = [0 xx $N] if 0 ∈ @matrix[$_] for ^$M;
@result[*; $_] = [0 xx $M] if 0 ∈ @matrix[*; $_] for ^$N;
.put for @result;
It’s very easy to follow. Every row that contains 0 zeroes an entire row in the @result
matrix, and every column that contains 0 zeroes an entire column. The trick is the use of subscripts and Array
s (as opposed to List
s).
You are given a singly linked list
$L
as below:L0 → L1 → … → Ln-1 → Ln
Write a script to reorder list as below:
L0 → Ln → L1 → Ln-1 → L2 → Ln-2 →
This one required a bit of cheating:
#!/usr/bin/env raku
my @list = 1 => 2, 2 => 3, 3 => 4, 4 => Nil;
for ^@list/2 {
my $A := @list[$_];
my $Z := @list[* - 1 - $_];
($A, $Z) = ($A.key => $Z.key), ($Z.key => $A.value);
}
@list[*/2] = @list[*/2].key => Nil;
say @list.map({.key, .value}).flat[^*/2].join(" → ");
(Well, it didn’t require cheating. I just chose the way that involved cheating.)