Peter
Peter Campbell Smith

Smallest index, largest element

Weekly challenge 250 — 1 January 2024

Week 250: 1 Jan 2024

Task 2

Task — Alphanumeric string value

You are given an array of alphanumeric strings. Write a script to return the maximum value of alphanumeric string in the given array. The value of an alphanumeric string can be defined as

a) The numeric representation of the string in base 10 if it is made up of digits only,
b) otherwise the length of the string.

Examples


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

"perl" consists of letters only so the value is 4.
"2" is digits only so the value is 2.
"000" is digits only so the value is 0.
"python" consits of letters so the value is 6.
"r4ku" consists of letters and digits so the value is 4.

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

Analysis

Again, it seems that the sensible thing to do is to iterate along the array, calculating $value = $s =~ m|^(\d+)$| ? $1 + 0 : length($s) and looking for the maximum. The + 0 is there to tidy up elements like '0001'.

Try it 

Try running the script with any input:



example: the, green, grass, grows, here, 23

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2024-01-01
use utf8;     # Week 250 task 2 - Alphanumeric string value
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

alpha_string_value('perl', '2', '000', 'python', 'r4ku');
alpha_string_value('001', '1', '000', '0001');
alpha_string_value('3', 'blind', 'mice', 'and', '10', 'green', 'bottles');

sub alpha_string_value {
    
    my (@a, $max, $s, $value);

    @a = @_;
    
    # loop over array elements and apply the stated rule
    $max = -1;
    for $s (@a) {
        $value = $s =~ m|^(\d+)$| ? $1 + 0 : length($s);
        $max = $value if $value > $max;
    }
    
    say qq[\nInput:  \@alphanumstr = ('] . join(q[', '], @a) . qq[')\nOutput: ] . $max;
}

Output


Input:  @alphanumstr = ('perl', '2', '000', 'python', 'r4ku')
Output: 6

Input:  @alphanumstr = ('001', '1', '000', '0001')
Output: 1

Input:  @alphanumstr = ('3', 'blind', 'mice', 'and', '10', 'green', 'bottles')
Output: 10


 

Any content of this website which has been created by Peter Campbell Smith is in the public domain