The weekly challenge 283 - Task 1: Unique Number

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-283/#TASK1
 3 #
 4 # Task 1: Unique Number
 5 # =====================
 6 #
 7 # You are given an array of integers, @ints, where every elements appears more
 8 # than once except one element.
 9 #
10 # Write a script to find the one element that appears exactly one time.
11 #
12 ## Example 1
13 ##
14 ## Input: @ints = (3, 3, 1)
15 ## Output: 1
16 #
17 ## Example 2
18 ##
19 ## Input: @ints = (3, 2, 4, 2, 4)
20 ## Output: 3
21 #
22 ## Example 3
23 ##
24 ## Input: @ints = (1)
25 ## Output: 1
26 #
27 ## Example 4
28 ##
29 ## Input: @ints = (4, 3, 1, 1, 1, 4)
30 ## Output: 3
31 #
32 ############################################################
33 ##
34 ## discussion
35 ##
36 ############################################################
37 #
38 # We first count how often each integer appears in the array, then
39 # we just return the first one that appears exactly once as a way
40 # to short-circuit that part of the execution.
41 
42 use strict;
43 use warnings;
44 
45 unique_number(3, 3, 1);
46 unique_number(3, 2, 4, 2, 4);
47 unique_number(1);
48 unique_number(4, 3, 1, 1, 1, 4);
49 
50 sub unique_number {
51    my @ints = @_;
52    print "Input: (", join(", ", @ints), ")\n";
53    my $found;
54    foreach my $n (@ints) {
55       $found->{$n}++;
56    }
57    foreach my $key (keys %$found) {
58       return print "Output: $key\n" if $found->{$key} == 1;
59    }
60    return "Error: No number found exactly once!\n";
61 }