forked from sherxon/AlgoDS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiskDefragmentation_14.java
More file actions
82 lines (73 loc) · 2.37 KB
/
Copy pathDiskDefragmentation_14.java
File metadata and controls
82 lines (73 loc) · 2.37 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
79
80
81
82
package adventofcode;
import java.math.BigInteger;
import java.util.Arrays;
/**
* Why Did you create this class? what does it do?
*/
public class DiskDefragmentation_14 {
public static void main(String[] args) {
// System.out.println(solve("nbysizxe"));
System.out.println(solve2("nbysizxe"));
}
private static int solve(String s) {
if (s == null || s.length() == 0)
return 0;
int count = 0;
for (int i = 0; i < 128; i++) {
String row = s + "-" + i;
String hash = KnotHash_10.calculateKnotHash(row);
for (int j = 0; j < hash.length(); j++) {
count += hexBitCount(String.valueOf(hash.charAt(j)));
}
}
return count;
}
private static int solve2(String s) {
if (s == null || s.length() == 0)
return 0;
int count = 0;
int[][] a = new int[128][128];
for (int i = 0; i < 128; i++) {
String row = s + "-" + i;
String hash = KnotHash_10.calculateKnotHash(row);
StringBuilder builder = new StringBuilder();
for (int j = 0; j < hash.length(); j++) {
String bin = hexToBin(String.valueOf(hash.charAt(j)));
builder.append(bin);
}
for (int k = 0; k < builder.length(); k++) {
a[i][k] = builder.charAt(k) - '0';
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == 1) {
count++;
removeRegion(a, i, j);
}
}
}
return count;
}
private static void removeRegion(int[][] a, int i, int j) {
if (i < 0 || j < 0 || i >= a.length || j >= a.length)
return;
if (a[i][j] == 0)
return;
a[i][j] = 0;
removeRegion(a, i + 1, j);
removeRegion(a, i - 1, j);
removeRegion(a, i, j + 1);
removeRegion(a, i, j - 1);
}
static int hexBitCount(String s) {
return new BigInteger(s, 16).bitCount();
}
static String hexToBin(String s) {
StringBuilder ss = new StringBuilder(new BigInteger(s, 16).toString(2));
for (int i = ss.length(); i < 4; i++) {
ss.insert(0, "0");
}
return ss.toString();
}
}