[Google foobar] Level 3 Doomsday Fuel

Google foobar challenge level 3 - Doomsday Fuel

Description

Doomsday Fuel

Making fuel for the LAMBCHOP’s reactor core is a tricky process because of the exotic matter involved. It starts as raw ore, then during processing, begins randomly changing between forms, eventually reaching a stable form. There may be multiple stable forms that a sample could ultimately reach, not all of which are useful as fuel.

Commander Lambda has tasked you to help the scientists increase fuel creation efficiency by predicting the end state of a given ore sample. You have carefully studied the different structures that the ore can take and which transitions it undergoes. It appears that, while random, the probability of each structure transforming is fixed. That is, each time the ore is in 1 state, it has the same probabilities of entering the next state (which might be the same state). You have recorded the observed transitions in a matrix. The others in the lab have hypothesized more exotic forms that the ore can become, but you haven’t seen all of them.

Write a function solution(m) that takes an array of array of nonnegative ints representing how many times that state has gone to the next state and return an array of ints for each terminal state giving the exact probabilities of each terminal state, represented as the numerator for each state, then the denominator for all of them at the end and in simplest form. The matrix is at most 10 by 10. It is guaranteed that no matter which state the ore is in, there is a path from that state to a terminal state. That is, the processing will always eventually end in a stable state. The ore starts in state 0. The denominator will fit within a signed 32-bit integer during the calculation, as long as the fraction is simplified regularly.

For example, consider the matrix m:
[
[0,1,0,0,0,1], # s0, the initial state, goes to s1 and s5 with equal probability
[4,0,0,3,2,0], # s1 can become s0, s3, or s4, but with different probabilities
[0,0,0,0,0,0], # s2 is terminal, and unreachable (never observed in practice)
[0,0,0,0,0,0], # s3 is terminal
[0,0,0,0,0,0], # s4 is terminal
[0,0,0,0,0,0], # s5 is terminal
]
So, we can consider different paths to terminal states, such as:
s0 -> s1 -> s3
s0 -> s1 -> s0 -> s1 -> s0 -> s1 -> s4
s0 -> s1 -> s0 -> s5
Tracing the probabilities of each, we find that
s2 has probability 0
s3 has probability 3/14
s4 has probability 1/7
s5 has probability 9/14
So, putting that together, and making a common denominator, gives an answer in the form of
[s2.numerator, s3.numerator, s4.numerator, s5.numerator, denominator] which is
[0, 3, 2, 9, 14].

Languages

To provide a Java solution, edit Solution.java
To provide a Python solution, edit solution.py

Test cases

Your code should pass the following test cases.
Note that it may also be run against hidden test cases not shown here.

— Java cases —
Input:
Solution.solution({0, 2, 1, 0, 0}, {0, 0, 0, 3, 4}, {0, 0, 0, 0, 0}, {0, 0, 0, 0,0}, {0, 0, 0, 0, 0})

Output:
[7, 6, 8, 21]

Input:
Solution.solution({0, 1, 0, 0, 0, 1}, {4, 0, 0, 3, 2, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0})
Output:
[0, 3, 2, 9, 14]

— Python cases —

Input:
solution.solution([[0, 2, 1, 0, 0], [0, 0, 0, 3, 4], [0, 0, 0, 0, 0], [0, 0, 0, 0,0], [0, 0, 0, 0, 0]])
Output:
[7, 6, 8, 21]

Input:
solution.solution([[0, 1, 0, 0, 0, 1], [4, 0, 0, 3, 2, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]])
Output:
[0, 3, 2, 9, 14]

Idea

뭐라 할것도 없다.. Absorbing Markov Chain의 공식을 그대로 구현하면 되는 문제긴 하다. 평소에 수학좀 열심히 해둘껄..

관련 개념 찾아보다가 구글 서치에 사용되는 알고리즘이라 들었는데.. 그래서 나온건가 싶긴 하다.

결론적으로 마르코프 체인이 사이클을 가질 때 수렴하는 값이 존재하고 이를 계산한다는건데, 공식은 구현할 수 있는데 왜 이게 수렴할 수 있는지에 대한 증명은 이해가 가질 않는다..

참고 1.
참고 2.
참고 3.

Code

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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
public class Solution {
public static int[] solution(int[][] m) {
Set<Integer> terminationRows = getTerminationRows(m);

if(terminationRows.contains(0)) {
return NON_REACH_ABLE(m.length + 1);
}

Matrix R = createR(m, terminationRows);
Matrix Q = createQ(m, terminationRows);
Matrix I = createI(Q.n);
Matrix IminusQ = I.minus(Q);
Matrix F = IminusQ.inverse();
Matrix result = F.multiply(R);

List<Fraction> row0 = result.getRow(0);

int[] res = new int[row0.size() + 1];
int lcm = row0.stream().map(f -> f.denominator).reduce(Solution::LCM).get();
List<Integer> num = row0.stream().map(f -> f.numerator * (lcm / f.denominator)).collect(Collectors.toList());
num.add(lcm);
for(int i = 0; i < res.length; i++) res[i] = num.get(i);

return res;
}

private static Set<Integer> getTerminationRows(int[][] m) {
Set<Integer> terminationRows = new HashSet<>();
for (int i = 0; i < m.length; i++) {
boolean containsValue = false;
for (int j = 0; j < m[i].length && !containsValue; j++) {
if (m[i][j] != 0) {
containsValue = true;
}
}
if (!containsValue) {
terminationRows.add(i);
}
}

return terminationRows;
}

private static int[] NON_REACH_ABLE(int length) {
int[] res = new int[length];
res[0] = res[length-1] = 1;
return res;
}

private static Matrix createI(int size) {
List<List<Fraction>> I = new ArrayList<>();
for (int i = 0; i < size; i++) {
List<Fraction> row = new ArrayList<>();
for (int j = 0; j < size; j++) {
row.add(i == j ? new Fraction(1) : new Fraction(0));
}
I.add(row);
}

return new Matrix(I);
}

private static Matrix createQ(int[][] m, Set<Integer> terminateRows) {
List<List<Fraction>> Q = new ArrayList<>();
for (int i = 0; i < m.length; i++) {
if (terminateRows.contains(i)) continue;

int denominator = Arrays.stream(m[i]).sum();
List<Fraction> row = new ArrayList<>();

for (int j = 0; j < m[i].length; j++) {
if (!terminateRows.contains(j)) {
row.add(new Fraction(m[i][j], denominator));
}
}

Q.add(row);
}

return new Matrix(Q);
}

private static Matrix createR(int[][] m, Set<Integer> terminateRows) {
List<List<Fraction>> R = new ArrayList<>();
for (int i = 0; i < m.length; i++) {
if (terminateRows.contains(i)) continue;

int denominator = Arrays.stream(m[i]).sum();
List<Fraction> row = new ArrayList<>();

for (int j = 0; j < m[i].length; j++) {
if (terminateRows.contains(j)) {
row.add(new Fraction(m[i][j], denominator));
}
}

R.add(row);
}

return new Matrix(R);
}

private static class Matrix {
private List<List<Fraction>> matrix;
private int n;
private int m;

public Matrix(List<List<Fraction>> matrix) {
this.matrix = matrix;
this.n = matrix.size();
this.m = matrix.get(0).size();
}

public Fraction getFraction(int i, int j) {
return matrix.get(i).get(j);
}

public Matrix minus(Matrix target) {
List<List<Fraction>> result = new ArrayList<>();
for(int i = 0; i < n; i++) {
List<Fraction> row = new ArrayList<>();
for(int j = 0; j < m; j++) {
row.add(this.getFraction(i, j).minus(target.getFraction(i,j)));
}
result.add(row);
}
return new Matrix(result);
}

private Matrix cofactor(int r, int c) {
List<List<Fraction>> result = new ArrayList<>();
for(int i = 0; i < n; i++) {
if(i == r) continue;
List<Fraction> row = new ArrayList<>();
for(int j = 0; j < n; j++) {
if(j == c) continue;
row.add(this.getFraction(i, j));
}
result.add(row);
}

return new Matrix(result);
}

public Fraction det() {
if(n == 1) return getFraction(0, 0);
Fraction result = new Fraction(0);
if(n != m) return result;

int sign = 1;
for(int i = 0; i < n; i++) {
Fraction cofactorDet = cofactor(0, i).det();
result = result.plus(cofactorDet.multiply(getFraction(0,i)).multiply(sign));
sign *= -1;
}
return result;
}

public Matrix adj() {
List<List<Fraction>> result = new ArrayList<>();
if(n == 1) {
result.add(new ArrayList<Fraction>(){{ add(new Fraction(1));}});
return new Matrix(result);
}
for(int i = 0; i < n; i++) {
result.add(new ArrayList<>());
}

for(int i = 0; i < n; i++) {
for(int j = 0, sign = (((i + j) & 1) == 0) ? 1 : -1; j < m; j++, sign*=-1) {
result.get(j).add(cofactor(i,j).det().multiply(sign));
}
}

return new Matrix(result);
}

public Matrix inverse() {
Fraction inverseDet = det().reverse();
return adj().multiply(inverseDet);
}

public Matrix multiply(Matrix target) {
List<List<Fraction>> result = new ArrayList<>();
for(int i = 0; i < n; i++) {
List<Fraction> row = new ArrayList<>();
for(int j = 0; j < target.m; j++) {
row.add(new Fraction(0));
}
for(int j = 0; j < target.m; j++) {
for(int k = 0; k < m; k++) {
Fraction f1 = getFraction(i, k);
Fraction f2 = target.getFraction(k, j);
Fraction fraction = f1.multiply(f2);
row.set(j, fraction.plus(row.get(j)));
}
}
result.add(row);
}

return new Matrix(result);
}

public Matrix multiply(Fraction fraction) {
List<List<Fraction>> result = new ArrayList<>();
for(int i = 0; i < n; i++) {
List<Fraction> row = new ArrayList<>();
for(int j = 0; j < m; j++) {
row.add(getFraction(i, j).multiply(fraction));
}
result.add(row);
}
return new Matrix(result);
}

public List<Fraction> getRow(int r) {
return matrix.get(r);
}

public void print() {
System.out.println("=================== Print Matrix ==================");
System.out.println("=================== N [" + n + "] M : [" + m + "] ==================");
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
getFraction(i,j).print();
}
System.out.println();
}
System.out.println("=====================================");
}
}

private static class Fraction {
private int numerator;
private int denominator;

public Fraction(int numerator, int denominator) {
int gcd = numerator != 0 ? GCD(Math.abs(numerator), Math.abs(denominator)) : 1;
int n = numerator / gcd;
int d = numerator != 0 ? denominator / gcd : 1;
if(d < 0) { n = -n; d = -d; }
this.numerator = n;
this.denominator = d;
}

public Fraction(int numerator) {
this.numerator = numerator;
this.denominator = 1;
}

public Fraction plus(Fraction target) {
return new Fraction(numerator * target.denominator + denominator * target.numerator, denominator * target.denominator);
}

public Fraction minus(Fraction target) {
return new Fraction(numerator * target.denominator - denominator * target.numerator, denominator * target.denominator);
}

public Fraction multiply(int n) {
return new Fraction(numerator * n, denominator);
}

public Fraction multiply(Fraction fraction) {
return new Fraction(numerator * fraction.numerator, denominator * fraction.denominator);
}

public Fraction reverse() {
return new Fraction(denominator, numerator);
}

public void print() {
System.out.print("[" + numerator + " / " + denominator + "]");
}
}

private static int GCD(int p, int q) {
return q == 0 ? p : GCD(q, p % q);
}

private static int LCM(int p, int q) {
return p * q / GCD(p, q);
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/30/PS/Google/google-foobar-2022-level3-1/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.