Peter
Peter Campbell Smith

Add up the singletons
and clear out the list

Weekly challenge 228 — 31 July 2023

Week 228: 31 Jul 2023

Task 1

Task — Unique sum

You are given an array of integers. Write a script to find out the sum of unique elements in the given array.

Examples


Example 1
Input: @int = (2, 1, 3, 2)
Output: 4

Example 2
Input: @int = (1, 1, 1, 1)
Output: 0

Example 3
Input: @int = (2, 1, 3, 4)
Output: 10

Analysis

It's very tempting to use List::Uniq, and yes I succumbed to temptation, which reduces the task to:

$sum += $_ for uniq(@_);

Otherwise, the options seem to be:

  • Sort the list, then add to $sum each $element that isn't equal to the previous one, or
  • Add each element to $sum unless $seen{element}, and then set $seen{$element} to 1.

Try it 

Example: 1, 2, 3, 4, 5, 5

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2023-07-31
use utf8;     # Week 228 task 1 - Unique sum
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use List::Uniq 'uniq';

my ($j, @int);

unique_sum(2, 1, 3, 2);
unique_sum(1, 1, 1, 1);

# longer example
for $j (1 .. 12) {
    push (@int, int(rand(9) + 1));
}
unique_sum(@int);

sub unique_sum {
    
    my $sum;
    $sum += $_ for uniq(@_);
    
    say qq[\nInput:  \@int = (] . join(', ', @_) . ')';
    say qq[Output: ] . (defined($sum) ? $sum : 0);
}

Output


Input:  @int = (2, 1, 3, 2)
Output: 6

Input:  @int = (1, 1, 1, 1)
Output: 1

Input:  @int = (1, 2, 2, 4, 9, 6, 2, 4, 3, 5, 5, 4)
Output: 30

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain