Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #300 (Beautiful Permutations and Nested Arrays)
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:
The Weekly Challenge for the week of 2024-12-15 through 2024-12-21 is #300.
The tasks for challenge #300 are as follows:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 300-1: Beautiful Arrangements Submitted by: Mohammad Sajid Anwar Description re-written by Robbie Hatley for clarity: Given a positive integer n, write a script to return the number of "beautiful arrangements" within the set of permutations of the sequence (1..n). A 1-indexed permutation of (1..n) is considered "a beautiful arrangement" if for every i (1 <= i <= n) either of the following is true: 1) perm[i] is divisible by i 2) i is divisible by perm[i] Example #1: Input: $n = 2 Output: 2 1st arrangement: [1, 2] perm[1] is divisible by i = 1 perm[2] is divisible by i = 2 2nd arrangement: [2, 1] perm[1] is divisible by i = 1 i=2 is divisible by perm[2] = 1 Example #2: Input: $n = 1 Output: 1 Example #3: Input: $n = 10 Output: 700
Other than the hassle of having to generate all of the permutations of (1..n), then counting how many of them are "beautiful arrangements", this is conceptually straightforward, if a bit complex (O(n!)). One snag is the requirement for "1-indexed", but I'll handle that by just unshifting the string "dummy" to the left end of every permutation. And to generate the permutations, I'll use the non-OOP "permute" function from CPAN module "Math::Combinatorics".
Robbie Hatley's Perl Solution to The Weekly Challenge 300-1
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Task 300-2: Nested Arrays Submitted by: Mohammad Sajid Anwar Description re-written by Robbie Hatley for clarity: You are given an array @ints of integers of length n containing a permutation of the integers in the range [0,n-1]. Write a script to build the n sets "set[i]" (0 <= i <= n-1) such that set[i] = {ints[i], ints[ints[i]], ints[ints[ints[i]]], etc}. For each set[i], stop adding elements right before a duplicate element occurs. Return the length of the longest set[i]. Example #1: Input: (5, 4, 0, 3, 1, 6, 2) Output: 4 One of the longest sets is set[0], which has length 4: set[0] = {ints[0], ints[5], ints[6], ints[2]} = {5, 6, 2, 0} Example #2: Input: (0, 1, 2) Output: 1
This is conceptually straightforward: Just build the n sets set[i] and see what the longest length is. Should be no more complex than O(n^2) as we're building n sets with a max length of n each.
Robbie Hatley's Perl Solution to The Weekly Challenge 300-2
That's it for challenge 300; see you on challenge 301!
Comments
Post a Comment