The weekly challenge 224 - Task 1: Special Notes
1 #!/usr/bin/perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-224/#TASK1 3 # 4 # Task 1: Special Notes 5 # ===================== 6 # 7 # You are given two strings, $source and $target. 8 # 9 # Write a script to find out if using the characters (only once) from source, a target string can be created. 10 # 11 ## Example 1 12 ## 13 ## Input: $source = "abc" 14 ## $target = "xyz" 15 ## Output: false 16 # 17 ## Example 2 18 ## 19 ## Input: $source = "scriptinglanguage" 20 ## $target = "perl" 21 ## Output: true 22 # 23 ## Example 3 24 ## 25 ## Input: $source = "aabbcc" 26 ## $target = "abc" 27 ## Output: true 28 # 29 ############################################################ 30 ## 31 ## discussion 32 ## 33 ############################################################ 34 # 35 # We re-use the solution from the weekly challenge 221 task 1: 36 # https://theweeklychallenge.org/blog/perl-weekly-challenge-221/#TASK1 37 # Solution from 38 # http://gott-gehabt.de/800_wer_wir_sind/thomas/Homepage/Computer/perl/theweeklychallenge-221-1.html 39 # This has a function that returns the length of a good string in words - in 40 # our case, "words" is our first input, and the potential good string consists 41 # of our second input string. 42 # The actual solution is therefore trivial. 43 44 use strict; 45 use warnings; 46 use Data::Dumper; 47 48 special_notes("abc", "xyz"); 49 special_notes("scriptinglanguage", "perl"); 50 special_notes("aabbcc", "abc"); 51 52 sub special_notes { 53 my ($source, $target) = @_; 54 print "Input: source: $source, target: $target\n"; 55 if(good_string_result($target, $source)) { 56 print "Output: true\n"; 57 return "true"; 58 } 59 print "Output: false\n"; 60 return "false"; 61 } 62 63 sub good_string_result { 64 my ($word, $chars) = @_; 65 my ($wordmap, $charmap); 66 my $result = 0; 67 map { $wordmap->{$_}++ } split //, $word; 68 map { $charmap->{$_}++ } split //, $chars; 69 foreach my $c (keys %$wordmap) { 70 return 0 unless $charmap->{$c}; 71 return 0 unless $charmap->{$c} >= $wordmap->{$c}; 72 $result += $wordmap->{$c}; 73 } 74 return $result; 75 }