bulls and cows ai

Solutions on MaxInterview for bulls and cows ai by the best coders in the world

showing results for - "bulls and cows ai"
Josué
10 Aug 2019
1import java.util.*;
2class Main {
3    static ArrayList<String> possib = new ArrayList<String>();
4    public static void main(String args[]) {
5        System.out.println("COWS AND BULLS SOLVER:");
6        init();
7        Scanner in = new Scanner(System.in);
8        while (possib.size() > 1) {
9            String guess = possib.get((int)(Math.random() * possib.size()));
10            System.out.print(guess+" ");
11            int bulls = in.nextInt();
12            int cows = in.nextInt();
13            for (int j = 0; j < possib.size(); j++)
14                if (!check(possib.get(j),guess,cows,bulls)) {
15                    possib.remove(j);
16                    j--;
17                }
18        }
19        for (int j = 0; j < possib.size(); j++)
20            System.out.println(possib.get(j));
21    }
22    
23    static void init() {
24        for (int a = 1; a <= 9; a++) { 
25            for (int b = 1; b <= 9; b++) {
26                if (b == a) continue;
27                for (int c = 1; c <= 9; c++) {
28                    if (c == b || c == a) continue;
29                    for (int d = 1; d <= 9; d++) {
30                        if (d == a || d == b || d == c) continue;
31                        String cnt = ""+a+b+c+d;
32                        possib.add(cnt);
33                    }
34                }
35            }
36        }
37    }
38    
39    static boolean check(String ans,String guess,int cows,int bulls) {
40        for (int i = 0; i < guess.length(); i++) {
41            int ind = ans.indexOf(guess.charAt(i));
42            if (ind == i) bulls--;
43            else if (ind >= 0) cows--;
44        }
45        return (cows == 0) && (bulls == 0);
46    }
47}
48
similar questions
queries leading to this page
bulls and cows ai