-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution4.java
More file actions
78 lines (61 loc) · 2.31 KB
/
Copy pathSolution4.java
File metadata and controls
78 lines (61 loc) · 2.31 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
77
78
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution4 {
public static void main(String[] args)
{
for (String arg : args) {
Integer N = Integer.valueOf(arg) - 1;
List<Integer> current = Arrays.asList(1);
for (int n = 0; n < N; n++) {
List<Integer> next = new ArrayList<>();
int previous = 0;
List<Integer> group = new ArrayList<>();
for (int i = 0; i < current.size(); i++) {
Integer actual = current.get(i);
if (isFirstElement(previous)) {
//no values before
group.add(actual);
}
if (previousElementWasEqual(previous, actual)) {
//if the same value before
group.add(actual);
}
if (!previousElementWasEqual(previous, actual) && !isFirstElement(previous)) {
addGroup(next, group);
group = new ArrayList<>();
group.add(actual);
}
if (isLastElement(i, current.size() - 1)) {
addGroup(next, group);
}
previous = actual;
}
current = next;
}
System.out.println(current.stream().reduce((integer, integer2) -> integer + integer2).get());
}
}
private static void addGroup(List<Integer> next, List<Integer> group) {
if (group.size() == 1) {
//if group is one element then add 1 at start
next.add(1);
next.add(group.get(0));
} else {
//in other case we can assume that there are same elements in group
//so we increment first one
Integer first = group.get(0);
next.add(group.size());
next.add(first);
}
}
private static boolean isLastElement(int i, int i2) {
return i == i2;
}
private static boolean previousElementWasEqual(int previous, Integer value) {
return previous == value;
}
private static boolean isFirstElement(int previous) {
return previous == 0;
}
}