-
Notifications
You must be signed in to change notification settings - Fork 0
/
locateSeat.ts
45 lines (43 loc) · 1.03 KB
/
locateSeat.ts
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
enum Instruction {
LOWER_HALF = 'LOWER_HALF',
UPPER_HALF = 'UPPER_HALF',
}
const findNumber = (
instructions: Instruction[],
start: number,
end: number,
): number => {
if (start === end) return start
const [instruction, ...rest] = instructions
if (rest.length === 0) {
return instruction === Instruction.LOWER_HALF ? start : end
}
if (instruction === Instruction.LOWER_HALF) {
return findNumber(rest, start, start + Math.floor((end - start) / 2))
}
return findNumber(rest, start + Math.ceil((end - start) / 2), end)
}
export const locateSeat = ({ rows, cols }: { rows: number; cols: number }) => (
passId: string,
): { row: number; col: number } => ({
row: findNumber(
passId
.split('')
.filter((s) => ['F', 'B'].includes(s))
.map((s) =>
s === 'F' ? Instruction.LOWER_HALF : Instruction.UPPER_HALF,
),
0,
rows - 1,
),
col: findNumber(
passId
.split('')
.filter((s) => ['L', 'R'].includes(s))
.map((s) =>
s === 'L' ? Instruction.LOWER_HALF : Instruction.UPPER_HALF,
),
0,
cols - 1,
),
})