-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcounting-valleys.js
50 lines (39 loc) · 1.23 KB
/
counting-valleys.js
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
console.log("fichier counting-valleys.js chargé !")
/*
UDDDUDUU => 1
Algoritme pour compter le nombre de vallées
Boucle de consommation des pas :
Je prend le premier pas.
Si c'est un U, je compte +1
Sinon si c'est un D, je compte -1
Je prend le second pas.
Si c'est un U, je compte +1
Sinon si c'est un D, je compte -1
Et ainsi de suite
Structure de contrôle permettant de détecter une valée
Quand je reviens à 0, j'ai fini une montagne, ou une vallée.
Si pas qui m'a fait revenir à 0 est un U, alors j'étais dans une vallée
*/
const jeViensDUneVallee = (positionAgainstSeaLevel, step) => {
return positionAgainstSeaLevel == 0 && step == "U"
}
const countNumberOfValleysFor = (steps) => {
let positionAgainstSeaLevel = 0
let numberOfValleys = 0
for(step of steps) {
switch (step) {
case 'U':
positionAgainstSeaLevel++
break
case 'D':
positionAgainstSeaLevel--
break
}
// DEBUG.
// console.log(step, positionAgainstSeaLevel)
if (jeViensDUneVallee(positionAgainstSeaLevel, step)) {
numberOfValleys++
}
}
return numberOfValleys
}