The Weekly Challenge 353

Word Counting & Coupon Validation!

Original Challenge Link

Task 1: Max Words

"Word Counter: Finding the Longest Sentence!"

This week's first task involves finding the maximum number of words in any sentence from a given array of sentences. Given an array of sentences, we need to return the maximum number of words that appear in a single sentence. Words are separated by whitespace, and an empty sentence has 0 words.

The Strategy: We iterate through each sentence, split it by whitespace to count the words, and track the maximum count. We use a simple loop to process each sentence and update the maximum when we find a sentence with more words.
Perl Implementation
sub max_words ($sentences) {
    ($sentences) = $SENTENCES_CHECK->($sentences);
    my $best = 0;

    for my $sentence (@$sentences) {
        my @words = grep { length $_ } split /\s+/, $sentence;
        my $count = scalar @words;
        $best = $count if $count > $best;
    }

    return $best;
}
Python Implementation
def max_words(sentences: Sequence[str]) -> int:
    """
    Return the maximum number of whitespace-separated words in any sentence.
    An empty sentence counts as having 0 words.
    """
    best = 0
    for sentence in sentences:
        count = len(sentence.split())
        if count > best:
            best = count
    return best

Task 2: Validate Coupon

"Coupon Inspector: Verifying Discount Codes!"

The second task involves validating coupon codes. Given three arrays (codes, names, and status), we need to validate each entry based on specific rules: the code must be non-empty with only alphanumeric characters and underscores, the name must be one of four allowed categories (electronics, grocery, pharmacy, restaurant), and the status must be true.

The Strategy: We iterate through each index of the three arrays and validate each field. For codes, we use regex to check for alphanumeric and underscore characters. For names, we check against a predefined set of allowed categories. For status, we check if the value is "true" or "1". We combine all three checks to determine validity.
Perl Implementation
sub validate_coupon ($codes, $names, $status) {
    ($codes)  = $CODES_CHECK->($codes);
    ($names)  = $NAMES_CHECK->($names);
    ($status) = $STATUS_CHECK->($status);

    die 'Input arrays must have the same length'
      if @$codes != @$names || @$codes != @$status;

    my @out;
    for my $i ( 0 .. $#$codes ) {
        my $code_ok   = defined $codes->[$i] && $codes->[$i] ne '' && $codes->[$i] =~ /^\w+$/;
        my $name_ok   = defined $names->[$i] && exists $ALLOWED{ $names->[$i] };
        my $status_ok = _status_is_true( $status->[$i] );
        push @out, ( $code_ok && $name_ok && $status_ok ) ? 1 : 0;
    }

    return \@out;
}
Python Implementation
def validate_coupons(
    codes: Sequence[str], names: Sequence[str], status: Sequence[str]
) -> list[bool]:
    """
    Validate coupon entries.

    A coupon is valid iff:
    - codes[i] is non-empty and contains only alphanumeric/underscore characters
    - names[i] is one of the allowed categories
    - status[i] is true
    """
    if not (len(codes) == len(names) == len(status)):
        raise ValueError("Input arrays must have the same length")

    output: list[bool] = []
    for code, name, st in zip(codes, names, status, strict=True):
        code_ok = bool(code) and all(ch.isalnum() or ch == "_" for ch in code)
        name_ok = name in ALLOWED_NAMES
        status_ok = _status_is_true(st)
        output.append(code_ok and name_ok and status_ok)
    return output