-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
76 lines (65 loc) · 2.11 KB
/
Solution.java
File metadata and controls
76 lines (65 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Stack;
class Solution {
public static void main(String[] args) {
int[][] baseball = {
{123,1,1},
{356,1,0},
{327,2,0},
{489,0,1}
};
int answer = solution(baseball);
System.out.println(answer);
}
public static int solution(int[][] baseball) {
// Make a stack for candidate numbers
Stack<Integer> stack = new Stack<Integer>();
for (int i=1; i<10; i++){
for(int j=1; j<10; j++){
for(int k=1; k<10; k++){
if(i != j && j != k && k != i) {
stack.add(i*100 + j*10 + k);
}
}
}
}
Stack<Integer> temp = new Stack<Integer>();
boolean flag = true;
while(!stack.isEmpty()){
int num = stack.pop();
// check each condition in baseball[][]
for(int i=0; i<baseball.length; i++){
int strikeNum = calStrike(num, baseball[i][0]);
int ballNum = calBall(num, baseball[i][0]) - strikeNum;
if(strikeNum != baseball[i][1] || ballNum != baseball[i][2]){
flag = false;
break;
}
}
if(flag) temp.add(num);
flag = true;
}
return temp.size();
}
public static int calStrike(int num, int target){
int cnt = 0;
String numToStr = Integer.toString(num);
String targetToStr = Integer.toString(target);
for(int i=0; i< targetToStr.length(); i++){
if(numToStr.charAt(i) == targetToStr.charAt(i)){
cnt++;
}
}
return cnt;
}
public static int calBall(int num, int target){
int cnt = 0;
String numToStr = Integer.toString(num);
String targetToStr = Integer.toString(target);
for(int i=0; i<targetToStr.length(); i++){
if(numToStr.contains(Character.toString(targetToStr.charAt(i)))){
cnt++;
}
}
return cnt;
}
}