-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReto #6.js
More file actions
74 lines (59 loc) · 1.63 KB
/
Reto #6.js
File metadata and controls
74 lines (59 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Reto #6: 🧤 Emparejando guantes
*
* En el taller de Santa, los elfos han encontrado una montaña de guantes mágicos totalmente desordenados. Cada guante viene descrito
* por dos valores:
*
* hand: indica si es un guante izquierdo (L) o derecho (R)
* color: el color del guante (string)
* Tu tarea es ayudarles a emparejar guantes: Un par válido es un guante izquierdo y uno derecho del mismo color.
* Debes devolver una lista con los colores de todos los pares encontrados. Ten en cuenta que puede haber varios pares del mismo color.
* 🧩 Ejemplos
*/
const gloves = [
{ hand: 'L', color: 'red' },
{ hand: 'R', color: 'red' },
{ hand: 'R', color: 'green' },
{ hand: 'L', color: 'blue' },
{ hand: 'L', color: 'green' }
]
matchGloves(gloves)
// ["red", "green"]
const gloves2 = [
{ hand: 'L', color: 'gold' },
{ hand: 'R', color: 'gold' },
{ hand: 'L', color: 'gold' },
{ hand: 'L', color: 'gold' },
{ hand: 'R', color: 'gold' }
]
matchGloves(gloves2)
// ["gold", "gold"]
const gloves3 = [
{ hand: 'L', color: 'red' },
{ hand: 'R', color: 'green' },
{ hand: 'L', color: 'blue' }
]
matchGloves(gloves3)
// []
function matchGloves(gloves) {
const L = {};
const R = {};
for (const { hand, color } of gloves) {
if (hand === 'L') {
L[color] = (L[color] ?? 0) + 1;
} else {
R[color] = (R[color] ?? 0) + 1;
}
}
const ans = [];
for (const color in R) {
const countL = L[color];
if (countL !== undefined) {
const pairs = Math.min(R[color], countL);
for (let i = 0; i < pairs; i++) {
ans.push(color);
}
}
}
return ans;
}