The weekly challenge 260 - Task 1: Unique Occurrences
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-260/#TASK1 3 # 4 # Task 1: Unique Occurrences 5 # ========================== 6 # 7 # You are given an array of integers, @ints. 8 # 9 # Write a script to return 1 if the number of occurrences of each value in the 10 # given array is unique or 0 otherwise. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (1,2,2,1,1,3) 15 ## Output: 1 16 ## 17 ## The number 1 occurred 3 times. 18 ## The number 2 occurred 2 times. 19 ## The number 3 occurred 1 time. 20 ## 21 ## All occurrences are unique, therefore the output is 1. 22 # 23 ## Example 2 24 ## 25 ## Input: @ints = (1,2,3) 26 ## Output: 0 27 # 28 ## Example 3 29 ## 30 ## Input: @ints = (-2,0,1,-2,1,1,0,1,-2,9) 31 ## Output: 1 32 # 33 ############################################################ 34 ## 35 ## discussion 36 ## 37 ############################################################ 38 # 39 # First, we calculate how often each value occurs in @ints and 40 # store that information in a $map. Then we check if all values 41 # in $map are unique: if we find one that isn't, we can set 42 # $unique to 0. 43 44 use strict; 45 use warnings; 46 use Data::Dumper; 47 48 unique_occurrences(1,2,2,1,1,3); 49 unique_occurrences(1,2,3); 50 unique_occurrences(-2,0,1,-2,1,1,0,1,-2,9); 51 52 sub unique_occurrences { 53 my @ints = @_; 54 print "Input: (" . join(", ", @ints) . ")\n"; 55 my $map = {}; 56 map { $map->{$_}++ } @ints; 57 my $seen = {}; 58 my $unique = 1; 59 foreach my $key (keys %$map) { 60 if($seen->{$map->{$key}}) { 61 $unique = 0; 62 } 63 $seen->{$map->{$key}}++; 64 } 65 print "Output: $unique\n"; 66 }