Robbie Hatley's Solutions To The Weekly Challenge #250

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 (2023-12-31 through 2024-01-06) is weekly challenge #250. Its tasks are as follows:

Task 250-1: Smallest Index
Submitted by: Mohammad S Anwar
Given an array of integers @ints, write a script to find the
smallest index i such that i mod 10 == $ints[i]; otherwise,
return -1.

Example 1:
Input: @ints = (0, 1, 2)
Output: 0
i=0: 0 mod 10 = 0 == $ints[0].
i=1: 1 mod 10 = 1 == $ints[1].
i=2: 2 mod 10 = 2 == $ints[2].
All indices have i mod 10 == $ints[i], so we return
the smallest index, 0.

Example 2:
Input: @ints = (4, 3, 2, 1)
Output: 2
i=0: 0 mod 10 = 0 != $ints[0].
i=1: 1 mod 10 = 1 != $ints[1].
i=2: 2 mod 10 = 2 == $ints[2].
i=3: 3 mod 10 = 3 != $ints[3].
2 is the only index which has i mod 10 == $ints[i].

Example 3:
Input: @ints = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
Output: -1
No index satisfies i mod 10 == $ints[i].

To solve this problem, I'll use a 3-part loop on array index variable $i, starting from 0 and working upward, and report the first (and hence least) index found for which $i%10 == $ints[$i]:

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

Task 250-2: Alphanumeric String Value
Submitted by: Mohammad S Anwar
Given an array of alphanumeric strings, write a script to return
the maximum "alphanumeric string value" in the given array, where
"alphanumeric string value" is defined as:
a) If string contains digits only: The base-10 numeric value.
b) Otherwise: The length of the string.

Example 1:
Input:  ("perl", "2", "000", "python", "r4ku")
Output: 6

Example 2:
Input:  ("001", "1", "000", "0001")
Output: 1

To solve this, I'll make these subs: 1. "sub is_array_of_alnums ($aref)"
2. "sub alnum_string_value ($x)"
3. "sub max_value ($aref)"
My main loop will first check each array to make sure it's an array of alnums, then feed each array to sub max_value and report the max value. sub max_value($aref) will work by applying "min" from List::Util to a map which applies alnum_string_value($_) to each $_ in @$aref:

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

That's it for challenge 250; see you on challenge 251! Happy New Year!

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