The weekly challenge 305 - Task 2: Alien Dictionary
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-305/#TASK2 3 # 4 # Task 2: Alien Dictionary 5 # ======================== 6 # 7 # You are given a list of words and alien dictionary character order. 8 # 9 # Write a script to sort lexicographically the given list of words based on the 10 # alien dictionary characters. 11 # 12 ## Example 1 13 ## 14 ## Input: @words = ("perl", "python", "raku") 15 ## @alien = qw/h l a b y d e f g i r k m n o p q j s t u v w x c z/ 16 ## Output: ("raku", "python", "perl") 17 # 18 ## Example 2 19 ## 20 ## Input: @words = ("the", "weekly", "challenge") 21 ## @alien = qw/c o r l d a b t e f g h i j k m n p q s w u v x y z/ 22 ## Output: ("challenge", "the", "weekly") 23 # 24 ############################################################ 25 ## 26 ## discussion 27 ## 28 ############################################################ 29 # 30 # We transliterate all words to their conjugate word in the transliterated 31 # namespace, then we can sort alphabetically. The we transliterate the sorted 32 # words back to the original words. 33 34 use strict; 35 use warnings; 36 37 alien_dictionary( ["perl", "python", "raku"], qw/h l a b y d e f g i r k m n o p q j s t u v w x c z/ ); 38 alien_dictionary( ["the", "weekly", "challenge"], qw/c o r l d a b t e f g h i j k m n p q s w u v x y z/ ); 39 40 sub alien_dictionary { 41 my ($words, @alien) = @_; 42 print "Input: (" . join(", ", @$words) . ")\n"; 43 print " qw/" . join(" ", @alien) . "/\n"; 44 my $alien = join("",@alien); 45 my @tmp = (); 46 foreach my $w (@$words) { 47 eval "\$w =~ tr/a-z/$alien/;"; 48 push @tmp, $w; 49 } 50 my @sorted = sort @tmp; 51 @tmp = (); 52 foreach my $w (@sorted) { 53 eval "\$w =~ tr /$alien/a-z/;"; 54 push @tmp, $w; 55 } 56 print "Output: (" . join(", ", @tmp) . ")\n"; 57 }