oldtechaa

Posted on

# Perl Weekly Challenge #217 - Flattening the Matrix

This week we have a very simple challenge! Again due to time, I just did the first challenge this week, but I have an idea of how I'd solve the second and I'll compare with the way others implemented it.

Anyway, to the challenge. The goal is to find the 3rd smallest element of a matrix. The simplest way is simply to flatten, sort, and pick the element. There might be absolutely more performant ways to do it, such as scanning the entire matrix once and keeping a list of the lowest three as you iterate, but this is a case where I feel that it's simply not worth it. One pass to flatten and one sort isn't worth all the extra implementation complexity. I do look forward to seeing any solutions including that technique though.

Here's my code:

``````my @matrix1 = ([3, 1, 2], [5, 2, 4], [0, 1, 3]);
my @list1;

foreach (@matrix1) {map {push @list1, \$_} @{\$_}}
@list1 = sort @list1;
say \$list1[2];
``````

Repeated for each input dataset.

So the easy simple way to do this is just to use map to flatten the array onto @list1, then sort it in place and pick the third element. That simple. Essentially 3 lines for the majority of the task.

As I said, I look forward to seeing the other solutions for these challenges, and I'll hopefully see you next week!