Task 1: Similar List
Given three lists of integers, check if all three lists are similar (contain the same unique set of elements).
Example Output
Input: @list1 = (1, 2, 2, 3), @list2 = (2, 3, 1), @list3 = (3, 1, 2, 1)
Output: true
Logic
Convert each list into a set of unique elements (using hash keys in Perl and set() in Python) and test if all three sets are identical.
Perl Solution
ch-1.pl
sub are_similar_lists ( $list1, $list2, $list3 ) {
my %set1 = map { $_ => 1 } @$list1;
my %set2 = map { $_ => 1 } @$list2;
my %set3 = map { $_ => 1 } @$list3;
my @k1 = sort keys %set1;
my @k2 = sort keys %set2;
my @k3 = sort keys %set3;
return 0 if @k1 != @k2 || @k1 != @k3;
for my $i ( 0 .. $#k1 ) {
return 0 if $k1[$i] ne $k2[$i] || $k1[$i] ne $k3[$i];
}
return 1;
}
Python Solution
ch-1.py
def are_similar_lists(
list1: list[int], list2: list[int], list3: list[int]
) -> bool:
"""Return True if all three lists contain the same set of unique elements."""
return set(list1) == set(list2) == set(list3)
Task 2: Nearest RGB
Given a 7-character hexadecimal color string #RRGGBB, find the nearest 4-character shorthand #RGB hex color.
Example Output
Input: $hex_color = "#09f166"
Output: "#11ee66" or "#1E6"
Logic
Each channel in 4-character shorthand expands to duplicate nibbles (multiples of 17). Round each of the R, G, B channel values (0..255) to the nearest multiple of 17.
Perl Solution
ch-2.pl
sub nearest_rgb ($hex_color) {
$hex_color =~ s/^#//;
my $r = hex( substr( $hex_color, 0, 2 ) );
my $g = hex( substr( $hex_color, 2, 2 ) );
my $b = hex( substr( $hex_color, 4, 2 ) );
my $r_short = _round_to_nearest( $r, 17 );
my $g_short = _round_to_nearest( $g, 17 );
my $b_short = _round_to_nearest( $b, 17 );
return sprintf( "#%X%X%X", $r_short / 17, $g_short / 17, $b_short / 17 );
}
Python Solution
ch-2.py
def nearest_rgb(hex_color: str) -> str:
"""Find the nearest 4-character shorthand #RGB for a 7-character #RRGGBB."""
hex_color = hex_color.lstrip("#")
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
r_idx = min(15, round(r / 17))
g_idx = min(15, round(g / 17))
b_idx = min(15, round(b / 17))
return f"#{r_idx:X}{g_idx:X}{b_idx:X}"