Repository navigation
Expand file tree
/
Copy pathmetroCard.js
More file actions
77 lines (66 loc) · 2.37 KB
/
Copy pathmetroCard.js
File metadata and controls
77 lines (66 loc) · 2.37 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
75
76
77
/*
You just bought a public transit card that allows you to ride the Metro
for a certain number of days.
Here is how it works: upon first receiving the card, the system allocates
you a 31-day pass, which equals the number of days in January. The second
time you pay for the card, your pass is extended by 28 days, i.e. the number
of days in February (note that leap years are not considered), and so on.
The 13th time you extend the pass, you get 31 days again.
You just ran out of days on the card, and unfortunately you've forgotten
how many times your pass has been extended so far. However, you do remember
the number of days you were able to ride the Metro during this most recent
month. Figure out the number of days by which your pass will now be extended,
and return all the options as an array sorted in increasing order.
Example
For lastNumberOfDays = 30, the output should be
metroCard(lastNumberOfDays) = [31].
There are 30 days in April, June, September and November, so the next
months to consider are May, July, October or December. All of them have
exactly 31 days, which means that you will definitely get a 31-days pass
the next time you extend your card.
*/
function metroCard(lastNumberOfDays) {
let result = [];
let months = ['Jan', 'Feb', 'Mar', 'Apr',
'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
let hash_map = {
'Jan': 31,
'Feb': 28,
'Mar': 31,
'Apr': 30,
'May': 31,
'June': 30,
'July': 31,
'Aug': 31,
'Sep': 30,
'Oct': 31,
'Nov': 30,
'Dec': 31,
};
let givenMonths = [];
for (let key in hash_map) {
if (hash_map[key] === lastNumberOfDays) {
givenMonths.push(key);
}
}
let nextMonths = [];
for (let i = 0; i < givenMonths.length; i++) {
let index = months.indexOf(givenMonths[i]);
if (index === months[months.length-1]) {
index = 0;
}
index+= 1;
if (months[index] === undefined) {
index = 0;
}
nextMonths.push(months[index]);
}
for (let i = 0; i < nextMonths.length; i++) {
if (!(result.includes(hash_map[nextMonths[i]]))) {
result.push(hash_map[nextMonths[i]]);
}
}
return result;
}
console.log(metroCard(30)) // [31]
console.log(metroCard(31)) // [28,30,31]