Skip to content

Latest commit

 

History

History
49 lines (42 loc) · 1.08 KB

299.猜数字游戏.md

File metadata and controls

49 lines (42 loc) · 1.08 KB

299.猜数字游戏

/*
 * @lc app=leetcode.cn id=299 lang=typescript
 *
 * [299] 猜数字游戏
 */

// @lc code=start
function getHint(secret: string, guess: string): string {}
// @lc code=end

解法 1: 迭代

function getHint(secret: string, guess: string): string {
  let [a, b] = [0, 0]
  const map1 = Array(10).fill(0)
  const map2 = Array(10).fill(0)

  for (let i = 0; i < secret.length; i++) {
    const [s1, s2] = [secret[i], guess[i]].map(Number)
    if (s1 === s2) {
      a++
    } else {
      if (map1[s2]) map1[s2]--, b++
      else map2[s2]++
      if (map2[s1]) map2[s1]--, b++
      else map1[s1]++
    }
  }
  return `${a}A${b}B`
}

Case

test.each([
  { input: { secret: '1807', guess: '7810' }, output: '1A3B' },
  { input: { secret: '1123', guess: '0111' }, output: '1A1B' },
  { input: { secret: '1', guess: '0' }, output: '0A0B' },
  { input: { secret: '1', guess: '1' }, output: '1A0B' },
])('input: secret = $input.secret, guess = $input.guess', ({ input: { secret, guess }, output }) => {
  expect(getHint(secret, guess)).toEqual(output)
})