-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount Salutes.js
36 lines (29 loc) · 1.31 KB
/
Count Salutes.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
// Description
// 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 firstRight = hallway.indexOf(">")
let lastLeft = hallway.lastIndexOf("<")
let right = 0
let left = 0
let salutes = 0
for (let i = firstRight; i<=lastLeft; i++) {
if (hallway[i]==">") {
right++
} else if (hallway[i]=="<") {
salutes += right * 2
}
}
return salutes
}