TASK #1: Unique Number
You are given an array of integers, @ints, where every elements appears more than once except one element.
Write a script to find the one element that appears exactly one time.
#!/usr/bin/perl use strict; use warnings; use Statistics::Frequency; =begin Let's use the marvellous Statistics CPAN module! =cut sub unique_number { my @ints = @_;# create a new Statistics::Frequency object my $freq = Statistics::Frequency->new(@ints); for (my $i = 0; $i <= $#ints; $i++) {$freq->frequency($element) returns the frequency of an element return($ints[$i]) if ( $freq->frequency($ints[$i]) == 1); } } # Tests my @ints; # Example 1 @ints = (3, 3, 1); print(unique_number(@ints), "\n");# Output: 1 # Example 2 @ints = (3, 2, 4, 2, 4); print(unique_number(@ints), "\n");# Output: 3 # Example 3 @ints = (1); print(unique_number(@ints), "\n");# Output: 1 # Example 4 @ints = (4, 3, 1, 1, 1, 4); print( unique_number(@ints), "\n" );# Output: 3 # Example 5 @ints = (3, 3, 3, 2, 2, 1); print( unique_number(@ints), "\n" );# Output: 1
#!/usr/bin/perl use strict; use warnings; =begin Let's use my favorite Statistics module again! =cut use Statistics::Frequency; sub digit_count_value { my @ints = @_;# create a new Statistics::Frequency object my $freq = Statistics::Frequency->new(@ints); for (my $i = 0; $i < scalar(@ints); $i++) {# $freq->frequency($i) returns the frequency # only if $i is element of @ints if (grep( /^$i$/, @ints )) { return("false") if($freq->frequency($i) != $ints[$i]); } else {# if $i is not an element of @ints, $ints[$i] should be 0 return("false") if ($ints[$i] != 0); } } return("true"); } # Tests my @ints; # Example 1 @ints = (1, 2, 1, 0); print(digit_count_value(@ints), "\n");# Output: true # Example 2 @ints = (0, 3, 0); print(digit_count_value(@ints), "\n");# Output: false # Example 3 @ints = (2, 0, 2, 0); print( digit_count_value(@ints), "\n");# Output: true # Example 4 @ints = (2, 1, 2, 0, 0); print( digit_count_value(@ints), "\n");# Output: true # Example 5 @ints = (2, 1, 0, 0, 2); print( digit_count_value(@ints), "\n");# Output: false # Example 6 @ints = (2, 1, 1, 0, 0); print( digit_count_value(@ints), "\n");# Output: false # Example 7 @ints = (0, 3, 2, 0, 1); print( digit_count_value(@ints), "\n");# Output: false # Example 8 @ints = (2, 1, 2, 0); print( digit_count_value(@ints), "\n");# Output: false # Example 9 @ints = (3, 1, 2, 0); print( digit_count_value(@ints), "\n");# Output: false