The weekly challenge 228 - Task 1: Unique Sum

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-228/#TASK1
 3 #
 4 # Task 1: Unique Sum
 5 # ==================
 6 #
 7 # You are given an array of integers.
 8 #
 9 # Write a script to find out the sum of unique elements in the given array.
10 #
11 ## Example 1
12 ##
13 ## Input: @int = (2, 1, 3, 2)
14 ## Output: 4
15 ##
16 ## In the given array we have 2 unique elements (1, 3).
17 #
18 ## Example 2
19 ##
20 ## Input: @int = (1, 1, 1, 1)
21 ## Output: 0
22 ##
23 ## In the given array no unique element found.
24 #
25 ## Example 3
26 ##
27 ## Input: @int = (2, 1, 3, 4)
28 ## Output: 10
29 ##
30 ## In the given array every element is unique.
31 #
32 ############################################################
33 ##
34 ## discussion
35 ##
36 ############################################################
37 #
38 # For each Element in the array, count the number of occurences.
39 # Sum up the numbers where this number is 1.
40 
41 use strict;
42 use warnings;
43 
44 unique_sum(2, 1, 3, 2);
45 unique_sum(1, 1, 1, 1);
46 unique_sum(2, 1, 3, 4);
47 
48 sub unique_sum {
49    my @int = @_;
50    print "Input: (" . join(", ", @int) . ")\n";
51    my $count;
52    # count the number of occurences for each element in the array
53    map { $count->{$_}++; } @int;
54    my $sum = 0;
55    # sum up the ones that occured exacty once
56    foreach my $key (keys %$count) {
57       $sum += $key if $count->{$key} == 1;
58    }
59    print "Output: $sum\n";
60 }