I am learning how to code Javascript. Been learning for 6 months now. I'm working through code wars problems to help me with my logic when it comes to algorithms.
I was working on this CodeWars problem Find All Pairs
Here was my logic and code:
SET a pair count variable
SET a sorretd array varible
FOR LOOP iterate though the array
SET index = 0
WHILE index < array argument
Increment index
IF the current iteration is equal to the index + 1
ADD to the pair count varible
RETURN count variable
CODE:
function duplicates(array) {
let pairResult = 0;
let sorrtedArray = array.sort();
for (let index = 0; index < sorrtedArray.length; index++) {
if (sorrtedArray[index + 1] === sorrtedArray[index]) {
pairResult += 1;
index++
console.log(index);
}
}
return pairResult;
}
The test output I was getting with the two test cases were:
console.log(duplicates([1, 2, 5, 6, 5, 2])) ====> 2
console.log(duplicates([1, 2, 2, 20, 6, 20, 2, 6, 2])); ====> 5
I know it was counting 2
s three times, at least that is what it seems. Anyways, I had to look at the solution. Below is a code that was almost identical to mine that worked.
function duplicates(array){
//Make the magic happen
const newArray = array.sort((a,b) => a-b);
if (newArray.length <= 1) return 0;
let count = 0;
for (let i = 0; i < newArray.length ; i++) {
if (newArray[i] == newArray[i+1]) {
count++;
i++;
}
}
return count;
}
My question is why are we incrementing the i++
again within the for loop when were incrementing it already when we declare the for loop?
It's there to avoid over-counting duplicates. As the requirements say:
If there are more pairs of a certain number, count each pair only once. Eg: for [0, 0, 0, 0] the return value is 2 (= 2 pairs of 0s)
For example, given
[2, 2, 2]
you'd want to count one set of pairs.
When a pair is found
for (let i = 0; i < newArray.length ; i++) {
if (newArray[i] == newArray[i+1]) {
count++;
i++;
}
}
you've now checked off both indicies i
and i + 1
- if you proceeded to compare indicies i + 1
and i + 2
on the next iteration, you'd be counting the item at i + 1
one too many.
By doing i++
inside the loop, you ensure that you skip over to the next unchecked item, without iterating over something you've already checked, to avoid double-counting.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.