DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 101

Challenge 101
My solutions

TASK #1 › Pack a Spiral

The task

You are given an array @A of items (integers say, but they can be anything).

Your task is to pack that array into an MxN matrix spirally counterclockwise, as tightly as possible. Tightly means the absolute value |M-N| of the difference has to be as small as possible.

My solution

This challenge is kinda of the reverse of task 2 from challenge 88. In that task we were given a spiral and had to unwind it.

This task can be broken up into three steps:

  1. Work out the tightest grid.
    • Work with $y from 1 to one less than the array size.
    • If the array size can be evenly divided by $y and it is tighter than the current grid size, update $max_x and $max_y.
  2. Populate the grid
    • Create a @direction array with the x/y offsets for right, up, left and down.
    • Create a loop from 0 to $#values.
    • Put that value in the given location.
    • If the next x/y value is either out of bounds or that position already has a value, change directions.
  3. Display the grid
    • Since 0,0 represents the bottom left, we use the reverse function on the @grid array.
    • I use sprintf to right justify numbers and left justify strings. This ensure that even if the lengths of the values are different, they will be correctly aligned.


» ./ 1 2 3 4 5 6
6 5 4
1 2 3

» ./ 1 2 3 4 5 6 7 8 9 10 11 12
 9  8  7  6
10 11 12  5
 1  2  3  4

» ./ the quick brown fox jumps over the lazy dog
the   over  jumps
lazy  dog   fox  
the   quick brown
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Origin-containing Triangle

The task

You are given three points in the plane, as a list of six co-ordinates: A=(x1,y1), B=(x2,y2) and C=(x3,y3).

Write a script to find out if the triangle formed by the given three co-ordinates contain origin (0,0).

Print 1 if found otherwise 0.

My solution

I have debated whether I should submit a solution to this task. I am, but with a massive caveat. My high school algebra was more than 25 years ago, and the solution is not my own workings. I've taken the first solution from this website, and convert it to Perl.


» ./ "A=(0,1), B=(1,0) and C=(2,2)"

» ./ "A=(1,1), B=(-1,1) and C=(0,-3)"

» ./ "A=(0,1), B=(2,0) and C=(-6,0)"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)