Task 1: Pokemon Sequence
Given a list of Pokemon names, find the longest sequence of names such that the last letter of one matches the first letter of the next.
Logic
We perform a greedy depth-first or iterative search starting from each name in the list, maintaining a list of used names. If the last character of the current name matches the first character of a candidate name, we greedily transition to it and continue the sequence, keeping track of the longest path found.
Perl Solution
ch-1.pl
my @names = qw(audino bagon baltoy ...);
my %used;
my @sequence;
foreach my $name (@names) {
next if $used{$name};
my $current = $name;
my @temp = ($current);
my %temp_used = %used;
$temp_used{$current} = 1;
while (1) {
my $found = 0;
foreach my $next (@names) {
next if $temp_used{$next};
if ( substr( $current, -1 ) eq substr( $next, 0, 1 ) ) {
$current = $next;
push( @temp, $current );
$temp_used{$current} = 1;
$found = 1;
last;
}
}
last unless $found;
}
if ( scalar(@temp) > scalar(@sequence) ) {
@sequence = @temp;
}
%used = %temp_used;
}
Python Solution
ch-1.py
for name in names:
if name in used:
continue
current = name
temp = [current]
temp_used = used.copy()
temp_used[current] = True
while True:
found = False
for next_name in names:
if next_name in temp_used:
continue
if current[-1] == next_name[0]:
current = next_name
temp.append(current)
temp_used[current] = True
found = True
break
if not found:
break
if len(temp) > len(sequence):
sequence = temp
used = temp_used
Task 2: Chaocipher
Implement a script to encrypt and decrypt messages using the symmetric Chaocipher algorithm with fixed mixed alphabets.
Logic
Chaocipher maps characters through left and right mixed alphabets. For each character, we find its index in one alphabet, shift/swap indices, and lookup the mapped character in the other alphabet. Non-alphabetic characters are preserved.
Perl Solution
ch-2.pl
sub chaocipher_encrypt {
my $message = shift;
my $ciphertext = "";
my $left_index = 0;
my $right_index = 0;
foreach my $char ( split //, uc($message) ) {
if ( $char !~ /[A-Z]/ ) {
$ciphertext .= $char;
next;
}
my $left_char_index = index( $left_alphabet, $char );
( $left_index, $right_index ) = ( $right_index, $left_index );
my $right_char = substr( $right_alphabet, ( $left_char_index + $right_index ) % 26, 1 );
$ciphertext .= $right_char;
}
return $ciphertext;
}
Python Solution
ch-2.py
def chaocipher_encrypt(message: str) -> str:
left_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
right_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"
ciphertext = ""
left_index = 0
right_index = 0
for char in message.upper():
if not char.isalpha():
ciphertext += char
continue
left_char_index = left_alphabet.index(char)
left_index, right_index = right_index, left_index
right_char_index = (left_char_index + right_index) % 26
ciphertext += right_alphabet[right_char_index]
return ciphertext