Robbie Hatley's Solutions To The Weekly Challenge #262

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

This week (2024-03-247 through 2024-03-30) is weekly challenge #262. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 262-1: Max Positive Negative
Submitted by: Mohammad Sajid Anwar
You are given an array of integers, @ints. Write a script to
return the maximum number of either positive or negative
integers in the given array.

Example 1:
Input: @ints = (-3, 1, 2, -1, 3, -2, 4)
Output: 4
Count of positive integers: 4
Count of negative integers: 3
Maximum of count of positive and negative integers: 4

Example 2:
Input: @ints = (-1, -2, -3, 1)
Output: 3
Count of positive integers: 1
Count of negative integers: 3
Maximum of count of positive and negative integers: 3

Example 3:
Input: @ints = (1,2)
Output: 2
Count of positive integers: 2
Count of negative integers: 0
Maximum of count of positive and negative integers: 2

I'll use "grep" to get lists of all positive and negative numbers, "scalar" to get the sizes of those lists, then return the negative count if it's the larger, else return the positive count.

   use v5.36;
   sub max_pos_neg (@a) {
      my $pos = scalar grep {$_ > 0} @a;
      my $neg = scalar grep {$_ < 0} @a;
      if ($neg > $pos) {return $neg} else {return $pos}
   }

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 262-2: Count Equal Divisible
Submitted by: Mohammad Sajid Anwar
You are given an array of integers, @ints, and an integer $k.
Write a script to return the number of pairs (i, j) where
a) 0 <= i < j < size of @ints
b) ints[i] == ints[j]
c) i x j is divisible by k

Example 1
Input: @ints = (3,1,2,2,2,1,3) and $k = 2
Output: 4
(0, 6) => ints[0] == ints[6] and 0 x 6 is divisible by 2
(2, 3) => ints[2] == ints[3] and 2 x 3 is divisible by 2
(2, 4) => ints[2] == ints[4] and 2 x 4 is divisible by 2
(3, 4) => ints[3] == ints[4] and 3 x 4 is divisible by 2

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

Requirement (a) is easily implementable with a pair of nested 3-part loops. Requirement (b) is just an integer equality check, implementable with "==". Requirement (c) can be implemented as "0==(i*j)%k".

   use v5.36;
   sub count_eq_div ($k, @a) {
      my $c = 0;
      for    (my $i =    0   ; $i <= $#a-1 ; ++$i) {
         for (my $j = $i + 1 ; $j <= $#a-0 ; ++$j) {
            if ($a[$i]==$a[$j] && 0==($i*$j)%$k) {++$c}
         }
      }
      return $c;
   }

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

That's it for challenge 262; see you on challenge 263!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #221

Robbie Hatley's Solutions To The Weekly Challenge #239