Peter’s blog ✴ Week 130 ✴ 13 September 2021
THE WEEKLY CHALLENGE
Uneven number and binary tree
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.
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
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.
I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.
#!/usr/bin/perl use v5.26; use strict; use warnings; # PWC 130 task 1 - Peter Campbell Smith - 2021-09-13 odd_number(1, 2, 3, 4, 3, 2, 1, 4, 4, 3, 4); sub odd_number { my (@N, $j, %count); # get $count{$j} == number of instances of $j for $j (@_) { $count{$j} ++; } # look for the first instance of $count{$j} being odd for $j (keys %count) { if ($count{$j} & 1) { say qq[\nInput: ] . join(', ', @_); say qq[Output: $j]; last; } } }
9 lines of code
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