Robbie Hatley's Solutions To The Weekly Challenge #268

For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:

The Weekly Challenge

The Weekly Challenge for the week of 2024-05-05 through 2024-05-11 is #268. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 268-1: Magic Number
Submitted by: Mohammad Sajid Anwar
You are given two arrays of integers of same size, @x and @y.
Write a script to find the magic number which when added to each
element of the first array gives the second array. Element
order is not important.

Example 1:
Input: @x = (3, 7, 5)
       @y = (9, 5, 7)
Output: 2
The magic number is 2.
@x = (3, 7, 5)
   +  2  2  2
@y = (5, 9, 7)

Example 2:
Input: @x = (1, 2, 1)
       @y = (5, 4, 4)
Output: 3
The magic number is 3.
@x = (1, 2, 1)
   +  3  3  3
@y = (5, 4, 4)

Example 3:
Input: @x = (2)
       @y = (5)
Output: 3

I'll sort both arrays then subtract the second from the first. If all elements of the difference are the same, that common value is our "magic number", otherwise return "none":

   sub magic ($matref) {
      my @row1 = sort {$a<=>$b} @{$$matref[0]};
      my @row2 = sort {$a<=>$b} @{$$matref[1]};
      my @diff = map {$$_[1]-$$_[0]} zip6 @row1, @row2;
      all {$diff[0] == $_} @diff and return $diff[0]
      or return 'none';
   }

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 268-2: Number Game
Submitted by: Mohammad Sajid Anwar
You are given an array of integers, @ints, with even number of
elements. Write a script to create a new array made up of
elements of the given array. Pick the two smallest integers and
add it to new array in decreasing order i.e. high to low. Keep
doing until the given array is empty.

Example 1
Input: @ints = (2, 5, 3, 4)
Output: (3, 2, 5, 4)
Round 1: we picked (2, 3) and push it to the new array (3, 2)
Round 2: we picked the remaining (4, 5) and push it to the new
array (5, 4)

Example 2
Input: @ints = (9, 4, 1, 3, 6, 4, 6, 1)
Output: (1, 1, 4, 3, 6, 4, 9, 6)

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

This is equivalent to first sorting each array in increasing numeric order ("sort {$a<=>$b} @array"), then swapping pairs. Something like this:

   sub stairway (@array) {
      my @zigzag = sort {$a<=>$b} @array;
      for ( my $i = 0 ; $i <= $#zigzag - 1 ; $i += 2 ) {
         my $temp = $zigzag[$i];
         $zigzag[$i] = $zigzag[$i+1];
         $zigzag[$i+1] = $temp;
      }
      return @zigzag;
   }

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

That's it for challenge 268; see you on challenge 269!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #266

Robbie Hatley's Solutions To The Weekly Challenge #273