Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #333 (“Straight Line” and “Duplicate Zeros”)

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, with a new pair of tasks each Monday. You can find it here:

The Weekly Challenge

The Weekly Challenge for the week of 2025-08-04 through 2025-08-10 is #333

The tasks for challenge #333 are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 333-1: Straight Line
Submitted by: Mohammad Sajid Anwar
You are given a list of co-ordinates. Write a script to find out
if the given points make a straight line.

Example 1
Input: @list = ([2, 1], [2, 3], [2, 5])
Output: true

Example 2
Input: @list = ([1, 4], [3, 4], [10, 4])
Output: true

Example 3
Input: @list = ([0, 0], [1, 1], [2, 3])
Output: false

Example 4
Input: @list = ([1, 1], [1, 1], [1, 1])
Output: true

Example 5
Input: @list = ([1000000, 1000000],
                [2000000, 2000000],
                [3000000, 3000000])
Output: true

I'll consider points A, B, C to be collinear if-and-only-if one of the following three things is true:

  1. Two-or-more of the points are less than one billionth apart.
  2. The slopes of all three sides of △ABC are all infinite (indicated by POSIX "Inf").
  3. The slopes of all three sides of △ABC are less than one billionth apart.

Robbie Hatley's Perl Solution to The Weekly Challenge 333-1

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 333-2: Duplicate Zeros
Submitted by: Mohammad Sajid Anwar
You are given an array of integers. Write a script to duplicate
each occurrence of zero, shifting the remaining elements to the
right. The elements beyond the length of the original array are
not written.

Example 1
Input: @ints = (1, 0, 2, 3, 0, 4, 5, 0)
Output: (1, 0, 0, 2, 3, 0, 0, 4)
Each zero is duplicated.
Elements beyond the original length (like 5 and last 0) are
discarded.

Example 2
Input: @ints = (1, 2, 3)
Output: (1, 2, 3)
No zeros exist, so the array remains unchanged.

Example 3
Input: @ints = (1, 2, 3, 0)
Output: (1, 2, 3, 0)

Example 4
Input: @ints = (0, 0, 1, 2)
Output: (0, 0, 0, 0)

Example 5
Input: @ints = (1, 2, 0, 3, 4)
Output: (1, 2, 0, 0, 3)

To solve this problem, I'll first make an empty new array, then for every element of the original array, if it's 0 push two 0s to new array, else push original element to new array, then return a slice of the new array from index 0 to the highest valid index of the original array.

Robbie Hatley's Perl Solution to The Weekly Challenge 333-2

That's it for challenge 333; see you on challenge 334!

Comments

Popular posts from this blog

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #326 (“Day of Year” and “Decompressed List”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #317 (Theme: “Friendly Acronyms”)

Robbie Hatley's Solutions, in Perl, for The Weekly Challenge #319 (“Word Count” and “Minimum Common”)