The Weekly Challenge 062

Sort Email Addresses and 3D N-Queens

Solutions on GitHub

Task 1: Sort Email Addresses

Sort a list of email addresses by domain name first, then by mailbox name.

Example Output

Input: [[email protected], [email protected], [email protected]] Output: [email protected], [email protected], [email protected]

Logic

Split each email into mailbox and domain components around '@'. Sort primarily by domain, and secondarily by mailbox name.

Perl Solution

ch-1.pl

sub email_sort { my ($mailbox_a, $domain_a) = split '@', $a; my ($mailbox_b, $domain_b) = split '@', $b; return $domain_a cmp $domain_b || $mailbox_a cmp $mailbox_b; } my @sorted_emails = sort email_sort @emails;

Python Solution

ch-1.py

def email_sort_key(email: str): mailbox, domain = email.split('@') return (domain, mailbox) sorted_emails = sorted(emails, key=email_sort_key)

Task 2: 3D N-Queens

Place N queens on an N x N x N 3D chessboard such that no two queens attack each other.

Example Output

N = 4 Queens placed safely across 3D coordinates.

Logic

Backtracking search extending 2D N-queens check to 3 dimensions, checking 2D plane projections and 3D diagonals.

Perl Solution

ch-2.pl

sub is_safe { my ($cube, $x, $y, $z, $n) = @_; for my $i (0 .. $n-1) { return 0 if $cube->[$i][$y][$z] || $cube->[$x][$i][$z] || $cube->[$x][$y][$i]; } return 1; }

Python Solution

ch-2.py

def is_safe(cube, x, y, z, n): for i in range(n): if cube[i][y][z] or cube[x][i][z] or cube[x][y][i]: return False return True