Skip to content

Commit 11716db

Browse files
authored
Create 1643-kth-smallest-instructions.js
1 parent c2848ad commit 11716db

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1643-kth-smallest-instructions.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* @param {number[]} destination
3+
* @param {number} k
4+
* @return {string}
5+
*/
6+
const kthSmallestPath = function (destination, k) {
7+
let v = destination[0],
8+
h = destination[1]
9+
const mu = (c, n) => {
10+
let res = ''
11+
for (let i = 0; i < n; i++) {
12+
res += c
13+
}
14+
return res
15+
}
16+
17+
let res = ''
18+
while (h > 0 && v > 0) {
19+
let pre = comb(h + v - 1, v)
20+
if (k <= pre) {
21+
res += 'H'
22+
h -= 1
23+
} else {
24+
res += 'V'
25+
v -= 1
26+
k -= pre
27+
}
28+
}
29+
if (h == 0) res += mu('V', v)
30+
if (v == 0) res += mu('H', h)
31+
return res
32+
}
33+
34+
function product(a, b) {
35+
let prd = a,
36+
i = a
37+
38+
while (i++ < b) {
39+
prd *= i
40+
}
41+
return prd
42+
}
43+
44+
function comb(n, r) {
45+
if (n == r) {
46+
return 1
47+
} else {
48+
r = r < n - r ? n - r : r
49+
return product(r + 1, n) / product(1, n - r)
50+
}
51+
}

0 commit comments

Comments
 (0)