Robbie Hatley’s Solutions, in Perl, for The Weekly Challenge #388 (“Dyck Words” and “Secret Santa”)

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here: The Weekly Challenge

The Weekly Challenge for the week of 2026-08-24 through 2026-08-30 is #388.

The tasks for challenge #388 are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 388-1: Dyck Words
Submitted by: Mohammad S Anwar
A Dyck Word of order $n is a string of length 2x$n consisting of
$n ‘U’ (Up) characters and $n ‘D’ (Down) characters such that no
initial prefix of the string contains more ‘D’s than ‘U’s.

Write a script to return a list of all valid Dyck words of
length 2x$n, sorted in lexicographical (alphabetical) order.

I first generate likely candidate equivalent integers (with the correct number of binary digits, beginning with 1 and ending with 0). I then check each candidate to see if it actually is a Dyck number. For each Dyck number, I sprintf it as a binary number, transliterate 01 to DU, quote it, and push it to a list. Finally, I return the list. (There is no need to sort the list, as the fact that I generate candidates in increasing order means that the final list is already in sorted.)

Robbie Hatley's Perl Solution to The Weekly Challenge 388-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 388-2: Secret Santa
Submitted by: Roger Bell_West
A company with $n employees is running a Secret Santa exchange.
Each employee buys one gift and receives one gift.
Write a script to return the total number of valid gift
assignments where no employee receives the gift they originally
bought (i.e., employee $i must not be assigned gift $i).

The number of Secret Santa arrangements for n persons is the nth Pierre Remond de Montmort number, which is the number of derangements of n items. The "derangements" function of CPAN module "Algorithm::Combinatorics" generates the correct number of arrays for all non-negative integers. (Sadly, CPAN module "Math::Combinatorics" does NOT give the correct answers for the "0" and "1" cases.)

Robbie Hatley's Perl Solution to The Weekly Challenge 388-2

That's it for challenge 388; see you on challenge 389!

Comments

Popular posts from this blog

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #336 (“Equal Group” and “Final Score”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #339 (Theme: “Maximum Overdrive”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #341 (“Broken Keyboard” and “Reverse Prefix”)