Task 1: Rotate Matrix
Write a script to rotate a given 3x3 matrix by 90, 180, and 270 degrees clockwise.
Example Output
Rotate by 90:
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]
Logic
We can rotate a matrix by transposing it (swapping rows and columns) and then reversing either the rows or the columns depending on the direction of rotation. We can use slicing libraries like PDL in Perl or NumPy in Python to do this cleanly.
Perl Solution
ch-1.pl
use PDL;
my $m = sequence(3,3)+1;
for (0..2) {
say(90*($_+1));
$m = $m->transpose->slice([-1,0]);
print($m);
}
Python Solution
ch-1.py
import numpy as np
class ArrRotator:
def __init__(self):
self.arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
def rotate_arr(self, degree: int):
result_arr = self.arr
for _ in range(degree // 90):
result_arr = np.rot90(result_arr, -1)
return result_arr
Task 2: Vowel Strings
Generate all possible vowel strings of a given length that follow specific adjacency rules (e.g. ae, ai, ei, etc.).
Logic
Generate all permutations/combinations of vowels of the given length. Filter them by checking if all adjacent characters in the string match the allowed transition rules.
Perl Solution
ch-2.pl
use List::Permute::Limit qw(permute_iter);
my @ok_rules = ( 'ae', 'ai', 'ei', 'ia', 'ie', 'io', 'iu', 'oa', 'ou', 'uo', 'ue' );
my %ok_hash = map { $_ => 1} @ok_rules;
sub check_perm {
my $perm = shift;
my @perm_arr = @$perm;
for ( 0 .. scalar @perm_arr - 2 ) {
return 0 unless $ok_hash{$perm_arr[$_] . $perm_arr[ $_ + 1 ]};
}
return 1;
}
Python Solution
ch-2.py
from itertools import permutations
class VowelString:
def check_valid(self):
ok_rules = ['ae', 'ai', 'ei', 'ia', 'ie', 'io', 'iu', 'oa', 'ou', 'uo', 'ue']
for item_count, item in enumerate(self.permutation[:-1]):
if item + self.permutation[item_count+1] not in ok_rules:
return 0
return 1