-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountSalutes.js
35 lines (25 loc) · 1.22 KB
/
countSalutes.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
/* There is a narrow hallway in which people can go right and left only. When two people meet in the hallway, by tradition they must salute each other. People move at the same speed left and right.
Your task is to write a function that, given a string representation of people moving in the hallway, will count the number of salutes that will occur.
Note: 2 salutes occur when people meet, one to the other and vice versa.
Input
People moving right will be represented by >; people moving left will be represented by <. An example input would be >--<--->->. The - character represents empty space, which you need not worry about.
Examples
Input: >----->-----<--<
Output: 8
Explanation: Both guys moving right will meet both guys moving left.
Hence a total of 4 meetings will occur and 8 salutes will occur.
Input: <---<--->----<
Output: 2
Explanation: Only one meeting occurs.*/
function countSalutes(hallway) {
let rightDirection = 0;
let totalSalutes = 0;
for (let i = 0; i < hallway.length; i++) {
if (hallway[i] === '>') {
rightDirection++;
} else if (hallway[i] === '<') {
totalSalutes += 2 * rightDirection; // Each left-facing person salutes each right-facing person
}
}
return totalSalutes;
}