@cubingcenter/scrambler 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +2 -0
  2. package/dist/puzzles/cube2/solver/search.d.ts.map +1 -1
  3. package/dist/puzzles/cube2/solver/search.js +3 -3
  4. package/dist/puzzles/cube2/solver/tables.d.ts +6 -0
  5. package/dist/puzzles/cube2/solver/tables.d.ts.map +1 -1
  6. package/dist/puzzles/cube2/solver/tables.js +16 -2
  7. package/dist/puzzles/cube3/index.d.ts +1 -0
  8. package/dist/puzzles/cube3/index.d.ts.map +1 -1
  9. package/dist/puzzles/cube3/moves.d.ts.map +1 -1
  10. package/dist/puzzles/cube3/moves.js +104 -18
  11. package/dist/puzzles/cube3/scrambler.d.ts +16 -1
  12. package/dist/puzzles/cube3/scrambler.d.ts.map +1 -1
  13. package/dist/puzzles/cube3/scrambler.js +1 -1
  14. package/dist/puzzles/cube3/solver/browser-loader.js +6 -2
  15. package/dist/puzzles/cube3/solver/index.d.ts +5 -3
  16. package/dist/puzzles/cube3/solver/index.d.ts.map +1 -1
  17. package/dist/puzzles/cube3/solver/index.js +2 -1
  18. package/dist/puzzles/cube3/solver/node-loader.js +9 -2
  19. package/dist/puzzles/cube3/solver/phase1.d.ts +18 -0
  20. package/dist/puzzles/cube3/solver/phase1.d.ts.map +1 -1
  21. package/dist/puzzles/cube3/solver/phase1.js +132 -14
  22. package/dist/puzzles/cube3/solver/phase2.d.ts +47 -0
  23. package/dist/puzzles/cube3/solver/phase2.d.ts.map +1 -1
  24. package/dist/puzzles/cube3/solver/phase2.js +236 -66
  25. package/dist/puzzles/cube3/solver/search-utils.d.ts +1 -1
  26. package/dist/puzzles/cube3/solver/search-utils.d.ts.map +1 -1
  27. package/dist/puzzles/cube3/solver/symmetry.d.ts +24 -0
  28. package/dist/puzzles/cube3/solver/symmetry.d.ts.map +1 -0
  29. package/dist/puzzles/cube3/solver/symmetry.js +74 -0
  30. package/dist/puzzles/cube3/solver/tables.d.ts +6 -1
  31. package/dist/puzzles/cube3/solver/tables.d.ts.map +1 -1
  32. package/dist/puzzles/cube3/validation.d.ts.map +1 -1
  33. package/dist/puzzles/cube3/validation.js +15 -7
  34. package/dist/puzzles/cube4/index.d.ts +3 -2
  35. package/dist/puzzles/cube4/index.d.ts.map +1 -1
  36. package/dist/puzzles/cube4/index.js +2 -2
  37. package/dist/puzzles/cube4/moves.d.ts +5 -0
  38. package/dist/puzzles/cube4/moves.d.ts.map +1 -1
  39. package/dist/puzzles/cube4/moves.js +120 -11
  40. package/dist/puzzles/cube4/reduction/browser-loader.d.ts +3 -0
  41. package/dist/puzzles/cube4/reduction/browser-loader.d.ts.map +1 -1
  42. package/dist/puzzles/cube4/reduction/browser-loader.js +34 -3
  43. package/dist/puzzles/cube4/reduction/center2.d.ts +20 -3
  44. package/dist/puzzles/cube4/reduction/center2.d.ts.map +1 -1
  45. package/dist/puzzles/cube4/reduction/center2.js +53 -9
  46. package/dist/puzzles/cube4/reduction/edge3.d.ts +4 -0
  47. package/dist/puzzles/cube4/reduction/edge3.d.ts.map +1 -1
  48. package/dist/puzzles/cube4/reduction/edge3.js +23 -3
  49. package/dist/puzzles/cube4/reduction/generated/c3_pair_dist.bin +1 -0
  50. package/dist/puzzles/cube4/reduction/generated/center2-manifest.json +36 -0
  51. package/dist/puzzles/cube4/reduction/generated/center2-pruning-wide.bin +1 -0
  52. package/dist/puzzles/cube4/reduction/generated/hc-distances.bin +1 -0
  53. package/dist/puzzles/cube4/reduction/generated/hc-manifest.json +38 -0
  54. package/dist/puzzles/cube4/reduction/generated/hc-move.bin +0 -0
  55. package/dist/puzzles/cube4/reduction/hc-pdb.d.ts +50 -0
  56. package/dist/puzzles/cube4/reduction/hc-pdb.d.ts.map +1 -0
  57. package/dist/puzzles/cube4/reduction/hc-pdb.js +202 -0
  58. package/dist/puzzles/cube4/reduction/node-loader.d.ts +5 -0
  59. package/dist/puzzles/cube4/reduction/node-loader.d.ts.map +1 -1
  60. package/dist/puzzles/cube4/reduction/node-loader.js +48 -8
  61. package/dist/puzzles/cube4/reduction/pairing-coordinate.js +5 -5
  62. package/dist/puzzles/cube4/reduction/phase3-search.d.ts +111 -5
  63. package/dist/puzzles/cube4/reduction/phase3-search.d.ts.map +1 -1
  64. package/dist/puzzles/cube4/reduction/phase3-search.js +341 -22
  65. package/dist/puzzles/cube4/reduction/solve.d.ts +112 -1
  66. package/dist/puzzles/cube4/reduction/solve.d.ts.map +1 -1
  67. package/dist/puzzles/cube4/reduction/solve.js +920 -181
  68. package/dist/puzzles/cube4/scrambler.d.ts +105 -4
  69. package/dist/puzzles/cube4/scrambler.d.ts.map +1 -1
  70. package/dist/puzzles/cube4/scrambler.js +216 -166
  71. package/dist/puzzles/cube4/state.d.ts.map +1 -1
  72. package/dist/puzzles/cube4/state.js +4 -1
  73. package/dist/puzzles/pyraminx/solver/search.d.ts.map +1 -1
  74. package/dist/puzzles/pyraminx/solver/search.js +3 -6
  75. package/dist/puzzles/pyraminx/solver/tables.d.ts +6 -0
  76. package/dist/puzzles/pyraminx/solver/tables.d.ts.map +1 -1
  77. package/dist/puzzles/pyraminx/solver/tables.js +17 -0
  78. package/dist/puzzles/skewb/solver/search.js +3 -3
  79. package/dist/puzzles/skewb/solver/tables.d.ts +6 -0
  80. package/dist/puzzles/skewb/solver/tables.d.ts.map +1 -1
  81. package/dist/puzzles/skewb/solver/tables.js +17 -0
  82. package/dist-cjs/puzzles/cube2/solver/search.js +2 -2
  83. package/dist-cjs/puzzles/cube2/solver/tables.js +17 -3
  84. package/dist-cjs/puzzles/cube3/moves.js +104 -18
  85. package/dist-cjs/puzzles/cube3/scrambler.js +1 -1
  86. package/dist-cjs/puzzles/cube3/solver/browser-loader.js +6 -2
  87. package/dist-cjs/puzzles/cube3/solver/index.js +8 -1
  88. package/dist-cjs/puzzles/cube3/solver/node-loader.js +9 -2
  89. package/dist-cjs/puzzles/cube3/solver/phase1.js +133 -14
  90. package/dist-cjs/puzzles/cube3/solver/phase2.js +233 -63
  91. package/dist-cjs/puzzles/cube3/solver/symmetry.js +80 -0
  92. package/dist-cjs/puzzles/cube3/validation.js +15 -7
  93. package/dist-cjs/puzzles/cube4/index.js +3 -1
  94. package/dist-cjs/puzzles/cube4/moves.js +121 -11
  95. package/dist-cjs/puzzles/cube4/reduction/browser-loader.js +34 -3
  96. package/dist-cjs/puzzles/cube4/reduction/center2.js +54 -9
  97. package/dist-cjs/puzzles/cube4/reduction/edge3.js +24 -3
  98. package/dist-cjs/puzzles/cube4/reduction/generated/c3_pair_dist.bin +1 -0
  99. package/dist-cjs/puzzles/cube4/reduction/generated/center2-manifest.json +36 -0
  100. package/dist-cjs/puzzles/cube4/reduction/generated/center2-pruning-wide.bin +1 -0
  101. package/dist-cjs/puzzles/cube4/reduction/generated/hc-distances.bin +1 -0
  102. package/dist-cjs/puzzles/cube4/reduction/generated/hc-manifest.json +38 -0
  103. package/dist-cjs/puzzles/cube4/reduction/generated/hc-move.bin +0 -0
  104. package/dist-cjs/puzzles/cube4/reduction/hc-pdb.js +213 -0
  105. package/dist-cjs/puzzles/cube4/reduction/node-loader.js +48 -8
  106. package/dist-cjs/puzzles/cube4/reduction/pairing-coordinate.js +5 -5
  107. package/dist-cjs/puzzles/cube4/reduction/phase3-search.js +343 -23
  108. package/dist-cjs/puzzles/cube4/reduction/solve.js +918 -173
  109. package/dist-cjs/puzzles/cube4/scrambler.js +214 -163
  110. package/dist-cjs/puzzles/cube4/state.js +4 -1
  111. package/dist-cjs/puzzles/pyraminx/solver/search.js +2 -5
  112. package/dist-cjs/puzzles/pyraminx/solver/tables.js +18 -1
  113. package/dist-cjs/puzzles/skewb/solver/search.js +2 -2
  114. package/dist-cjs/puzzles/skewb/solver/tables.js +18 -1
  115. package/package.json +14 -5
@@ -3,16 +3,107 @@
3
3
  * (phase 4), returning the move sequence that solves the given state.
4
4
  * The scramble for a sampled state is the inverted solution.
5
5
  */
6
- import { applyCube4Algorithm, invertCube4Algorithm } from "../moves.js";
7
- import { center1Mask, getCenter1Distance, applyCenter1Move, CENTER1_MOVES } from "./center1.js";
8
- import { center2Bridge, isCenter2Goal, CENTER2_MOVES, CENTER2_SEARCH_MOVES, CENTER2_RL_STATES } from "./center2.js";
6
+ import { applyCube4Algorithm, invertCube4Algorithm, simplifyCube4Algorithm } from "../moves.js";
7
+ import { center1Mask, getCenter1Distance, applyCenter1Move, CENTER1_MOVES, CENTER1_GOAL_MASKS } from "./center1.js";
8
+ import { center2Bridge, getWingMoveMaps, isCenter2Goal, CENTER2_MOVES, CENTER2_SEARCH_MOVES, CENTER2_SEARCH_MOVES_WIDE, CENTER2_RL_STATES } from "./center2.js";
9
9
  import { encodeCenter3 } from "./center3.js";
10
- import { encodePairingState } from "./pairing-coordinate.js";
10
+ import { encodePairingState, hasPairingTransversal } from "./pairing-coordinate.js";
11
+ import { encodeHcPdb } from "./hc-pdb.js";
11
12
  import { getSymTables, getMvSymFrom } from "./edge3.js";
12
13
  import { FastPhase3Solver } from "./phase3-search.js";
13
- import { toCube3State } from "./phase4.js";
14
- import { Cube3Phase2SearchError } from "../../cube3/solver/index.js";
14
+ import { checkCube4Reduction, toCube3State } from "./phase4.js";
15
+ import { encodeCornerOrientation, encodeEdgeOrientation, encodeUdSlice } from "../../cube3/solver/coordinates.js";
15
16
  import { createSolvedCube4State } from "../state.js";
17
+ function mulberry32(seed) {
18
+ let a = seed >>> 0;
19
+ return () => {
20
+ a |= 0;
21
+ a = (a + 0x6d2b79f5) | 0;
22
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
23
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
24
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
25
+ };
26
+ }
27
+ function hashCube4State(state) {
28
+ let h = 0x811c9dc5;
29
+ for (const arr of [state.cp, state.co, state.wp, state.centers]) {
30
+ for (let i = 0; i < arr.length; i++) {
31
+ h ^= arr[i] & 0xff;
32
+ h = Math.imul(h, 0x01000193);
33
+ }
34
+ }
35
+ return h >>> 0;
36
+ }
37
+ /**
38
+ * Fisher-Yates order, or identity when rng is null (restarts=1 keeps the
39
+ * legacy deterministic traversal bit-identical).
40
+ */
41
+ function restartOrder(n, rng) {
42
+ const order = Array.from({ length: n }, (_, i) => i);
43
+ if (rng) {
44
+ for (let i = n - 1; i > 0; i--) {
45
+ const j = Math.floor(rng() * (i + 1));
46
+ const t = order[i];
47
+ order[i] = order[j];
48
+ order[j] = t;
49
+ }
50
+ }
51
+ return order;
52
+ }
53
+ /**
54
+ * Fisher-Yates within equal-key runs of a key-sorted array, so the
55
+ * caller's sorted early-break (`value > length123`) stays valid.
56
+ */
57
+ function shuffleTies(arr, key, rng) {
58
+ if (!rng)
59
+ return;
60
+ let run = 0;
61
+ for (let i = 1; i <= arr.length; i++) {
62
+ if (i < arr.length && key(arr[i]) === key(arr[run]))
63
+ continue;
64
+ for (let k = i - 1; k > run; k--) {
65
+ const j = run + Math.floor(rng() * (k - run + 1));
66
+ const t = arr[k];
67
+ arr[k] = arr[j];
68
+ arr[j] = t;
69
+ }
70
+ run = i;
71
+ }
72
+ }
73
+ function getCube3Phase1Heuristic(cube3State, tables) {
74
+ const co = encodeCornerOrientation(cube3State);
75
+ const eo = encodeEdgeOrientation(cube3State);
76
+ const ud = encodeUdSlice(cube3State);
77
+ const combined = (co << 11) + eo;
78
+ const coeo = (tables.pruningTables.cornerOrientationEdgeOrientation.values[combined >> 1] >>
79
+ ((combined & 1) << 2)) &
80
+ 0x0f;
81
+ const udd = (tables.pruningTables.udSlice.values[ud >> 1] >> ((ud & 1) << 2)) & 0x0f;
82
+ return Math.max(coeo, udd);
83
+ }
84
+ function getTriAxialCube3Heuristic(standardReduced, tables) {
85
+ const s0 = toCube3State(standardReduced);
86
+ if (!s0)
87
+ return 99;
88
+ let minH = getCube3Phase1Heuristic(s0, tables);
89
+ if (minH <= 3)
90
+ return minH;
91
+ const sx = toCube3State(applyCubeRotation(standardReduced, ["x"]));
92
+ if (sx) {
93
+ const hx = getCube3Phase1Heuristic(sx, tables);
94
+ if (hx < minH)
95
+ minH = hx;
96
+ if (minH <= 3)
97
+ return minH;
98
+ }
99
+ const sz = toCube3State(applyCubeRotation(standardReduced, ["z"]));
100
+ if (sz) {
101
+ const hz = getCube3Phase1Heuristic(sz, tables);
102
+ if (hz < minH)
103
+ minH = hz;
104
+ }
105
+ return minH;
106
+ }
16
107
  function cornerPermutationParity(cp) {
17
108
  let parity = 0;
18
109
  const seen = new Array(8).fill(false);
@@ -30,13 +121,48 @@ function cornerPermutationParity(cp) {
30
121
  }
31
122
  return parity;
32
123
  }
124
+ /**
125
+ * Computes the spatial determinant (+1 for valid 3D rotations, -1 for reflections)
126
+ * of the 3 axes defined by the center colors on faces U, R, F.
127
+ */
128
+ function getOrientationDet(uColor, rColor, fColor) {
129
+ const vec = (c) => {
130
+ switch (c) {
131
+ case 0: return [0, 0, 1];
132
+ case 3: return [0, 0, -1];
133
+ case 1: return [1, 0, 0];
134
+ case 4: return [-1, 0, 0];
135
+ case 2: return [0, 1, 0];
136
+ case 5: return [0, -1, 0];
137
+ default: return [0, 0, 0];
138
+ }
139
+ };
140
+ const [ux, uy, uz] = vec(uColor);
141
+ const [rx, ry, rz] = vec(rColor);
142
+ const [fx, fy, fz] = vec(fColor);
143
+ const cx = ry * fz - rz * fy;
144
+ const cy = rz * fx - rx * fz;
145
+ const cz = rx * fy - ry * fx;
146
+ return cx * ux + cy * uy + cz * uz;
147
+ }
148
+ function axisDet(uAxis, rAxis, fAxis) {
149
+ if ((uAxis === 0 && rAxis === 1 && fAxis === 2) ||
150
+ (uAxis === 1 && rAxis === 2 && fAxis === 0) ||
151
+ (uAxis === 2 && rAxis === 0 && fAxis === 1)) {
152
+ return 1;
153
+ }
154
+ return -1;
155
+ }
33
156
  const ROT_MOVES = {
34
157
  "x": ["Rw", "Lw'"],
35
158
  "y": ["Uw", "Dw'"],
36
159
  "z": ["Fw", "Bw'"],
37
160
  "x'": ["Rw'", "Lw"],
38
161
  "y'": ["Uw'", "Dw"],
39
- "z'": ["Fw'", "Bw"]
162
+ "z'": ["Fw'", "Bw"],
163
+ "x2": ["Rw2", "Lw2"],
164
+ "y2": ["Uw2", "Dw2"],
165
+ "z2": ["Fw2", "Bw2"]
40
166
  };
41
167
  const VALID_24_ORIENTATIONS = (() => {
42
168
  const map = new Map();
@@ -63,12 +189,16 @@ const ROT_MAP = {
63
189
  "y": { "U": "U", "R": "F", "F": "L", "D": "D", "L": "B", "B": "R" },
64
190
  "y'": { "U": "U", "R": "B", "F": "R", "D": "D", "L": "F", "B": "L" },
65
191
  "z": { "U": "R", "R": "D", "F": "F", "D": "L", "L": "U", "B": "B" },
66
- "z'": { "U": "L", "R": "U", "F": "F", "D": "R", "L": "D", "B": "B" }
192
+ "z'": { "U": "L", "R": "U", "F": "F", "D": "R", "L": "D", "B": "B" },
193
+ "x2": { "U": "D", "R": "R", "F": "B", "D": "U", "L": "L", "B": "F" },
194
+ "y2": { "U": "U", "R": "L", "F": "B", "D": "D", "L": "R", "B": "F" },
195
+ "z2": { "U": "D", "R": "L", "F": "F", "D": "U", "L": "R", "B": "B" }
67
196
  };
68
197
  const INVERT_ROT = {
69
198
  "x": "x'", "x'": "x",
70
199
  "y": "y'", "y'": "y",
71
- "z": "z'", "z'": "z"
200
+ "z": "z'", "z'": "z",
201
+ "x2": "x2", "y2": "y2", "z2": "z2"
72
202
  };
73
203
  function rotateMove(move, rot) {
74
204
  const map = ROT_MAP[rot];
@@ -76,17 +206,22 @@ function rotateMove(move, rot) {
76
206
  const newFace = map[face];
77
207
  return (newFace + move.slice(1));
78
208
  }
79
- function rotateAlgorithm(alg, rotSeq) {
80
- let res = [...alg];
81
- for (const r of rotSeq) {
82
- res = res.map((m) => rotateMove(m, r));
83
- }
84
- return res;
209
+ export function rotateAlgorithm(alg, rotSeq) {
210
+ // Single pass over the algorithm (one allocation): applying the rotation
211
+ // sequence per move instead of re-mapping the whole array per rotation.
212
+ if (rotSeq.length === 0)
213
+ return [...alg];
214
+ return alg.map((move) => {
215
+ let current = move;
216
+ for (const rot of rotSeq)
217
+ current = rotateMove(current, rot);
218
+ return current;
219
+ });
85
220
  }
86
- function invertRotationSequence(rotSeq) {
221
+ export function invertRotationSequence(rotSeq) {
87
222
  return [...rotSeq].reverse().map((r) => INVERT_ROT[r]);
88
223
  }
89
- function applyCubeRotation(state, rotSeq) {
224
+ export function applyCubeRotation(state, rotSeq) {
90
225
  let s = state;
91
226
  for (const r of rotSeq) {
92
227
  s = applyCube4Algorithm(s, ROT_MOVES[r]);
@@ -116,196 +251,800 @@ function isCancelled(previous, current) {
116
251
  }
117
252
  return false;
118
253
  }
119
- function solveCenter1Diverse(centers, urf, tables, cap = 80) {
120
- const startMask = center1Mask(centers, urf);
121
- const solutions = [];
122
- const path = [];
123
- const minH = getCenter1Distance(startMask, tables);
124
- for (let maxD = minH; maxD <= minH + 1; maxD++) {
125
- const dfs = (mask, depth, lm) => {
126
- if (solutions.length >= cap)
127
- return true;
128
- const h = getCenter1Distance(mask, tables);
129
- if (h === 0) {
130
- solutions.push({
131
- moves: path.slice(0, depth).map((m) => CENTER1_MOVES[m]),
132
- length: depth
133
- });
134
- return false;
135
- }
136
- if (depth + h > maxD)
137
- return false;
138
- for (let m = 0; m < CENTER1_MOVES.length; m++) {
139
- if (lm >= 0 && Math.floor(lm / 3) === Math.floor(m / 3))
140
- continue;
141
- const next = applyCenter1Move(mask, tables.moveMaps, m);
142
- path[depth] = m;
143
- if (dfs(next, depth + 1, m))
144
- return true;
145
- }
146
- return false;
147
- };
148
- if (dfs(startMask, 0, -1))
254
+ // Precomputed phase-2 cancellation matrix over CENTER2_SEARCH_MOVES: the
255
+ // search evaluates isCancelled per child per node (~0.3M nodes × 23 moves
256
+ // per attempt with regex + Map lookups); the table makes it one boolean
257
+ // read with a bit-identical traversal.
258
+ export const P2_CANCEL = CENTER2_SEARCH_MOVES.map((previous) => CENTER2_SEARCH_MOVES.map((current) => isCancelled(previous, current)));
259
+ // Same over the wide 28-move set (used when `center2Wide` is set).
260
+ const P2_CANCEL_WIDE = CENTER2_SEARCH_MOVES_WIDE.map((previous) => CENTER2_SEARCH_MOVES_WIDE.map((current) => isCancelled(previous, current)));
261
+ const SKIP_AXIS_2 = new Int32Array(CENTER2_SEARCH_MOVES.length);
262
+ for (let i = 0; i < CENTER2_SEARCH_MOVES.length; i++) {
263
+ const m1 = CENTER2_SEARCH_MOVES[i];
264
+ const face1 = m1.replace(/2|'|w/g, "");
265
+ const isWide1 = m1.includes("w");
266
+ SKIP_AXIS_2[i] = CENTER2_SEARCH_MOVES.length;
267
+ for (let j = i + 1; j < CENTER2_SEARCH_MOVES.length; j++) {
268
+ const m2 = CENTER2_SEARCH_MOVES[j];
269
+ const face2 = m2.replace(/2|'|w/g, "");
270
+ const isWide2 = m2.includes("w");
271
+ if (face1 !== face2 || isWide1 !== isWide2) {
272
+ SKIP_AXIS_2[i] = j;
149
273
  break;
274
+ }
150
275
  }
151
- return solutions;
152
276
  }
153
277
  const phase3Solver = new FastPhase3Solver();
154
- /**
155
- * Solve a 4x4 state with the reduction solver + the cube3 two-phase finish.
156
- * `solveCube3` is injected (the cube3 solver loads its tables lazily).
157
- */
158
- export async function solveCube4State(state, tables, solveCube3) {
278
+ /** Temporary instrumentation for F2 goal statistics (CUBE4_F2_STATS=1). */
279
+ export const f2Stats = { goals: 0, transversalPass: 0, axisRejects: 0, minTransversalL2: 99, minChiralL2: 99 };
280
+ export function resetF2Stats() {
281
+ f2Stats.goals = 0;
282
+ f2Stats.transversalPass = 0;
283
+ f2Stats.axisRejects = 0;
284
+ f2Stats.minTransversalL2 = 99;
285
+ f2Stats.minChiralL2 = 99;
286
+ }
287
+ /** Trigger rate for the stagnationCut early-stop (checks vs actual cuts). */
288
+ export const stagnationStats = { checks: 0, cuts: 0 };
289
+ export function resetStagnationStats() {
290
+ stagnationStats.checks = 0;
291
+ stagnationStats.cuts = 0;
292
+ }
293
+ export async function solveCube4State(state, tables, solveCube3, options) {
294
+ // NOTE: no wall-clock deadline inside the search — all loops are bounded
295
+ // by deterministic work caps (node counts, candidate counts, length
296
+ // caps), so the same state always takes the same path. The caller keeps
297
+ // its own backstop (`timeoutMs` handled at the call site).
159
298
  const sym = getSymTables();
160
- const cornerParity = cornerPermutationParity(state.cp);
161
- const p1Sols = solveCenter1Diverse(state.centers, 0, tables.center1, 80);
162
- p1Sols.sort((a, b) => a.moves.length - b.moves.length);
163
- const minP1 = p1Sols[0]?.moves.length ?? 0;
164
- const candidates = [];
165
- const moveLog = new Array(25);
166
- function searchPhase2(c, r, maxl, lm, depth, bridgeState, p1Moves) {
167
- if (isCenter2Goal(c, r)) {
168
- if (maxl === 0) {
169
- const moves2 = moveLog.slice(0, depth).map((m) => CENTER2_MOVES[m]);
170
- const s2 = applyCube4Algorithm(bridgeState, moves2);
171
- const pairing = encodePairingState(s2.wp);
172
- if (pairing) {
173
- const eXc = (pairing.parity ^ cornerParity);
174
- const ct3 = encodeCenter3(s2, eXc).coordinate;
175
- const cdist = tables.center3.pruning[ct3];
176
- if (cdist !== 0xff && cdist !== undefined) {
177
- const symIdx = getMvSymFrom(pairing.edge, pairing.edge, 20, sym.sym2Raw, sym.sym2Mask, sym.raw2Sym, sym.mvrot, sym.mvroto);
178
- const edist = (tables.edge3.distances[(symIdx >> 3) >> 1] >>
179
- (((symIdx >> 3) & 1) * 4)) &
180
- 0x0f;
181
- candidates.push({
182
- moves12: [...p1Moves, ...moves2],
183
- length12: p1Moves.length + moves2.length,
184
- ct3,
185
- cdist,
186
- edge: pairing.edge,
187
- edist,
188
- value: p1Moves.length + moves2.length + Math.max(cdist, edist),
189
- state: s2
299
+ phase3Solver.resetEpochNodes();
300
+ const totalRestarts = Math.max(1, Math.floor(options?.restarts ?? 1));
301
+ // Cross-restart work accumulators (reported in nodes/timings).
302
+ let accP2 = 0;
303
+ let accF3calls = 0;
304
+ let accF1Ms = 0;
305
+ let accF2Ms = 0;
306
+ let accF3Ms = 0;
307
+ let accFinishMs = 0;
308
+ let accPolishMs = 0;
309
+ const runOnce = async (rng) => {
310
+ const tR0 = performance.now();
311
+ const p1Sols = [];
312
+ let minOverallH = 99;
313
+ const urfDistances = [];
314
+ for (const urf of [0, 1, 2]) {
315
+ const mask = center1Mask(state.centers, urf);
316
+ const h = getCenter1Distance(mask, tables.center1);
317
+ urfDistances.push(h);
318
+ if (h < minOverallH)
319
+ minOverallH = h;
320
+ }
321
+ const path = [];
322
+ const p1Extra = options?.phase1ExtraDepths ?? 3;
323
+ const p1Cap = options?.phase1Cap ?? 400;
324
+ // Per-restart DFS traversal order (identity when rng is null).
325
+ const p1Order = restartOrder(CENTER1_MOVES.length, rng);
326
+ for (let maxD = minOverallH; maxD <= minOverallH + p1Extra; maxD++) {
327
+ for (const urf of [0, 1, 2]) {
328
+ const minH = urfDistances[urf];
329
+ if (maxD < minH)
330
+ continue;
331
+ const mask = center1Mask(state.centers, urf);
332
+ let axisCount = 0;
333
+ const dfs = (m, depth, lm) => {
334
+ if (axisCount >= p1Cap)
335
+ return true;
336
+ const h = getCenter1Distance(m, tables.center1);
337
+ if (h === 0) {
338
+ let rotAlign = [];
339
+ if (m === CENTER1_GOAL_MASKS.rl) {
340
+ rotAlign = [];
341
+ }
342
+ else if (m === CENTER1_GOAL_MASKS.ud) {
343
+ rotAlign = ["z"];
344
+ }
345
+ else if (m === CENTER1_GOAL_MASKS.fb) {
346
+ rotAlign = ["y'"];
347
+ }
348
+ else {
349
+ return false;
350
+ }
351
+ axisCount++;
352
+ p1Sols.push({
353
+ moves: path.slice(0, depth).map((mv) => CENTER1_MOVES[mv]),
354
+ length: depth,
355
+ rotAlign
190
356
  });
191
- if (candidates.length >= 60)
357
+ return false;
358
+ }
359
+ if (depth + h > maxD)
360
+ return false;
361
+ for (let mi = 0; mi < CENTER1_MOVES.length; mi++) {
362
+ const mv = p1Order[mi];
363
+ if (lm >= 0 && Math.floor(lm / 3) === Math.floor(mv / 3))
364
+ continue;
365
+ const next = applyCenter1Move(m, tables.center1.moveMaps, mv);
366
+ path[depth] = mv;
367
+ if (dfs(next, depth + 1, mv))
192
368
  return true;
193
369
  }
370
+ return false;
371
+ };
372
+ dfs(mask, 0, -1);
373
+ }
374
+ if (p1Sols.length >= p1Cap)
375
+ break;
376
+ }
377
+ p1Sols.sort((a, b) => a.moves.length - b.moves.length);
378
+ const minP1 = p1Sols[0]?.moves.length ?? 0;
379
+ const tF1End = performance.now();
380
+ const candidates = [];
381
+ const moveLog = new Array(25);
382
+ // Incremental wing tracking stack for phase-2 goal transversal checks:
383
+ // avoids full 6-7 move replaying from scratch across hundreds of thousands of candidate goals.
384
+ const wpStack = Array.from({ length: 24 }, () => new Uint8Array(24));
385
+ let validWpDepth = 0;
386
+ const wingMaps = getWingMoveMaps();
387
+ /**
388
+ * Anti-hang work cap for the phase-2 search (successful attempts use
389
+ * ~0.1-0.3M nodes; this only aborts pathological explorations).
390
+ * Exceeding it degrades gracefully: the call returns false and the
391
+ * remaining (prep, length2) combinations still run.
392
+ */
393
+ const deep = options?.deep === true;
394
+ // Wide phase-2 set (28 moves) + its pruning table. Both sets are
395
+ // prefixes of CENTER2_MOVES, so search indices stay valid move-table
396
+ // indices in either mode.
397
+ const c2Wide = options?.center2Wide === true;
398
+ const C2_SEARCH = c2Wide ? CENTER2_SEARCH_MOVES_WIDE : CENTER2_SEARCH_MOVES;
399
+ const C2_CANCEL = c2Wide ? P2_CANCEL_WIDE : P2_CANCEL;
400
+ // Per-restart child order (identity when rng is null). Entries stay
401
+ // original move-table indices, so all table lookups are unaffected.
402
+ const p2Order = restartOrder(C2_SEARCH.length, rng);
403
+ let c2pruning = tables.center2.pruning;
404
+ if (c2Wide) {
405
+ if (!tables.center2.pruningWide) {
406
+ throw new Error("4x4 solve: center2Wide requested but pruningWide tables are not loaded — regenerate center2 tables.");
407
+ }
408
+ c2pruning = tables.center2.pruningWide;
409
+ }
410
+ const P2_MAX_NODES = deep ? 24_000_000 : 8_000_000;
411
+ // Smaller pool + shorter extension (was 180/100/14/12 on the fast path):
412
+ // the deep length2 levels are where F2 tails burn. Validated on a 44-state
413
+ // corpus: -16% nodes, identical average length (one +1 in 44).
414
+ const CAND_CAP = deep ? 300 : 120;
415
+ const CAND_MIN = deep ? 180 : 35;
416
+ const P2_MAX_ABS = deep ? 18 : 14;
417
+ const P2_MAX_MIN = deep ? 16 : 10;
418
+ const L123_CAP = options?.maxReductionLen
419
+ ? Math.min(options.maxReductionLen, deep ? 48 : 45)
420
+ : (deep ? 48 : 45);
421
+ const EXT_MX = deep ? 20 : 16;
422
+ let p2nodes = 0;
423
+ let f3calls = 0;
424
+ function searchPhase2(c, r, maxl, lm, depth, bridgeState, prep) {
425
+ p2nodes++;
426
+ if (p2nodes > P2_MAX_NODES)
427
+ return false;
428
+ if (isCenter2Goal(c, r)) {
429
+ if (maxl === 0) {
430
+ while (validWpDepth < depth) {
431
+ const m = moveLog[validWpDepth];
432
+ const base = m * 24;
433
+ const src = wpStack[validWpDepth];
434
+ const dst = wpStack[validWpDepth + 1];
435
+ for (let i = 0; i < 24; i++)
436
+ dst[i] = src[wingMaps[base + i]];
437
+ validWpDepth++;
438
+ }
439
+ const goalWp = wpStack[depth];
440
+ if (process.env.CUBE4_F2_STATS === "1")
441
+ f2Stats.goals++;
442
+ if (!hasPairingTransversal(goalWp))
443
+ return false;
444
+ if (process.env.CUBE4_F2_STATS === "1")
445
+ f2Stats.transversalPass++;
446
+ const moves2 = moveLog.slice(0, depth).map((m) => CENTER2_MOVES[m]);
447
+ const s2 = applyCube4Algorithm(bridgeState, moves2);
448
+ const uAxis = s2.centers[0] % 3;
449
+ const rAxis = s2.centers[4] % 3;
450
+ const fAxis = s2.centers[8] % 3;
451
+ if (process.env.CUBE4_F2_STATS === "1") {
452
+ if (depth < f2Stats.minTransversalL2)
453
+ f2Stats.minTransversalL2 = depth;
454
+ }
455
+ if (axisDet(uAxis, rAxis, fAxis) !== 1) {
456
+ if (process.env.CUBE4_F2_STATS === "1")
457
+ f2Stats.axisRejects++;
458
+ return false;
459
+ }
460
+ if (process.env.CUBE4_F2_STATS === "1") {
461
+ if (depth < f2Stats.minChiralL2)
462
+ f2Stats.minChiralL2 = depth;
463
+ }
464
+ const pairing = encodePairingState(s2.wp);
465
+ if (pairing) {
466
+ const s2CornerParity = cornerPermutationParity(s2.cp);
467
+ const eXc = (pairing.parity ^ s2CornerParity);
468
+ const ct3 = encodeCenter3(s2, eXc).coordinate;
469
+ const cdist = tables.center3.pruning[ct3];
470
+ if (cdist !== 0xff && cdist !== undefined) {
471
+ const symIdx = getMvSymFrom(pairing.edge, pairing.edge, 20, sym.sym2Raw, sym.sym2Mask, sym.raw2Sym, sym.mvrot, sym.mvroto);
472
+ const edist = tables.edge3.distances.length >= 31006080
473
+ ? tables.edge3.distances[symIdx >> 3]
474
+ : (tables.edge3.distances[(symIdx >> 3) >> 1] >>
475
+ (((symIdx >> 3) & 1) * 4)) &
476
+ 0x0f;
477
+ const moves2Remapped = prep.totalRot.length === 0
478
+ ? moves2
479
+ : rotateAlgorithm(moves2, invertRotationSequence(prep.totalRot));
480
+ const hcCoord = tables.hc ? tables.hc.index[encodeHcPdb(s2.centers)] : -1;
481
+ const hcRaw = hcCoord >= 0 && tables.hc ? tables.hc.distances[hcCoord] : 0;
482
+ const hdist = hcRaw === 0x0f ? 0 : hcRaw;
483
+ let pdist = 0;
484
+ let pdistHigh = 0;
485
+ if (tables.c3PairDist) {
486
+ const c3Base = ct3 * 144;
487
+ for (let s = 0; s < 12; s++) {
488
+ const idx = c3Base + s * 12 + pairing.edge[s];
489
+ const d = (idx & 1) === 0 ? (tables.c3PairDist[idx >> 1] & 0x0f) : (tables.c3PairDist[idx >> 1] >> 4);
490
+ if (d > pdist)
491
+ pdist = d;
492
+ if (d >= 8)
493
+ pdistHigh++;
494
+ }
495
+ }
496
+ const cand = {
497
+ moves12: [...prep.prefix, ...moves2Remapped],
498
+ length12: prep.prefix.length + moves2.length,
499
+ ct3,
500
+ cdist,
501
+ edge: pairing.edge,
502
+ edist,
503
+ hdist,
504
+ pdist,
505
+ hcCoord,
506
+ rotCost: 0,
507
+ value: prep.prefix.length + moves2.length + Math.max(cdist, edist, hdist, pdist) + (pdistHigh >= 4 ? 2 : (pdistHigh >= 2 ? 1 : 0)),
508
+ state: s2,
509
+ p1: prep.p1,
510
+ totalRot: prep.totalRot
511
+ };
512
+ if (candidates.length < CAND_CAP) {
513
+ candidates.push(cand);
514
+ if (candidates.length === CAND_CAP) {
515
+ candidates.sort((a, b) => a.value - b.value);
516
+ }
517
+ }
518
+ else if (cand.value < candidates[candidates.length - 1].value) {
519
+ candidates[candidates.length - 1] = cand;
520
+ for (let j = candidates.length - 1; j > 0 && candidates[j].value < candidates[j - 1].value; j--) {
521
+ const tmp = candidates[j];
522
+ candidates[j] = candidates[j - 1];
523
+ candidates[j - 1] = tmp;
524
+ }
525
+ }
526
+ p1CandCount++;
527
+ const maxP1Cand = options?.p1CandCap !== undefined ? options.p1CandCap : (deep ? 96 : 64);
528
+ if (p1CandCount >= maxP1Cand)
529
+ return true;
530
+ }
531
+ }
194
532
  }
533
+ return false;
534
+ }
535
+ if (maxl === 0)
536
+ return false;
537
+ const c2ctMove = tables.center2.ctMove;
538
+ const c2rlMove = tables.center2.rlMove;
539
+ const c2RowC = c * CENTER2_MOVES.length;
540
+ const c2RowR = r * CENTER2_MOVES.length;
541
+ for (let mi = 0; mi < C2_SEARCH.length; mi++) {
542
+ const m = p2Order[mi];
543
+ if (lm >= 0 && C2_CANCEL[lm][m]) {
544
+ continue;
545
+ }
546
+ const nc = c2ctMove[c2RowC + m];
547
+ const nr = c2rlMove[c2RowR + m];
548
+ const prun = c2pruning[nc * CENTER2_RL_STATES + nr];
549
+ if (prun >= maxl) {
550
+ if (prun > maxl && rng === null && !c2Wide) {
551
+ mi = SKIP_AXIS_2[m] - 1;
552
+ }
553
+ continue;
554
+ }
555
+ moveLog[depth] = m;
556
+ if (validWpDepth > depth)
557
+ validWpDepth = depth;
558
+ if (searchPhase2(nc, nr, maxl - 1, m, depth + 1, bridgeState, prep))
559
+ return true;
195
560
  }
196
561
  return false;
197
562
  }
198
- if (maxl === 0)
199
- return false;
200
- for (let m = 0; m < CENTER2_SEARCH_MOVES.length; m++) {
201
- if (lm >= 0 && isCancelled(CENTER2_SEARCH_MOVES[lm], CENTER2_SEARCH_MOVES[m])) {
563
+ let p1CandCount = 0;
564
+ let MAX_P2 = 8;
565
+ // Phase-1 application + the phase-2 bridge depend only on the phase-1
566
+ // solution, not on the phase-2 target length: compute them once instead
567
+ // of redoing the work for every length12 iteration.
568
+ // Alignment is treated purely as a coordinate frame rotation (matching
569
+ // csTimer's sym frame remapping), adding 0 physical moves to prefix.
570
+ const preps = [];
571
+ for (const p1 of p1Sols) {
572
+ const s1 = applyCube4Algorithm(state, p1.moves);
573
+ const s1Aligned = p1.rotAlign.length === 0 ? s1 : applyCubeRotation(s1, p1.rotAlign);
574
+ const bridge = center2Bridge(s1Aligned);
575
+ if (!bridge)
202
576
  continue;
577
+ const totalRot = [...p1.rotAlign, ...bridge.rotation];
578
+ const prefix = p1.moves;
579
+ const prun = c2pruning[bridge.encoded.ct * CENTER2_RL_STATES + bridge.encoded.rl];
580
+ // Paired wings lookahead: check how many wings are already paired in bridge.state
581
+ let pairedWings = 0;
582
+ const wp = bridge.state.wp;
583
+ for (let pair = 0; pair < 12; pair++) {
584
+ if (Math.floor(wp[pair * 2] / 2) === Math.floor(wp[pair * 2 + 1] / 2)) {
585
+ pairedWings++;
586
+ }
203
587
  }
204
- const nc = tables.center2.ctMove[c * CENTER2_MOVES.length + m];
205
- const nr = tables.center2.rlMove[r * CENTER2_MOVES.length + m];
206
- const prun = tables.center2.pruning[nc * CENTER2_RL_STATES + nr];
207
- if (prun >= maxl)
208
- continue;
209
- moveLog[depth] = m;
210
- if (searchPhase2(nc, nr, maxl - 1, m, depth + 1, bridgeState, p1Moves))
211
- return true;
588
+ // Lookahead composite score: total estimated centers penalized by already-paired wings
589
+ const estCenters = prefix.length + prun;
590
+ const score = estCenters * 2 - Math.min(4, pairedWings);
591
+ preps.push({ p1, prefix, bridgeState: bridge.state, totalRot, ct: bridge.encoded.ct, rl: bridge.encoded.rl, prun, score });
212
592
  }
213
- return false;
214
- }
215
- let MAX_P2 = 8;
216
- do {
217
- OUTER: for (let length12 = minP1; length12 < minP1 + 14; length12++) {
218
- for (const p1 of p1Sols) {
219
- if (p1.moves.length > length12)
220
- break;
221
- const length2 = length12 - p1.moves.length;
222
- if (length2 > MAX_P2 || length2 < 0)
223
- continue;
224
- const s1 = applyCube4Algorithm(state, p1.moves);
225
- const bridge = center2Bridge(s1);
226
- if (!bridge)
227
- continue;
228
- const prun = tables.center2.pruning[bridge.encoded.ct * CENTER2_RL_STATES + bridge.encoded.rl];
229
- if (prun > length2)
230
- continue;
231
- const fullP1Moves = [...p1.moves, ...bridge.alignment];
232
- if (searchPhase2(bridge.encoded.ct, bridge.encoded.rl, length2, -1, 0, bridge.state, fullP1Moves)) {
233
- break OUTER;
593
+ // Ascending lookahead score (lowest total estimated center moves + wing bonus),
594
+ // tie-broken by lower phase-2 pruning bound then shorter prefix length
595
+ preps.sort((a, b) => (a.score - b.score) || (a.prun - b.prun) || (a.prefix.length - b.prefix.length));
596
+ // Filter: keep the best preps to avoid wasting phase-2 DFS work on suboptimal centers
597
+ const PREP_CAP = options?.prepCap !== undefined ? options.prepCap : (deep ? 160 : 100);
598
+ if (preps.length > PREP_CAP) {
599
+ preps.length = PREP_CAP;
600
+ }
601
+ // Per-restart tie order only (the ascending order above is preserved).
602
+ shuffleTies(preps, (p) => p.score, rng);
603
+ // Passes after the first one only extend MAX_P2 by one: every smaller
604
+ // length2 was already searched (deterministic — rerunning would push the
605
+ // same goals again as duplicates and crowd the 45 cap), so skip them.
606
+ // Tracked exactly per (prep, length2): this also fills holes left when a
607
+ // pass breaks early at the 45 cap, and is reused by the diversity
608
+ // extension below.
609
+ const searchedL2 = new Set();
610
+ let lastBestValue = 999;
611
+ let stagnantLengths = 0;
612
+ do {
613
+ OUTER: for (let length12 = minP1; length12 < minP1 + 16; length12++) {
614
+ for (let pi = 0; pi < preps.length; pi++) {
615
+ const prep = preps[pi];
616
+ if (prep.prefix.length > length12)
617
+ continue;
618
+ const length2 = length12 - prep.prefix.length;
619
+ if (length2 > MAX_P2 || length2 < 0)
620
+ continue;
621
+ if (prep.prun > length2)
622
+ continue;
623
+ const key = pi * 64 + length2;
624
+ if (searchedL2.has(key))
625
+ continue;
626
+ searchedL2.add(key);
627
+ p1CandCount = 0;
628
+ wpStack[0].set(prep.bridgeState.wp);
629
+ validWpDepth = 0;
630
+ searchPhase2(prep.ct, prep.rl, length2, -1, 0, prep.bridgeState, prep);
631
+ if (candidates.length >= CAND_CAP &&
632
+ candidates[0].value <= length12 + 9 &&
633
+ (candidates[0].edist <= 10 || length12 >= minP1 + 3)) {
634
+ break OUTER;
635
+ }
636
+ }
637
+ if (options?.stagnationCut !== false && candidates.length >= CAND_MIN) {
638
+ stagnationStats.checks++;
639
+ // NOTE: candidates is only sorted once it reaches CAND_CAP, so
640
+ // candidates[0] is NOT the best below the cap — scan the true min.
641
+ let curBest = Infinity;
642
+ for (let ci = 0; ci < candidates.length; ci++) {
643
+ const v = candidates[ci].value;
644
+ if (v < curBest)
645
+ curBest = v;
646
+ }
647
+ if (curBest >= lastBestValue) {
648
+ stagnantLengths++;
649
+ if (stagnantLengths >= 2) {
650
+ stagnationStats.cuts++;
651
+ break OUTER;
652
+ }
653
+ }
654
+ else {
655
+ lastBestValue = curBest;
656
+ stagnantLengths = 0;
657
+ }
234
658
  }
235
659
  }
660
+ MAX_P2++;
661
+ } while ((candidates.length === 0 && MAX_P2 <= P2_MAX_ABS) || (candidates.length < CAND_MIN && MAX_P2 <= P2_MAX_MIN));
662
+ if (candidates.length === 0) {
663
+ throw new Error("4x4 solve: no valid phase 2 candidates found.");
236
664
  }
237
- MAX_P2++;
238
- } while (candidates.length === 0 && MAX_P2 <= 14);
239
- if (candidates.length === 0) {
240
- throw new Error("4x4 solve: no valid phase 2 candidates found.");
241
- }
242
- candidates.sort((a, b) => a.value - b.value);
243
- let solvedCand = null;
244
- let solvedMoves3 = null;
245
- let standardReduced = null;
246
- let rotPath = [];
247
- let rotToStandard = [];
248
- let MAX_LENGTH3 = 13;
249
- let yieldCounter = 0;
250
- do {
251
- for (let length123 = candidates[0].value; length123 < 45; length123++) {
252
- for (let i = 0; i < Math.min(candidates.length, 60); i++) {
253
- const cand = candidates[i];
254
- if (cand.value > length123)
665
+ const tF2End = performance.now();
666
+ const validReductions = [];
667
+ /**
668
+ * Per-candidate IDA* proofs shared across all sweep stages: the greatest
669
+ * phase-3 length exhaustively proved empty for that candidate. Entries
670
+ * are only written on clean proofs (no cap abort, no goal seen, no TT
671
+ * hit, complete excess info), so skipping those lengths is exact.
672
+ */
673
+ const p3Proven = new Map();
674
+ /**
675
+ * Sync downstream chain for a phase-3 goal sequence: reduction check,
676
+ * orientation remap, 3x3 conversion + phase-1 heuristic. Returns the
677
+ * ValidReduction or null. Shared by the sweep validator and the polish
678
+ * pass (which retries the winner one length shorter).
679
+ */
680
+ function buildValidReduction(cand, moves3) {
681
+ const reduced = applyCube4Algorithm(cand.state, moves3);
682
+ if (checkCube4Reduction(reduced) !== null)
683
+ return null;
684
+ const totalRot = cand.totalRot;
685
+ const invTotalRot = totalRot.length === 0 ? [] : invertRotationSequence(totalRot);
686
+ const moves3Remapped = totalRot.length === 0 ? moves3 : rotateAlgorithm(moves3, invTotalRot);
687
+ const reducedOriginal = totalRot.length === 0 ? reduced : applyCubeRotation(reduced, invTotalRot);
688
+ const key = `${reducedOriginal.centers[0]},${reducedOriginal.centers[4]},${reducedOriginal.centers[8]}`;
689
+ const path = VALID_24_ORIENTATIONS.get(key);
690
+ if (!path)
691
+ return null;
692
+ const rotToStandard = invertRotationSequence(path);
693
+ const standardReduced = applyCubeRotation(reducedOriginal, rotToStandard);
694
+ const cube3State = toCube3State(standardReduced);
695
+ if (!cube3State) {
696
+ console.log(" toCube3State failed!");
697
+ return null;
698
+ }
699
+ const h3 = tables.cube3Phase1 ? getTriAxialCube3Heuristic(standardReduced, tables.cube3Phase1) : 0;
700
+ const reductionMoves = [
701
+ ...rotateAlgorithm(cand.moves12, rotToStandard),
702
+ ...rotateAlgorithm(moves3Remapped, rotToStandard)
703
+ ];
704
+ const simplifiedReduction = simplifyCube4Algorithm(reductionMoves);
705
+ return {
706
+ cand,
707
+ moves3,
708
+ moves3Remapped,
709
+ rotPath: path,
710
+ rotToStandard,
711
+ rotMoves: rotToStandard.flatMap((r) => ROT_MOVES[r]),
712
+ standardReduced,
713
+ h3,
714
+ totalEst: simplifiedReduction.length + h3
715
+ };
716
+ }
717
+ const centersBeam = Math.max(1, options?.centersBeam ?? 3);
718
+ const edgesPerCenter = Math.max(1, options?.edgesPerCenter ?? 3);
719
+ const maxReductionsTarget = options?.finishTries !== undefined
720
+ ? Math.max(1, options.finishTries)
721
+ : (centersBeam * edgesPerCenter);
722
+ /**
723
+ * One exact-length sweep over a value-sorted pool: tries increasing
724
+ * totals, collects up to maxReductionsTarget valid reductions using
725
+ * hierarchical beam search (centersBeam distinct centers x edgesPerCenter edge pairings).
726
+ * Shared across all stages below.
727
+ *
728
+ * Bounded by `maxCalls` solveLength calls (not wall-clock): easy states
729
+ * use ~100, so adversarial pools fail fast deterministically on any
730
+ * machine instead of grinding through the whole pool.
731
+ */
732
+ function sweepPool(pool, cfg) {
733
+ const candReductions = new Map();
734
+ const distinctCenters = new Set();
735
+ let foundAtLength = null;
736
+ OUTER_P3: for (let length123 = pool[0].value; length123 < L123_CAP; length123++) {
737
+ if (foundAtLength !== null && length123 > foundAtLength + 1)
255
738
  break;
256
- const length3 = length123 - cand.length12;
257
- if (length3 > MAX_LENGTH3 || length3 < 0)
258
- continue;
259
- if (cand.edist <= length3 && cand.cdist <= length3) {
260
- if (++yieldCounter % 100 === 0)
261
- await new Promise(r => setTimeout(r, 0));
262
- const moves3 = await phase3Solver.solveLength(cand.edge, cand.ct3, cand.edist, length3, tables.center3, tables.edge3.distances);
263
- if (!moves3)
739
+ // Sweep the whole (sorted) pool: see sortTop rationale.
740
+ for (let i = 0; i < pool.length; i++) {
741
+ const cand = pool[i];
742
+ if (cand.value > length123)
743
+ break;
744
+ const length3 = length123 - cand.length12;
745
+ const minL3 = Math.max(cand.edist, cand.cdist, cand.hdist, cand.pdist ?? 0);
746
+ if (length3 > cfg.maxLength3 || length3 < minL3)
264
747
  continue;
265
- const reduced = applyCube4Algorithm(cand.state, moves3);
266
- const key = `${reduced.centers[0]},${reduced.centers[4]},${reduced.centers[8]}`;
267
- const path = VALID_24_ORIENTATIONS.get(key);
268
- if (!path)
748
+ // IDA* threshold propagation: a previous exact-length call may have
749
+ // exhaustively proved this candidate empty through a longer length.
750
+ if ((p3Proven.get(cand) ?? -1) >= length3)
269
751
  continue;
270
- solvedCand = cand;
271
- solvedMoves3 = moves3;
272
- rotPath = path;
273
- rotToStandard = invertRotationSequence(rotPath);
274
- standardReduced = applyCubeRotation(reduced, rotToStandard);
275
- break;
752
+ const candCount = candReductions.get(cand) ?? 0;
753
+ if (candCount >= edgesPerCenter)
754
+ continue;
755
+ if (distinctCenters.size >= centersBeam && !distinctCenters.has(cand))
756
+ continue;
757
+ if (cand.edist <= length3 && cand.cdist <= length3 && cand.hdist <= length3 && (cand.pdist ?? 0) <= length3) {
758
+ const nodeLimit = length3 <= 12 ? 80000 : Math.max(45000, cfg.maxNodes);
759
+ f3calls++;
760
+ const validsBefore = validReductions.length;
761
+ const needed = edgesPerCenter - candCount;
762
+ const candReductionsBuffer = [];
763
+ const maxToCollect = Math.min(16, needed + 3);
764
+ const result = phase3Solver.solveLengthProven(cand.edge, cand.ct3, cand.edist, length3, tables.center3, tables.edge3.distances, nodeLimit, 16, (moves3) => {
765
+ const red = buildValidReduction(cand, moves3);
766
+ if (!red)
767
+ return false;
768
+ candReductionsBuffer.push(red);
769
+ if (foundAtLength === null)
770
+ foundAtLength = length123;
771
+ return candReductionsBuffer.length >= maxToCollect;
772
+ },
773
+ // hc mid-search prune disabled: on a 44-state corpus the per-node
774
+ // hc lookups cost more than they prune, and the altered
775
+ // capped/success pattern shifts the stop-at-3 valid selection
776
+ // toward shorter reductions (which finish as well or better on
777
+ // average). The exact hdist call gate above, the candidate hdist
778
+ // ranking, and the polish-pass hc bounds below all stay.
779
+ undefined, -1, tables.c3PairDist);
780
+ if (candReductionsBuffer.length > 0) {
781
+ // Sort solutions for this center candidate by totalEst (cancellation-aware length + tri-axial 3x3 heuristic)
782
+ candReductionsBuffer.sort((a, b) => a.totalEst - b.totalEst);
783
+ const toAdd = candReductionsBuffer.slice(0, needed);
784
+ for (const red of toAdd) {
785
+ validReductions.push(red);
786
+ }
787
+ candReductions.set(cand, candCount + toAdd.length);
788
+ distinctCenters.add(cand);
789
+ }
790
+ const proven = result.provenThrough;
791
+ if (process.env.CUBE4_SWEEP_STATS === "1") {
792
+ // eslint-disable-next-line no-console
793
+ console.log(`sweep l12=${cand.length12} l3=${length3} nodes=${result.nodesUsed}/${nodeLimit} ` +
794
+ `valid=${validReductions.length > validsBefore} proven=${proven} ` +
795
+ `c=${cand.cdist} e=${cand.edist} h=${cand.hdist}`);
796
+ }
797
+ if (result.moves === null && proven >= length3) {
798
+ const prev = p3Proven.get(cand) ?? -1;
799
+ if (proven > prev)
800
+ p3Proven.set(cand, proven);
801
+ }
802
+ // The finish loop attempts reductions up to maxReductionsTarget
803
+ if (validReductions.length >= maxReductionsTarget) {
804
+ break OUTER_P3;
805
+ }
806
+ }
276
807
  }
277
808
  }
278
- if (solvedCand)
809
+ }
810
+ const sortTop = (arr) => {
811
+ // No truncation: value misranks solvability (short bounds, hard joints),
812
+ // and truncating demonstrably discards winners (corpus-18/49). Cost lands
813
+ // only on hard states (early-stop rules); easy states stop early anyway.
814
+ const sorted = [...arr].sort((a, b) => a.value - b.value);
815
+ // Per-restart tie order only (ascending value order is preserved, so the
816
+ // sweep's `value > length123` break stays valid).
817
+ shuffleTies(sorted, (c) => c.value, rng);
818
+ return sorted;
819
+ };
820
+ // Sweeps with growing budgets; longitudes extend dynamically (reference
821
+ // style) while nothing is found, instead of fixed caps. Easy states only
822
+ // pay the first sweep.
823
+ // Sweeps with growing budgets; longitudes extend dynamically (reference
824
+ // style) while nothing is found, instead of fixed caps. Easy states only
825
+ // pay the first sweep.
826
+ // NOTE: lowering these caps was tried (20k/16k) and reverted: capped calls
827
+ // change which valids are found (±2 moves on the corpus). Only admissible
828
+ // heuristic strengthenings are length-safe here.
829
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 14 });
830
+ if (validReductions.length === 0) {
831
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 16 });
832
+ }
833
+ if (validReductions.length === 0) {
834
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 18 });
835
+ }
836
+ if (validReductions.length === 0) {
837
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 20 });
838
+ }
839
+ if (validReductions.length === 0) {
840
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 24 });
841
+ }
842
+ if (validReductions.length === 0 && deep) {
843
+ sweepPool(sortTop(candidates), { maxNodes: 60000, maxLength3: 27 });
844
+ }
845
+ // Diversity extension (only when both sweeps found nothing): the pool's
846
+ // joints are jointly hard, so gather DEEPER phase-2 solutions (longer
847
+ // length2 = different wings) and sweep those. Only hard states pay this.
848
+ if (validReductions.length === 0 && !options?.maxReductionLen) {
849
+ const poolStart = candidates.length;
850
+ let MX = MAX_P2;
851
+ EXTEND: while (candidates.length - poolStart < 40 && MX <= EXT_MX) {
852
+ for (let length12 = minP1; length12 < minP1 + 18; length12++) {
853
+ for (let pi = 0; pi < preps.length; pi++) {
854
+ const prep = preps[pi];
855
+ if (prep.prefix.length > length12)
856
+ break;
857
+ const length2 = length12 - prep.prefix.length;
858
+ if (length2 > MX || length2 < 0)
859
+ continue;
860
+ if (prep.prun > length2)
861
+ continue;
862
+ const key = pi * 64 + length2;
863
+ if (searchedL2.has(key))
864
+ continue;
865
+ searchedL2.add(key);
866
+ p1CandCount = 0;
867
+ wpStack[0].set(prep.bridgeState.wp);
868
+ validWpDepth = 0;
869
+ searchPhase2(prep.ct, prep.rl, length2, -1, 0, prep.bridgeState, prep);
870
+ if (candidates.length - poolStart >= 40)
871
+ break EXTEND;
872
+ }
873
+ }
874
+ MX++;
875
+ }
876
+ const fresh = sortTop(candidates.slice(poolStart));
877
+ if (fresh.length > 0) {
878
+ sweepPool(fresh, { maxNodes: 15000, maxLength3: 18 });
879
+ }
880
+ if (validReductions.length === 0 && fresh.length > 0) {
881
+ sweepPool(fresh, { maxNodes: 30000, maxLength3: 20 });
882
+ }
883
+ }
884
+ if (validReductions.length === 0) {
885
+ throw new Error("4x4 solve: reduction failed across all candidates.");
886
+ }
887
+ // Sort reductions by Total Estimated Moves (Reduction length + 3x3 Phase 1 lower bound)
888
+ validReductions.sort((a, b) => a.totalEst - b.totalEst);
889
+ const tFinishStart = performance.now();
890
+ let bestSolution = null;
891
+ let minTotalMoves = 999;
892
+ let bestPhases;
893
+ let bestRed = null;
894
+ // Best-of among the first two (as before); any further reductions are
895
+ // only attempted when those both failed, so a flaky 3x3 finish cannot
896
+ // sink the whole attempt while the common case costs nothing extra.
897
+ // Best-of among the first three (phase-4 is cheap now); further
898
+ // reductions are only attempted when those all failed.
899
+ const finishTries = options?.finishTries ?? maxReductionsTarget;
900
+ for (let i = 0; i < validReductions.length; i++) {
901
+ if (i >= finishTries && bestSolution)
279
902
  break;
903
+ const red = validReductions[i];
904
+ const cube3State = toCube3State(red.standardReduced);
905
+ if (!cube3State)
906
+ continue;
907
+ let cube3Solution;
908
+ try {
909
+ cube3Solution = await solveCube3(cube3State);
910
+ }
911
+ catch {
912
+ continue;
913
+ }
914
+ // Rotate the solve algorithm so it is performed from the standard orientation ("hacer los movimientos desde otro lado").
915
+ // This allows the solve to transition directly to the standard solved state WITHOUT ANY WHOLE-CUBE ROTATIONS (rotMoves)!
916
+ const rotatedFullSolution = [
917
+ ...rotateAlgorithm(red.cand.moves12, red.rotToStandard),
918
+ ...rotateAlgorithm(red.moves3Remapped, red.rotToStandard),
919
+ ...cube3Solution.moves
920
+ ];
921
+ const simplified = simplifyCube4Algorithm(rotatedFullSolution);
922
+ if (simplified.length < minTotalMoves) {
923
+ minTotalMoves = simplified.length;
924
+ bestSolution = simplified;
925
+ bestPhases = {
926
+ length12: red.cand.length12,
927
+ length1: red.cand.p1.moves.length,
928
+ length2: red.cand.length12 - red.cand.p1.moves.length,
929
+ length3: red.moves3.length,
930
+ finish: cube3Solution.moves.length
931
+ };
932
+ bestRed = red;
933
+ }
934
+ }
935
+ if (!bestSolution || !bestRed) {
936
+ throw new Error("4x4 solve: reduction failed across all candidates.");
937
+ }
938
+ // Polish pass: the sweep takes the first valid sequence per exact
939
+ // length, which is often one above optimal. Retry the winner one length
940
+ // shorter with a large budget (up to 2 iterations). Gated on totals
941
+ // above target so easy states never pay it.
942
+ const tPolishStart = performance.now();
943
+ // Polish the winner plus the runner-up by totalEst (was: winner only).
944
+ // Runner-up shortenings get their own finish and can only lower the min
945
+ // over finished totals; easy states skip the inner loop via the length
946
+ // gate below, so the extra pass costs ~nothing there.
947
+ const redToPolish = options?.deepPolish
948
+ ? validReductions.slice(0, 3)
949
+ : [bestRed, ...validReductions.filter((r) => r !== bestRed)].slice(0, 2);
950
+ for (const r of redToPolish) {
951
+ let curRed = r;
952
+ // The runner-up gets a cheap probe budget: its shortening is a bonus,
953
+ // and a full 150k grind on tail states cost seconds for nothing. It is
954
+ // also skipped entirely unless the total is high enough to matter.
955
+ const polishBudget = r === bestRed ? 150000 : 30000;
956
+ for (let iter = 0; iter < 4 && (minTotalMoves > 43 || curRed.moves3.length > 11); iter++) {
957
+ const cand = curRed.cand;
958
+ const shorterLen = curRed.moves3.length - 1;
959
+ if (shorterLen < cand.edist || shorterLen < cand.cdist || shorterLen < cand.hdist || shorterLen < (cand.pdist ?? 0))
960
+ break;
961
+ f3calls++;
962
+ const shorter = phase3Solver.solveLengthValid(cand.edge, cand.ct3, cand.edist, shorterLen, tables.center3, tables.edge3.distances, polishBudget, 64, (moves3) => buildValidReduction(cand, moves3) !== null, tables.hc, cand.hcCoord, tables.c3PairDist);
963
+ if (!shorter)
964
+ break;
965
+ const red = buildValidReduction(cand, shorter);
966
+ if (!red)
967
+ break;
968
+ const cube3State = toCube3State(red.standardReduced);
969
+ if (!cube3State)
970
+ break;
971
+ let cube3Solution;
972
+ try {
973
+ cube3Solution = await solveCube3(cube3State);
974
+ }
975
+ catch {
976
+ break;
977
+ }
978
+ const simplified = simplifyCube4Algorithm([
979
+ ...rotateAlgorithm(red.cand.moves12, red.rotToStandard),
980
+ ...rotateAlgorithm(red.moves3Remapped, red.rotToStandard),
981
+ ...cube3Solution.moves
982
+ ]);
983
+ if (simplified.length < minTotalMoves) {
984
+ minTotalMoves = simplified.length;
985
+ bestSolution = simplified;
986
+ curRed = red;
987
+ bestPhases = {
988
+ length12: red.cand.length12,
989
+ length1: red.cand.p1.moves.length,
990
+ length2: red.cand.length12 - red.cand.p1.moves.length,
991
+ length3: red.moves3.length,
992
+ finish: cube3Solution.moves.length
993
+ };
994
+ }
995
+ else {
996
+ break;
997
+ }
998
+ }
999
+ }
1000
+ accP2 += p2nodes;
1001
+ accF3calls += f3calls;
1002
+ accF1Ms += tF1End - tR0;
1003
+ accF2Ms += tF2End - tF1End;
1004
+ accF3Ms += tFinishStart - tF2End;
1005
+ accFinishMs += tPolishStart - tFinishStart;
1006
+ accPolishMs += performance.now() - tPolishStart;
1007
+ return { moves: bestSolution, phases: bestPhases };
1008
+ };
1009
+ let bestMoves = null;
1010
+ let bestPhasesOverall;
1011
+ let lastRestartError = null;
1012
+ for (let restart = 0; restart < totalRestarts; restart++) {
1013
+ FastPhase3Solver.nextEpoch();
1014
+ const rng = totalRestarts > 1
1015
+ ? mulberry32((hashCube4State(state) ^ Math.imul(restart + 1, 0x9e3779b9)) >>> 0)
1016
+ : null;
1017
+ try {
1018
+ const one = await runOnce(rng);
1019
+ if (!bestMoves || one.moves.length < bestMoves.length) {
1020
+ bestMoves = one.moves;
1021
+ bestPhasesOverall = one.phases;
1022
+ }
1023
+ }
1024
+ catch (error) {
1025
+ lastRestartError = error;
280
1026
  }
281
- MAX_LENGTH3++;
282
- } while (!solvedCand && MAX_LENGTH3 <= 18);
283
- if (!solvedCand || !solvedMoves3 || !standardReduced) {
284
- throw new Error("4x4 solve: reduction failed across all candidates.");
285
- }
286
- const cube3State = toCube3State(standardReduced);
287
- if (!cube3State) {
288
- throw new Error("4x4 solve: failed to convert reduced 4x4 state to 3x3 state.");
289
1027
  }
290
- let cube3Solution;
291
- try {
292
- cube3Solution = await solveCube3(cube3State);
1028
+ if (!bestMoves) {
1029
+ throw lastRestartError instanceof Error
1030
+ ? lastRestartError
1031
+ : new Error(`4x4 solve: all ${totalRestarts} restarts failed: ${String(lastRestartError)}`);
293
1032
  }
294
- catch (error) {
295
- if (error instanceof Cube3Phase2SearchError) {
296
- throw error;
1033
+ const scramble = invertCube4Algorithm(bestMoves);
1034
+ const result = {
1035
+ moves: bestMoves,
1036
+ scramble,
1037
+ nodes: { p2: accP2, p3: phase3Solver.epochNodes, f3calls: accF3calls },
1038
+ timings: {
1039
+ reductionMs: accF1Ms + accF2Ms + accF3Ms,
1040
+ f1Ms: accF1Ms,
1041
+ f2Ms: accF2Ms,
1042
+ f3Ms: accF3Ms,
1043
+ finishMs: accFinishMs,
1044
+ polishMs: accPolishMs
297
1045
  }
298
- throw error;
299
- }
300
- const fullSolInOriginal = [
301
- ...solvedCand.moves12,
302
- ...solvedMoves3,
303
- ...rotateAlgorithm(cube3Solution.moves, rotPath)
304
- ];
305
- const fullSolToStandard = [
306
- ...fullSolInOriginal,
307
- ...rotToStandard.flatMap((r) => ROT_MOVES[r])
308
- ];
309
- const scramble = invertCube4Algorithm(fullSolToStandard);
310
- return { moves: fullSolToStandard, scramble };
1046
+ };
1047
+ if (bestPhasesOverall)
1048
+ result.phases = bestPhasesOverall;
1049
+ return result;
311
1050
  }