forked from nayuki/Project-Euler-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp079.java
More file actions
70 lines (56 loc) · 2.13 KB
/
p079.java
File metadata and controls
70 lines (56 loc) · 2.13 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
/*
* Solution to Project Euler problem 79
* Copyright (c) Project Nayuki. All rights reserved.
*
* https://www.nayuki.io/page/project-euler-solutions
* https://github.com/nayuki/Project-Euler-solutions
*/
public final class p079 implements EulerSolution {
public static void main(String[] args) {
System.out.println(new p079().run());
}
private static String[] SUBSEQS = {"319", "680", "180", "690", "129", "620", "762", "689", "762", "318", "368", "710", "720", "710", "629", "168", "160", "689", "716", "731", "736", "729", "316", "729", "729", "710", "769", "290", "719", "680", "318", "389", "162", "289", "162", "718", "729", "319", "790", "680", "890", "362", "319", "760", "316", "729", "380", "319", "728", "716"};
private char[] packedSubseqs;
public String run() {
// Preprocessing
packedSubseqs = new char[SUBSEQS.length * 3];
for (int i = 0; i < packedSubseqs.length; i++)
packedSubseqs[i] = SUBSEQS[i / 3].charAt(i % 3);
// Try ascending lengths
for (int len = 3; len <= 10; len++) {
int end = Library.pow(10, len);
for (int guess = 0; guess < end; guess++) {
char[] guessChars = toChars(guess, len);
if (isConsistent(guessChars))
return new String(guessChars);
}
}
throw new RuntimeException("Not found");
}
private boolean isConsistent(char[] guess) {
// For each string 's' in SUBSEQS, test if 's' is a subsequence of 'guess'
for (int i = 0; i < packedSubseqs.length; i += 3) {
int j = 0; // Index in 's'
for (int k = 0; k < guess.length && j < 3; k++) { // Index in 'guess'
if (guess[k] == packedSubseqs[i + j])
j++;
}
if (j < 3) // Not all characters consumed, fail
return false;
}
return true;
}
// Converts integer to string with zero padding, in little endian.
// Since we're trying all combinations, the order doesn't matter.
private static char[] toChars(int n, int len) {
char[] result = new char[len];
int i = 0;
for (; i < result.length; i++, n /= 10)
result[i] = (char)('0' + (n % 10));
if (n != 0)
throw new IllegalArgumentException();
for (; i < result.length; i++)
result[i] = '0';
return result;
}
}