Peter
Peter Campbell Smith

Uneven number
and binary tree

Weekly challenge 130 — 13 September 2021

Week 130: 13 Sep 2021

Task 1

Task — Odd number

You are given an array of positive integers, such that all the numbers appear even number of times except one number. Write a script to find that integer.

Examples


Example 1
Input: @N = (2, 5, 4, 4, 5, 5, 2)
Output: 5 as it appears 3 times in the array whereas all 
other numbers - 2 and 4 - appear exactly twice.

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

Analysis

My vanilla solution is to pass through the array counting the number of occurrences of each entry, and then pass through the array of counts until finding an odd number.

Try it 

Try running the script with any input:



example: 9, 1, 2, 3, 9, 1, 2, 3, 9

Script


#!/usr/bin/perl

use v5.26;
use strict;
use warnings;

# PWC 130 task 1 - Peter Campbell Smith - 2021-09-13 

my (@N, $j, %count);

# sample data (3 is the answer)
@N = (1, 2, 3, 4, 3, 2, 1, 4, 4, 3, 4);

# get $count{$j} == number of instances of $j
for $j (@N) {
    $count{$j}++;
}

# look for the first instance of $count{$j} being odd                                                                 
for $j (keys %count) {
    if ($count{$j} & 1) {
        say qq[\nInput:  ] . join(', ', @N);
        say qq[Output: $j];
        last;
    }
}

Output


Input:  1, 2, 3, 4, 3, 2, 1, 4, 4, 3, 4
Output: 3

 

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