forked from c4fiber/java-onboarding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem1.java
96 lines (72 loc) · 2.57 KB
/
Problem1.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package onboarding;
import java.util.Comparator;
import java.util.List;
class Problem1 {
private static final int LEFT_PAGE_INDEX = 0;
private static final int RIGHT_PAGE_INDEX = 1;
private static final int MIN_PAGE_LENGTH = 1;
private static final int MAX_PAGE_LENGTH = 400;
private static final int RESULT_EXCEPTION = -1;
private static final int RESULT_DRAW = 0;
private static final int RESULT_POBI_WIN = 1;
private static final int RESULT_CRONG_WIN = 2;
public static int solution(List<Integer> pobi, List<Integer> crong) {
if (!isValidPages(pobi) || !isValidPages(crong)) {
return RESULT_EXCEPTION;
}
Integer pobiScore = calculateMaxScore(pobi);
Integer crongScore = calculateMaxScore(crong);
if (pobiScore > crongScore) {
return RESULT_POBI_WIN;
}
if (pobiScore < crongScore) {
return RESULT_CRONG_WIN;
}
return RESULT_DRAW;
}
private static boolean isValidPages(List<Integer> pages) {
Integer leftPage = pages.get(LEFT_PAGE_INDEX);
Integer rightPage = pages.get(RIGHT_PAGE_INDEX);
if (!isValidRange(leftPage) || !isValidRange(rightPage)) {
return false;
}
if (!isPageContinuous(leftPage, rightPage)) {
return false;
}
return isLeftPage(leftPage) && isRightPage(rightPage);
}
private static boolean isValidRange(Integer page) {
return MIN_PAGE_LENGTH <= page && page <= MAX_PAGE_LENGTH;
}
private static boolean isPageContinuous(Integer leftPage, Integer rightPage) {
return leftPage + 1 == rightPage;
}
private static boolean isLeftPage(Integer page) {
return page % 2 == 1;
}
private static boolean isRightPage(Integer page) {
return page % 2 == 0;
}
private static Integer calculateMaxScore(List<Integer> pages) {
return pages.stream()
.map(page -> Integer.max(calculateSumOfDigits(page), calculateProductOfDigits(page)))
.max(Comparator.naturalOrder())
.orElseThrow(IllegalArgumentException::new);
}
private static Integer calculateSumOfDigits(Integer page) {
int result = 0;
while (page != 0) {
result += page % 10;
page /= 10;
}
return result;
}
private static Integer calculateProductOfDigits(Integer page) {
int result = 1;
while (page != 0) {
result *= page % 10;
page /= 10;
}
return result;
}
}