This problem on codewars asks the following:
Given an array, find the integer that appears an odd number of times. There will always be exactly one integer that appears an odd number of times.
Example: (Input --> Output)
findOdd([20, 1, 1, 2, 2]) = 20
findOdd([5, 4, 3, 2, 1, 5, 4, 3, 2, 10, 10]) = 1
How to approach it with the PEDAC method:
P: Understand the problem -
We need to identify which number in an array appears an odd number of times. Although each number can appear multiple times, only one will appear an odd number of times.
E: Give Example -
In an array like [8, 8, 7, 7, 7], 7 shows up 3 times (odd), making it our target.
For [1, 1, 2], 2 appears just once (odd), pinpointing it as the solution.
D: What data structure(s) would be needed -
An object seems perfect for mapping each number to its occurrence count within the array.
A: Steps to solve it without language specific information -
- Loop first through the array: This allows me to inspect each number individually.
- If I arrive at a number, add it to a data structure: object
- Check if the number has been encountered before. If not, initialize its count in the object. If the number is already in the object, increment its count
- Loop through the object to inspect counts and return the odd number of counts
C: Code the solution guided by the pseudocode-
- Loop first through the array
for (let i of A) {
- If I arrive at a number, add it to a data structure: object
- Check if the number has been encountered before. If not, initialize its count in the object. If the number is already in the object, increment its count
if (!values[i]) {
values[i] = 1;
} else {
values[i] += 1;
}
}
- Loop through the object to inspect counts and return the odd number of counts
for (let k in values) {
if (values[k] % 2 === 1) {
return Number(k);
}
}
Putting it all together in the function findOdd
:
function findOdd(A) {
let values = {};
// Loop first through the array
for (let i of A) {
// Check if the number has been encountered before
if (!values[i]) {
values[i] = 1; // If not, initialize its count
} else {
values[i] += 1; // If it has, increment its count
}
}
// Loop through the object to find and return the number with an odd count
for (let k in values) {
if (values[k] % 2 === 1) {
return Number(k);
}
}
}
Top comments (0)