Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* All we love the “Bulls and Cows” game (http://en.wikipedia.org/wiki/Bulls_and_cows).
- Given a 4-digit secret number and a 4-digit guess number we say that we have b bulls and c cows when we have
- b matching digits on their right positions (bulls) and c matching digits on different positions (cows).
- Given the secret number and the number of bulls and cows your task is to write a program to find
- all matching guess numbers in increasing order.
- The secret number will always consist of exactly 4 digits, each in the range [1…9]!
- The input will consist of exactly 3 lines. At the first line there the secret number will be given.
- At the second line the number of bulls b will be given. At the third line the number of cows c will be given.
- The output should consist of a single line holding all matched guess numbers, given in increasing order,
- separated by single space. */
- "use strict";
- function solve(args) {
- var secretStr = args[0];
- var bulls = parseInt(args[1]);
- var cows = parseInt(args[2]);
- Array.prototype.contains = function (checkElement) {
- for (var index in this) {
- if (this.hasOwnProperty(index)) {
- if (this[index] === checkElement) {
- return true;
- }
- }
- }
- return false;
- };
- var matchedNumbers = [];
- var num, secretNumber, guessNumber;
- for (num = 1111; num < 10000; num += 1) {
- guessNumber = num.toString().split('');
- if (!guessNumber.contains('0')) {
- secretNumber = secretStr.split('');
- var countBulls = getBullsDigits();
- var countCows = getCowsDigits();
- if (countBulls == bulls && countCows == cows) {
- matchedNumbers.push(num);
- }
- }
- }
- if (matchedNumbers.length) {
- console.log(matchedNumbers.join(' '));
- } else {
- console.log('No');
- }
- function getBullsDigits() {
- var countBulls = 0;
- for (var i = 0; i < 4; i += 1) {
- if (guessNumber[i] == secretNumber[i]) {
- guessNumber[i] = '-';
- secretNumber[i] = '*';
- countBulls += 1;
- }
- }
- return countBulls;
- }
- function getCowsDigits() {
- var countCows = 0;
- if (countBulls < 3) {
- for (var i = 0; i < 4; i += 1) {
- for (var j = 0; j < 4; j += 1) {
- if (guessNumber[j] == secretNumber[i]) {
- guessNumber[j] = '-';
- secretNumber[i] = '*';
- countCows += 1;
- }
- }
- }
- }
- return countCows;
- }
- }
- solve(['2228', '2', '1']);
- solve(['1234', '3', '0']);
- solve(['1234', '3', '1']);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement