Robbie Hatley's Solutions To The Weekly Challenge #277

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-07-07 through 2024-07-13 is #277. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 277-1: Count Common
Submitted by: Mohammad Sajid Anwar
Given two arrays of strings,write a script to return the count
of words which appear once-each in the two arrays.

   # Example 1 input:
   [
      ["Perl", "is", "my", "friend"],
      ["Perl", "and", "Raku", "are", "friend"],
   ],
   # Expected output: 2
   # (The words "Perl" and "friend" appear once in each array.)

   # Example 2 input:
   [
      ["Perl", "and", "Python", "are", "very", "similar"],
      ["Python", "is", "top", "in", "guest", "languages"],
   ],
   # Expected output: 1
   # (The word "Python" appears once in each array.)

   # Example 3 input:
   [
      ["Perl", "is", "imperative", "Lisp", "is", "functional"],
      ["Crystal", "is", "similar", "to", "Ruby"],
   ],
   # Expected output: 0
   # ("is" appears twice in the first array so it doesn't count.)

I attack this problem by making a hash keyed by words with each value being a 2-element array containing counts of how many times that word appears in each array. Then I just count how many keys have both elements of the value equal to 1 (which means the word appears one-each in the two arrays of words).

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 277-2: Strong Pair
Submitted by: Mohammad Sajid Anwar
Given an array of integers, write a script to return the count
of all strong pairs in the given array. A pair of integers
x and y is called a "strong pair" if it satisfies theses
inequalities: 0 < |x - y| and |x - y| < min(x, y).

   # Example 1 input:
   [1, 2, 3, 4, 5],
   # Expected output: 4
   # (Strong Pairs: (2, 3), (3, 4), (3, 5), (4, 5).)

   # Example 2 input:
   [5, 7, 1, 7],
   # Expected output: 1
   # (Strong Pairs: (5, 7).)

To prevent considering duplicate pairs, I make sorted, deduped copies of both arrays, then I use nested ranged for loops to consider each unique pair, and I use && to and-together the given inequalities to determine how many pairs are "strong".

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

That's it for challenge 277; see you on challenge 278!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #262

Robbie Hatley's Solutions To The Weekly Challenge #239

Robbie Hatley's Solutions To The Weekly Challenge #266