PWC 166 › K-Directory Diff

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

Task #2 this week is another one of mine. The idea is to take any number of pathnames on the command line (and we must support at least three), and output a side-by-side diff of the files that are different. This is a skin-deep analysis, so there is no recursion, and no comparison of file sizes, modification times, or contents, although those would be worthy additions if someone wants to take it further.

I will be implementing a fairly basic version, although I have a more complex version I’ve been using for years that I might be persuaded to release if there is interest.

Data Design

I am going to have one main data structure, %dirs, that will be built up as we traverse the directories. It will hold all directory and file information, as well as a maxlen value for each directory, for ease of formatting columns later. Here’s what %dirs might look like, given a very simple set of input directories:

%dirs = (
  dir_a =>  {
      files  => {
                "Arial.ttf"       => 1,
                "Comic_Sans.ttf"  => 1,
              },
      maxlen => 14,
  },
  dir_b => {
      files  => {
                "Arial.ttf"       => 1,
                "Comic_Sans.ttf"  => 1,
                "Courier_New.ttf" => 1,
              },
      maxlen => 15,
  },
)
Continue reading “PWC 166 › K-Directory Diff”

PWC 166 › Hexadecimal Words

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

This is another one of my suggested tasks, and another time you’re going to read about a personal story that connects me to a task. For many years, right back to very first days I started hacking filesystems and writing kernel code, I’ve often needed to come up with 16- or 32-bit identifiers for things, usually represented in hexadecimal. And to this day, my repertoire of clever identifiers is more or less limited to 0xdeadbeef and 0xc0dedbad, and a few others. Let’s change that!

The simple version

A very simple solution simply reads the lines, filters out anything that isn’t the right length, or contains characters that can’t be substituted, and prints out the whole works:

use File::Slurper qw< read_lines >;

my $dict = $ARGV[0] // '../../../data/dictionary.txt';

say for map {     y/olist/01157/r    }
       grep { /^[0-9a-folist]{2,8}$/ } read_lines($dict);

That already gives me some great results, like 0xd15abled (“disabled”), and is nice and short. However, we didn’t come here for half measures. This version only returns single words, and doesn’t care how many substitutions it has done, so words like 0x57111e57 (“stillest”‽) are fair game.

Continue reading “PWC 166 › Hexadecimal Words”

PWC 165 › Simple SVG generator

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

The tasks this week are ones I devised. Allow me a moment to explain the motivation behind them.

I often have a need to quickly visualize some random bits of data, and while I’ve gotten great mileage out of terminal output, and things like gnuplot or spreadsheet imports, sometimes better and more convenient results are possible by generating the image myself.

There is ImageMagick (see perlmagick for a Perl interface), but its dependencies are heavy, and getting it to run at all on some systems (particularly the embedded systems I work on), can be challenging. And of course, it only works with raster images, which do not scale well.

Fortunately, it’s very easy to generate vector images with pure Perl (or most any language, for that matter). You can even do it easily without any CPAN modules, but remember, even you can use CPAN!

Enter Scalable Vector Graphics (SVG).

Raster images are comprised of a grid of pixels. Vector images use shapes like circles, lines, and curves. Because these are defined mathematically, vector images can be resized, squished, or rotated with no loss in quality.

Quick Introduction to SVG

For this task, I will be using the SVG module by Morgane Oger and recently maintained by our very own Mohammad Anwar. However, SVG files are simply XML documents, so it would not be much harder to generate the XML yourself. Here’s what SVG source looks like:

Continue reading “PWC 165 › Simple SVG generator”

PWC 164 › Palindromic Primes

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

The first task this week is to list all palindromic primes below 1000. Palindromes are very well known to Weekly Challenge enthusiasts as numbers (or words) that are the same forwards and backwards. Prime numbers should need no introduction.

Prime Sieve

I’m going to jump straight to it. Since the task is simple, I’m not going to use an external library such as Math::Prime::Util, even though that would be quite a bit faster. Instead, I’m going to generate the primes myself, using a Sieve of Eratosthenes. There are faster methods, but you can’t beat Eratosthenes for elegance!

Continue reading “PWC 164 › Palindromic Primes”

PWC 164 › Happy Numbers

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

Task #2 this week comes to us from Robert DiCicco, and Robert demands happiness! Or at least numbers that are happy. Either way, I could use some right about now.

We are to find the first 8 Happy Numbers in base 10. To test whether a number is Happy:

replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.

Those numbers for which this process end in 1 are happy numbers, while those numbers that do not end in 1 are unhappy numbers.

Weekly Challenge #164

If You’re Happy and You Know It return 1

Using the algorithm exactly as described above, the Perl code is straightforward:

Continue reading “PWC 164 › Happy Numbers”

PWC 163 › A tail of two sums

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

This week’s challenges are very quick, so I’m putting them in one blog post. The title is a bit of a play on words, given the tail recursion in part 2.

Full solutions are available at GitHub.

Task 1 › Bitwise Sum

For the first task, we’re asked to first bitwise AND (&) each unique pair of numbers, and then compute the sum of those operations. So, given an input of (a, b, c), we would compute:

a & b + a & c + b & c

To formalize this a bit, in preparation for writing the code, consider a pair (ni, nj) where i and j are the indices in the input array. Unique pairs could be interpreted to mean ji. However, the provided example clearly implies that self pairs are to be avoided, so we’ll include pairs where j > i. So for an array of length k (n1 … nk), this looks like:

\({ \displaystyle \sum \limits_{i=1}^{k} } \sum_{j=i+1}^{k} n_i\ \&\ n_j
\)

Continue reading “PWC 163 › A tail of two sums”

PWC 162 › Wheatstone–Playfair Cipher

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

Challenge #2 this week asks us to implement a version of the Playfair Cipher, which is a simple symmetric key cipher, invented in 1854 by Charles Wheatstone, that was used with pencil and paper. It ended up being called the Playfair Cipher because⁠—as I understand it⁠—the ironically named Lord Playfair promoted its use and basked in the glory.

This cipher was used by the Brits up to and including the First World War, to encrypt messages sent via telegraph. Without the key, messages can be decrypted eventually (and it’s easier, the longer the ciphertext, as it is vulnerable to frequency analysis), but the British knew that by the time the enemy decoded the message, the information would no longer be relevant.

Continue reading “PWC 162 › Wheatstone–Playfair Cipher”

PWC 162 › ISBN-13

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

This week‘s first task is simple: validate ISBN-13 codes.

ISBNs have been around for a long time and come in many different flavours. ISBN-13 is a thirteen-digit code consisting of twelve digits plus a check digit. The checksum calculation is simple. Given the digits x1, x2, …, x12, and the check digit, x13:

(10 – (x1 + 3x2 + x3 + 3x4 + … + x11 + 3x12 + x13)) ≡ 0 (mod 10)

To make calculation a little easier, we can move the check digit (x13) out of the sum and compare it at the end. For example, given the code 978-0-306-40615-7, we can calculate:

10 – (9 + 3×7 + 8 + 3×0 + 3 + 3×0 + 6 + 3×4 + 0 + 3×6 + 1 + 3×5) % 10) = 7

Using List::Util‘s pairmap function, we can simplify the calculation significantly:

Continue reading “PWC 162 › ISBN-13”

PWC 161 › Pangrams

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

For this week’s second challenge, the task is to generate a pangram.

A pangram is simply a collection of words that contain every letter in the alphabet (English, in this case). A classic pangram example is:

the quick brown fox jumped over the lazy dog

Wikipedia

Continue reading “PWC 161 › Pangrams”

PWC 161 › Abecedarian Words

This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)

I know, it’s been a long time!

This week, I’m back. I submitted the challenges for this week, so I thought it’s only fair that I give them a go myself. Unfortunately, I realized too late that this Abecedarian Words is essentially the same as Week 111’s “Ordered Letters” submitted by the venerable E. Choroba. I thought we hadn’t done it. Nuts. I’m sorry.

Challenge Description

An abecedarian word is a word whose letters are arranged in alphabetical order. For example, “knotty” is an abecedarian word, but “knots” is not. Output or return a list of all abecedarian words in the dictionary, sorted in decreasing order of length.

From: PWC Challenge #161
Continue reading “PWC 161 › Abecedarian Words”