美文网首页
猜数字(Bulls and Cows)游戏

猜数字(Bulls and Cows)游戏

作者: _____西班木有蛀牙 | 来源:发表于2020-06-12 17:35 被阅读0次
题目
// secret 秘密  guess 猜测
function get(secret, guess) {
  // 因为都是数字 建一个字典树 最多10个
  const trie = {};
  for (let i = 0; i < secret.length; i += 1) {
    trie[secret[i]] = 0
  }
  let bulls = 0;
  let cows = 0;
  for (let i = 0; i < guess.length; i += 1) {
    if (secret[i] === guess[i]) {
      // 公牛
      bulls += 1;
    } else if (trie[guess[i]] === 0) {
      // 奶牛
      trie[guess[i]] = 1;
    }
  }
  for (let i = 0; i <= 9; i += 1) {
    cows += trie[i] || 0
  }
  return `${bulls}A${cows}B`
}
get('1807', '7810') // 1A3B
get('1123', '0111') // 1A1B
get('1234', '4321') // 0A4B
get('111116', '100001') // 1A1B
var getHint = function (secret, guess) {
  var bull = 0;
  var cow = 0;
  // 储存
  var skeep = [];
  var gkeep = [];

  for (var i in guess) {
    if (secret[i] == guess[i]) {
      bull++;
    } else {
      skeep.push(secret[i]);
      gkeep.push(guess[i])
    }
  }

  for (var j in gkeep) {
    var findIndex = skeep.indexOf(gkeep[j]);
    if (findIndex != -1) {
      cow++;
      skeep[findIndex] = null;
    }
  }

  return bull + "A" + cow + 'B'
}

相关文章

  • 猜数字(Bulls and Cows)游戏

  • T299、猜数字游戏

    你在和朋友一起玩 猜数字(Bulls and Cows)游戏,该游戏规则如下:你写出一个秘密数字,并请朋友猜这个数...

  • 299. Bulls and Cows(easy)

    introduction 你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友...

  • 猜数字游戏

    你正在和你的朋友玩 [猜数字(Bulls and Cows)]游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给...

  • 299. 猜数字游戏

    题目:你正在和你的朋友玩猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给...

  • 299. 猜数字游戏

    你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一...

  • Leetcode-299 猜数字游戏

    299. 猜数字游戏[https://leetcode-cn.com/problems/bulls-and-cow...

  • 299. Bulls and Cows

    Description You are playing the following Bulls and Cows ...

  • 299. Bulls and Cows

    问题 You are playing the following Bulls and Cows game with...

  • 299. Bulls and Cows

    You are playing the following Bulls and Cows game with yo...

网友评论

      本文标题:猜数字(Bulls and Cows)游戏

      本文链接:https://www.haomeiwen.com/subject/cxjntktx.html