猜数字(Bulls and Cows)游戏
2020-06-12 本文已影响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'
}