Robbie Hatley's Solutions To The Weekly Challenge #226

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-16 through 2023-07-22) is weekly challenge #226.

Task 1 is as follows:

Task 1: Shuffle String
Submitted by: Mohammad S Anwar
You are given a string and an array of indices of same length as string.
Write a script to return the string after re-arranging the indices in 
the correct order.

Example 1:
Input: $string = 'lacelengh', @indices = (3,2,0,5,4,8,6,7,1)
Output: 'challenge'

Example 2:
Input: $string = 'rulepark', @indices = (4,7,3,1,0,5,2,6)
Output: 'perlraku'

This problem is the exact opposite of a Perl "slice", in that it asks not "What would this string look like if rearranged in this order?", but rather, "What original string would look like THIS if rearranged in THIS order?", which is a different question altogether. Fine, I'll start with a string of the same length but consisting only of Unicode "invalid character" characters, "�". Then I'll over-write the given indices of that string with the same-position characters of the given "scrambled" string:

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

Task 2 is as follows:

Task 2: Zero Array
Submitted by: Mohammad S Anwar

You are given an array of non-negative integers, @ints. Write a script 
to return the minimum number of operations to make every element equal 
zero. In each operation, you are required to pick a positive number
less than or equal to the smallest element in the array, then subtract 
that from each positive element in
the array.

Example 1:
Input: @ints = (1, 5, 0, 3, 5)
Output: 3
operation 1: pick 1 => (0, 4, 0, 2, 4)
operation 2: pick 2 => (0, 2, 0, 0, 2)
operation 3: pick 2 => (0, 0, 0, 0, 0)

Example 2:
Input: @ints = (0)
Output: 0

Example 3:
Input: @ints = (2, 1, 4, 0, 3)
Output: 4
operation 1: pick 1 => (1, 0, 3, 0, 2)
operation 2: pick 1 => (0, 0, 2, 0, 1)
operation 3: pick 1 => (0, 0, 1, 0, 0)
operation 4: pick 1 => (0, 0, 0, 0, 0)

There is no need to actually do any "operations". All we need to note is that the number of operations required will be equal to the number of unique positive integers present. So I'll use List::Util, do a "uniq sort", and shift the first number if it's 0:

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

That's it for 226; see you on 227!

Comments

Popular posts from this blog

Robbie Hatley's Solutions To The Weekly Challenge #221

Robbie Hatley's Solutions To The Weekly Challenge #239

Robbie Hatley's Solutions To The Weekly Challenge #262