The weekly challenge 283 - Task 2: Digit Count Value
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-283/#TASK2 3 # 4 # Task 2: Digit Count Value 5 # ========================= 6 # 7 # You are given an array of positive integers, @ints. 8 # 9 # Write a script to return true if for every index i in the range 0 <= i < size 10 # of array, the digit i occurs exactly the $ints[$i] times in the given array 11 # otherwise return false. 12 # 13 ## Example 1 14 ## 15 ## Input: @ints = (1, 2, 1, 0) 16 ## Ouput: true 17 ## 18 ## $ints[0] = 1, the digit 0 occurs exactly 1 time. 19 ## $ints[1] = 2, the digit 1 occurs exactly 2 times. 20 ## $ints[2] = 1, the digit 2 occurs exactly 1 time. 21 ## $ints[3] = 0, the digit 3 occurs 0 time. 22 # 23 ## Example 2 24 ## 25 ## Input: @ints = (0, 3, 0) 26 ## Ouput: false 27 ## 28 ## $ints[0] = 0, the digit 0 occurs 2 times rather than 0 time. 29 ## $ints[1] = 3, the digit 1 occurs 0 time rather than 3 times. 30 ## $ints[2] = 0, the digit 2 occurs exactly 0 time. 31 # 32 ############################################################ 33 ## 34 ## discussion 35 ## 36 ############################################################ 37 # 38 # This requires two passes: 39 # 1. count the digits 40 # 2. for each index of the array, check whether the digit count value 41 # for this index matches the value in the array. 42 43 use strict; 44 use warnings; 45 46 digit_count_value(1, 2, 1, 0); 47 digit_count_value(0, 3, 0); 48 49 sub digit_count_value { 50 my @ints = @_; 51 my $digits_counts = {}; 52 print "Input: (" . join(", ", @ints) . ")\n"; 53 foreach my $digit (@ints) { 54 $digits_counts->{$digit}++; 55 } 56 foreach my $i (0..$#ints) { 57 $digits_counts->{$i} //= 0; 58 return print "Output: false\n" unless $digits_counts->{$i} == $ints[$i]; 59 } 60 return print "Output: true\n"; 61 }