Peter
Peter Campbell Smith

Adopt a chilly ghost

Weekly challenge 215 — 1 May 2023

Week 215 - 1 May 2023

Task 1

Task — Odd one out

You are given a list of words (alphabetic characters only) of same size. Write a script to remove all words not sorted alphabetically and print the number of words in the list that are not alphabetically sorted.

Analysis

Well, this one is easier than last week's task 1.

The test for alphabetical ordering of each word can easily be done like this:
$count ++
   if lc($word) ne join('', sort split('', lc($word)));

This splits the word into an array of single letters, sorts that, joins them together and compares the result with the original word. If they match, then the word was in alphabetical order, and if not, it isn't. Note that I lower-cased both the original and sorted words so that, for example, abC is regarded as being in alphabetical order.

I'm not sure why the task requires the words to be of the same length; my solution copes with words of varying lengths too.

Try it 

Example: here, is, an, example

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-05-01
use utf8;     # Week 215 task 1 - Odd one out
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

odd_one_out('abc', 'xyz', 'tsu');
odd_one_out('rat', 'cab', 'dad');
odd_one_out('x', 'y', 'z');
odd_one_out('hippy', 'afoot', 'in', 'chilly', 'abbey');
odd_one_out('write', 'a', 'script', 'to', 'remove', 'all', 'words', 'not', 'sorted', 'alphabetically');
odd_one_out('abc', 'aBc', 'abC', 'bcA');

sub odd_one_out {
    
    my ($word, $count);
    
    $count = 0;
    for $word (@_) {
        $count ++ if lc($word) ne join('', sort split('', lc($word)));
    }
    say qq[\nInput:  \@words = ('] . join(q[', '], @_) . q[')];
    say qq[Output: $count];
}

Output


Input:  @words = ('abc', 'xyz', 'tsu')
Output: 1

Input:  @words = ('rat', 'cab', 'dad')
Output: 3

Input:  @words = ('x', 'y', 'z')
Output: 0

Input:  @words = ('hippy', 'afoot', 'in', 'chilly', 'abbey')
Output: 0

Input:  @words = ('write', 'a', 'script', 'to', 'remove', 'all', 'words', 'not', 'sorted', 'alphabetically')
Output: 7

Input:  @words = ('abc', 'aBc', 'abC', 'bcA')
Output: 1

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