Advent Calendar 2023
| Day 11 | Day 12 | Day 13 |
The gift is presented by Simon Green. Today he is talking about his solution to The Weekly Challenge - 220. This is re-produced for Advent Calendar 2023 from the original post.
Common Squares
Weekly Challenge 220
This is the second consecutive week I’ve done the task and written the blog 40,000+ feet in the air.
Task 1: Common Characters
You are given a list of words.
Write a script to return the list of common characters (sorted alphabetically) found in every word of the given list.
My solution
These are the steps I took.
-
From a list (array in
Perl) ofwords, I create a list calledset_list. Each item is aset(hashinPerl) of the lower case letters that occur in each word. InPythonthis is achieved using set(word) as strings are an iterable. InPerlI have a function calledword_to_hashas it seemed like a bit too much to stuff into a singlemapstatement. -
I take off the first word from the
set_listand assign it to thefirst_wordvariable. -
I loop through each letter in the first word alphabetically.
-
I check that the letter is indeed a letter from the English alphabet and that it appears in all the words in the
set_listlist. If it is, I append it to theletterslist. -
Finally, I print items in the letters list.
Examples
$ ./ch-1.py Perl Raku Rust
r
$ ./ch-1.py love live leave
e, l, v
Task 2: Squareful
You are given an array of integers, @ints.
An array is squareful if the sum of every pair of adjacent elements is a perfect square.
Write a script to find all the permutations of the given array that are squareful.
My solution
Rather than reinventing some perfectly good wheels, I use the permutation function from Python's itertools and Perl's Algorithm::Combinatorics to work through all possible permutations. If we already have a solution with these numbers (e.g. a duplicate number), we skip to the next permutation.
I then have an inner loop from 1 to one less than the number of integers we have. I check that the value at that position and the previous position makes up a perfect square. This is done by calculating the square root of the sum of the two numbers, and checking it is equals to an integer.
Examples
$ ./ch-2.py 1 17 8
(1, 8, 17), (17, 8, 1)
$ ./ch-2.py 2 2 2
(2, 2, 2)
If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.