Skip to content

Instantly share code, notes, and snippets.

@re4388
Created December 3, 2024 11:57
Show Gist options
  • Save re4388/e675eecb83ecbb86f92da1f08d19d81b to your computer and use it in GitHub Desktop.
Save re4388/e675eecb83ecbb86f92da1f08d19d81b to your computer and use it in GitHub Desktop.
interviewAns
// 題目:
// 已知存在 random 可以使用 random(x:int,y:int) 會回傳 x~y 的正整數
// 請寫一個 function, 傳入 為 n
// 回傳一個隨機的 n 位數, 其中每個位數都要不相等
// e.x 101 => 不允許(1 重複)
// 12345=> 允許
// ex, n=2, 10(o), 11(x) …. 98(o), 99(x)
function random(x, y) {
return Math.floor(Math.random() * (y - x + 1) + x)
}
/**
* 傳入 為 n
* return 一個隨機的 n 位數, 其中每個位數都要不相等
* @param {number} n
* @returns {number}
*/
function randomN(n) {
// use set to ensure the number is unique in each digit
const set = new Set()
let res = ''
while (set.size < n) {
// create n unique digits
const num = random(0, 9)
set.add(num)
}
// return the result in set
set.forEach((num) => {
// string concatenation
res += num
})
// convert string to number
return Number(res)
}
// test cases
for (let i = 0; i < 2000; i++) {
console.assert(checkEachDigitIsUnique(randomN(2)) === true)
console.assert(checkEachDigitIsUnique(randomN(3)) === true)
console.assert(checkEachDigitIsUnique(randomN(4)) === true)
console.assert(checkEachDigitIsUnique(randomN(5)) === true)
console.assert(checkEachDigitIsUnique(randomN(6)) === true)
console.assert(checkEachDigitIsUnique(randomN(7)) === true)
console.assert(checkEachDigitIsUnique(randomN(8)) === true)
console.assert(checkEachDigitIsUnique(randomN(9)) === true)
console.assert(checkEachDigitIsUnique(randomN(10)) === true)
}
/**
*
* this function is to check if each digit is unique
* if there is any duplicate digit, return false
*
* @param {number} input
* @returns {boolean}
*/
function checkEachDigitIsUnique(input) {
return new Set(String(input)).size === String(input).length
}
// 第二題
/**
1. A > B > C
A: 賞金 100 (來自 B) + 底池 500 = 600 籌碼。
B: 賞金 0 (被淘汰)。
C: 賞金 0 (沒有被淘汰,剩餘 100 籌碼)。
2. B > A > C
B: 賞金 100 (來自 A) + 底池 500 = 600 籌碼。C 剩下 100 籌碼繼續遊戲。
A: 賞金 0 (被淘汰)。
C: 賞金 0 (沒有被淘汰,剩餘 100 籌碼)。
3. C > B > A
C: 賞金 200 (來自 A 和 B) + 底池 500 = 700 籌碼。
A: 賞金 0 (被淘汰)。
B: 賞金 0 (被淘汰)。
4. A > C > B
A: 賞金 100 (來自 C) + 底池 500 = 600 籌碼。B 剩下 0 籌碼。
B: 賞金 0 (被淘汰)。B 的 200 籌碼在 A 贏 C 時就已經輸掉。
C: 賞金 0 (沒有被淘汰,剩餘 100 籌碼)。在 A 贏 C 時,C 剩下 100 籌碼。
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment