Robbie Hatley's Solutions To The Weekly Challenge #228

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

The Weekly Challenge

This week (2023-07-30 through 2023-08-05) is weekly challenge #228.

Task 1 is as follows:

Task 1: Unique Sum
Submitted by: Mohammad S Anwar

You are given an array of integers. Write a script to
find the sum of unique elements in the given array.

Example 1:  Input: @int = (2, 1, 3, 2)  Output: 4
In the given array we have 2 unique elements (1, 3).

Example 2:  Input: @int = (1, 1, 1, 1)  Output: 0
In the given array no unique element found.

Example 3:  Input: @int = (2, 1, 3, 4)  Output: 10
In the given array every element is unique.

To solve this problem, I made a hash of the number of instances of each element in an array, then used "map" to sum-up just those hash keys who's values are exactly 1:

Robbie Hatley's Solution to The Weekly Challenge 228-1

Task 2 is as follows:

Task 2: Empty Array
Submitted by: Mohammad S Anwar

You are given an array of integers in which all elements
are unique. Write a script to perform the following
operations until the array is empty, and return the total
count of operations: If the first element is the smallest
then remove it otherwise move it to the end.

Example 1:  Input: @int = (3, 4, 2)  Output: 5
Operation 1: move 3 to the end: (4, 2, 3)
Operation 2: move 4 to the end: (2, 3, 4)
Operation 3: remove element 2: (3, 4)
Operation 4: remove element 3: (4)
Operation 5: remove element 4: ()

Example 2:  Input: @int = (1, 2, 3)  Output: 3
Operation 1: remove element 1: (2, 3)
Operation 2: remove element 2: (3)
Operation 3: remove element 3: ()

For a change, task 2 was actually easier than task 1 this time. I use List::Util::min, shift, and push, and increment a counter:

Robbie Hatley's Solution to The Weekly Challenge 228-2

That's it for 228; see you on 229!

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