The weekly challenge 265 - Task 1: 33% Appearance
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-265/#TASK1 3 # 4 # Task 1: 33% Appearance 5 # ====================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to find an integer in the given array that appeared 33% or 10 # more. If more than one found, return the smallest. If none found then return 11 # undef. 12 # 13 ## Example 1 14 ## 15 ## Input: @ints = (1,2,3,3,3,3,4,2) 16 ## Output: 3 17 ## 18 ## 1 appeared 1 times. 19 ## 2 appeared 2 times. 20 ## 3 appeared 4 times. 21 ## 22 ## 3 appeared 50% (>33%) in the given array. 23 # 24 ## Example 2 25 ## 26 ## Input: @ints = (1,1) 27 ## Output: 1 28 ## 29 ## 1 appeared 2 times. 30 ## 31 ## 1 appeared 100% (>33%) in the given array. 32 # 33 ## Example 3 34 ## 35 ## Input: @ints = (1,2,3) 36 ## Output: 1 37 ## 38 ## 1 appeared 1 times. 39 ## 2 appeared 1 times. 40 ## 3 appeared 1 times. 41 ## 42 ## Since all three appeared 33.3% (>33%) in the given array. 43 ## We pick the smallest of all. 44 # 45 ############################################################ 46 ## 47 ## discussion 48 ## 49 ############################################################ 50 # 51 # For each element in the array, count the number of occurences. 52 # Then, we can start with the smallest of those numbers and check 53 # whether or not it has more than 33% appearances. If yes we are 54 # finished and return the found number, otherwise we continue. 55 # If we're at the end and didn't find any number that appeared 56 # at least 33% of the time we can return undef. 57 58 use strict; 59 use warnings; 60 61 thirty_three_appearance(1,2,3,3,3,3,4,2); 62 thirty_three_appearance(1,1); 63 thirty_three_appearance(1,2,3); 64 thirty_three_appearance(1,2,3,4); 65 66 sub thirty_three_appearance { 67 my @ints = @_; 68 my $found = {}; 69 my $count = scalar(@ints); 70 my $limit = 33/100; 71 my $appeared = undef; 72 print "Input: (" . join(", ", @ints) . ")\n"; 73 foreach my $i (@ints) { 74 $found->{$i}++; 75 } 76 foreach my $j (sort {$a<=>$b} keys %$found) { 77 if(($found->{$j}/$count) >= $limit) { 78 $appeared = $j; 79 last; 80 } 81 } 82 if(defined($appeared)) { 83 print "Output: $appeared\n"; 84 } else { 85 print "Output: undef\n"; 86 } 87 }