-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathumbrellas.js
59 lines (47 loc) · 2.07 KB
/
umbrellas.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
51
52
53
54
55
56
57
58
59
/*
A Man and his Umbrellas
Each morning a man walks to work, and each afternoon he walks back home.
If it is raining in the morning and he has an umbrella at home, he takes an umbrella for the journey so he doesn't get wet, and stores it at work. Likewise, if it is raining in the afternoon and he has an umbrella at work, he takes an umbrella for the journey home.
Given an array of the weather conditions, your task is to work out the minimum number of umbrellas he needs to start with in order that he never gets wet. He can start with some umbrellas at home and some at work, but the output is a single integer, the minimum total number.
The input is an array/list of consecutive half-day weather forecasts. So, e.g. the first value is the 1st day's morning weather and the second value is the 1st day's afternoon weather. The options are:
"clear",
"sunny",
"cloudy",
"rainy",
"overcast",
"windy"
"thunderstorms".
e.g. for three days, 6 values:
weather = ["rainy", "cloudy", "sunny", "sunny", "cloudy", "thunderstorms"]
N.B. He never takes an umbrella if it is not raining.
Examples:
minUmbrellas(["rainy", "clear", "rainy", "cloudy"])
should return 2
Because on the first morning, he needs an umbrella to take, and he leaves it at work. So on the second morning, he needs a second umbrella.
minUmbrellas(["sunny", "windy", "sunny", "clear"])
should return 0
Because it doesn't rain at all
minUmbrellas(["rainy", "rainy", "rainy", "rainy", "thunderstorms", "rainy"])
should return 1
Because he only needs 1 umbrella which he takes on every journey.
*/
const minUmbrellas = (weather) => {
let atWork = 0
let atHome = 0
let needed = 0
weather.map((day, i) => {
if (day === 'rainy' || day === 'thunderstorms') {
if (i % 2 === 0) {
atHome ? (atHome -= 1) : (needed += 1)
atWork += 1
} else {
atWork ? (atWork -= 1) : (needed += 1)
atHome += 1
}
}
})
return needed
}
console.log(minUmbrellas(['cloudy'])) // => 0
console.log(minUmbrellas(['rainy', 'rainy', 'rainy', 'rainy'])) // => 1
console.log(minUmbrellas(['overcast', 'rainy', 'clear', 'thunderstorms'])) // => 2