My Solution on this problem:
function numberOfPairs(gloves) {
const glove = gloves.slice().sort();
const pairs = [];
for (let i = 0; i < glove.length - 1; i ) {
if (glove[i] == glove[i 1]) {
pairs.push(glove[i]);
}
}
return pairs.length;
}
It pass the initial test but failed the attempt/random test. 2nd test
My Second Solution, I add i . It pass the Attempt
function numberOfPairs(gloves) {
const glove = gloves.slice().sort();
const pairs = [];
for (let i = 0; i < glove.length - 1; i ) {
if (glove[i] == glove[i 1]) {
pairs.push(glove[i]);
i // How?
}
}
return pairs.length;
}
Can you guys help me how does i fix the problem.
CodePudding user response:
Because if you found a pair, the next element is equal to the actual and you're advancing only one element in the array at a time. If you found a pair, the next element was the one found, then you have to advance another position in the array when you found it.
Say you have this array: [1, 2, 5, 8, 9, 2, 8] Let's number the lines to make it easier:
1 function numberOfPairs(gloves) {
2 const glove = gloves.slice().sort();
3 const pairs = [];
4 for (let i = 0; i < glove.length - 1; i ) {
5 if (glove[i] == glove[i 1]) {
6 pairs.push(glove[i]);
7 i // How?
8 }
9 }
10 return pairs.length;
11 }
after line 2 you will have the following sorted array:
[1, 2, 2, 5, 8, 8, 9]
with 2 pairs in it. Then you will start iteration of the array with i = 0 so in line 6 in the first iteraction glove[i] is 1 and glove[i 1] is 2. Different, so the for continues to i = 1.
Now the if in line 6 tests glove[i] with i = 1 making glove[i] = 2 and glove[i 1] also = 2 (first pair). So it enters the if and pushes the first number to pairs: 2.
Now if i isn't present in line 7, what would happen is that for would countinue to i = 2 making glove[i] = 2 and glove[i 1] = 5. But the 2 makes part of the first pair encountered. So this is incorrect. We must skip the 2nd 2 that's what i is line 7 is there for. It would be even worse if the 4th element in the array was 2 again because it would inform another pair when there only one.
After this for will continue not to i=2 but correctly to i=3 testing elements 5 and 8 for the next pair.
Hope this explains clearly enough.
CodePudding user response:
You can also group the colors and then count the pairs using Array.prototype.reduce.
function solution(input) {
return input.reduce(
([pairs, hash], clr) => {
hash[clr] = (hash[clr] ?? 0) 1;
return [pairs (hash[clr] % 2 === 0 ? 1 : 0), hash];
},
[0, {}]
)[0];
}
console.log(solution(["red", "green", "red", "blue", "blue"]));
console.log(solution(["red", "red", "red", "red", "red", "red"]));