Robbie Hatley's Solutions To The Weekly Challenge #283

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-08-18 through 2024-08-24 is #283. Its tasks are as follows:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 283-1: Unique Number
Submitted by: Mohammad Sajid Anwar
You are given an array of integers, @ints, where every element appears
more than once except one element. Write a script to find the one
element that appears exactly one time.

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

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

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

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

I use the function "singleton" from CPAN module "List::SomeUtils" to find any singleton elements in the given array.

   foreach my $aref (@arrays) {
      say '';
      my @singles = singleton @$aref;
      say "Number Array     = (@$aref)";
      say "Unique Number(s) = @singles";
   }

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

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task 283-2: Digit Count Value
Submitted by: Mohammad Sajid Anwar
You are given an array of positive integers, @ints. Write a script to
return true if for every index i in the range 0 <= i < size of
array, the digit i occurs exactly the $ints[$i] times in the given
array otherwise return false.

Example 1:
Input: @ints = (1, 2, 1, 0)
Ouput: true
$ints[0] = 1, the digit 0 occurs exactly 1 time.
$ints[1] = 2, the digit 1 occurs exactly 2 times.
$ints[2] = 1, the digit 2 occurs exactly 1 time.
$ints[3] = 0, the digit 3 occurs 0 time.

Example 2:
Input: @ints = (0, 3, 0)
Ouput: false
$ints[0] = 0, the digit 0 occurs 2 times rather than 0 time.
$ints[1] = 3, the digit 1 occurs 0 time rather than 3 times.
$ints[2] = 0, the digit 2 occurs exactly 0 time.

I make a hash of digit counts, then compare the number of occurrences of each index to the array value at that index.

   my %digit_count = map {$_ => 0} 0..$#$aref;
   for my $number (@$aref) {
      for my $digit (split '', $number) {
         ++$digit_count{$digit};
      }
   }
   my $truth = 1;
   for my $index (0..$#$aref) {
      if ($digit_count{$index} != $$aref[$index]) {
         $truth = 0;
         last;
      }
   }

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

That's it for challenge 283; see you on challenge 284!

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