The weekly challenge 215 - Task 1 - Keeping the order
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-215/#TASK1 3 # 4 # Task 1: Odd one Out 5 # =================== 6 # 7 # You are given a list of words (alphabetic characters only) of same size. 8 # 9 # Write a script to remove all words not sorted alphabetically and print the 10 # number of words in the list that are not alphabetically sorted. 11 # 12 ## Example 1 13 ## 14 ## Input: @words = ('abc', 'xyz', 'tsu') 15 ## Output: 1 16 ## 17 ## The words 'abc' and 'xyz' are sorted and can't be removed. 18 ## The word 'tsu' is not sorted and hence can be removed. 19 # 20 ## Example 2 21 ## 22 ## Input: @words = ('rat', 'cab', 'dad') 23 ## Output: 3 24 ## 25 ## None of the words in the given list are sorted. 26 ## Therefore all three needs to be removed. 27 # 28 ## Example 3 29 ## 30 ## Input: @words = ('x', 'y', 'z') 31 ## Output: 0 32 # 33 ############################################################ 34 ## 35 ## discussion 36 ## 37 ############################################################ 38 # 39 # We look at each word in the list. If it's sorted, we keep it. 40 # At the end, the amount of removed words is the difference 41 # in length of the original list and the "keep" list. 42 43 use strict; 44 use warnings; 45 46 odd_one_out('abc', 'xyz', 'tsu'); 47 odd_one_out('rat', 'cab', 'dad'); 48 odd_one_out('x', 'y', 'z'); 49 50 sub odd_one_out { 51 my @words = @_; 52 print "Input: (" . join(",", @words) . ")\n"; 53 my @keep = (); 54 foreach my $word (@words) { 55 push @keep, $word if is_sorted($word); 56 } 57 my $removed = scalar(@words) - scalar(@keep); 58 print "Output: $removed\n"; 59 } 60 61 # a word is sorted if it is the same after sorting 62 # all of its characters, so we split each word into 63 # its characters, sort them, and join them back into 64 # a word again 65 sub is_sorted { 66 my $word = shift; 67 my $sorted_word = join("", sort(split //, $word)); 68 return $word eq $sorted_word; 69 } 70