@cubingcenter/scrambler 0.6.3 → 0.8.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 (191) hide show
  1. package/README.md +17 -4
  2. package/dist/core/api.d.ts.map +1 -1
  3. package/dist/core/api.js +10 -2
  4. package/dist/puzzles/cube2/solver/browser-loader.d.ts +4 -7
  5. package/dist/puzzles/cube2/solver/browser-loader.d.ts.map +1 -1
  6. package/dist/puzzles/cube2/solver/browser-loader.js +42 -14
  7. package/dist/puzzles/cube2/solver/generated-assets.d.ts.map +1 -1
  8. package/dist/puzzles/cube2/solver/generated-assets.js +8 -3
  9. package/dist/puzzles/cube2/solver/search.d.ts.map +1 -1
  10. package/dist/puzzles/cube2/solver/search.js +3 -3
  11. package/dist/puzzles/cube2/solver/tables.d.ts +6 -0
  12. package/dist/puzzles/cube2/solver/tables.d.ts.map +1 -1
  13. package/dist/puzzles/cube2/solver/tables.js +16 -2
  14. package/dist/puzzles/cube3/index.d.ts +1 -0
  15. package/dist/puzzles/cube3/index.d.ts.map +1 -1
  16. package/dist/puzzles/cube3/moves.d.ts.map +1 -1
  17. package/dist/puzzles/cube3/moves.js +104 -18
  18. package/dist/puzzles/cube3/scrambler.d.ts +16 -1
  19. package/dist/puzzles/cube3/scrambler.d.ts.map +1 -1
  20. package/dist/puzzles/cube3/scrambler.js +1 -1
  21. package/dist/puzzles/cube3/solver/browser-loader.d.ts.map +1 -1
  22. package/dist/puzzles/cube3/solver/browser-loader.js +48 -22
  23. package/dist/puzzles/cube3/solver/generated-assets.d.ts.map +1 -1
  24. package/dist/puzzles/cube3/solver/generated-assets.js +9 -3
  25. package/dist/puzzles/cube3/solver/index.d.ts +5 -3
  26. package/dist/puzzles/cube3/solver/index.d.ts.map +1 -1
  27. package/dist/puzzles/cube3/solver/index.js +2 -1
  28. package/dist/puzzles/cube3/solver/node-loader.js +9 -2
  29. package/dist/puzzles/cube3/solver/phase1.d.ts +37 -0
  30. package/dist/puzzles/cube3/solver/phase1.d.ts.map +1 -1
  31. package/dist/puzzles/cube3/solver/phase1.js +156 -15
  32. package/dist/puzzles/cube3/solver/phase2.d.ts +75 -0
  33. package/dist/puzzles/cube3/solver/phase2.d.ts.map +1 -1
  34. package/dist/puzzles/cube3/solver/phase2.js +279 -68
  35. package/dist/puzzles/cube3/solver/search-utils.d.ts +1 -1
  36. package/dist/puzzles/cube3/solver/search-utils.d.ts.map +1 -1
  37. package/dist/puzzles/cube3/solver/symmetry.d.ts +24 -0
  38. package/dist/puzzles/cube3/solver/symmetry.d.ts.map +1 -0
  39. package/dist/puzzles/cube3/solver/symmetry.js +74 -0
  40. package/dist/puzzles/cube3/solver/tables.d.ts +6 -1
  41. package/dist/puzzles/cube3/solver/tables.d.ts.map +1 -1
  42. package/dist/puzzles/cube3/solver/tables.js +14 -12
  43. package/dist/puzzles/cube3/validation.d.ts.map +1 -1
  44. package/dist/puzzles/cube3/validation.js +15 -7
  45. package/dist/puzzles/cube4/browser-worker-pool.d.ts +82 -0
  46. package/dist/puzzles/cube4/browser-worker-pool.d.ts.map +1 -0
  47. package/dist/puzzles/cube4/browser-worker-pool.js +205 -0
  48. package/dist/puzzles/cube4/browser-worker.d.ts +2 -0
  49. package/dist/puzzles/cube4/browser-worker.d.ts.map +1 -0
  50. package/dist/puzzles/cube4/browser-worker.js +31 -0
  51. package/dist/puzzles/cube4/index.d.ts +10 -2
  52. package/dist/puzzles/cube4/index.d.ts.map +1 -1
  53. package/dist/puzzles/cube4/index.js +6 -2
  54. package/dist/puzzles/cube4/moves.d.ts +5 -0
  55. package/dist/puzzles/cube4/moves.d.ts.map +1 -1
  56. package/dist/puzzles/cube4/moves.js +212 -11
  57. package/dist/puzzles/cube4/reduction/browser-loader.d.ts +29 -1
  58. package/dist/puzzles/cube4/reduction/browser-loader.d.ts.map +1 -1
  59. package/dist/puzzles/cube4/reduction/browser-loader.js +227 -32
  60. package/dist/puzzles/cube4/reduction/center2.d.ts +44 -3
  61. package/dist/puzzles/cube4/reduction/center2.d.ts.map +1 -1
  62. package/dist/puzzles/cube4/reduction/center2.js +152 -10
  63. package/dist/puzzles/cube4/reduction/edge3.d.ts +4 -0
  64. package/dist/puzzles/cube4/reduction/edge3.d.ts.map +1 -1
  65. package/dist/puzzles/cube4/reduction/edge3.js +23 -3
  66. package/dist/puzzles/cube4/reduction/finish3.d.ts +53 -0
  67. package/dist/puzzles/cube4/reduction/finish3.d.ts.map +1 -0
  68. package/dist/puzzles/cube4/reduction/finish3.js +393 -0
  69. package/dist/puzzles/cube4/reduction/generated/c3_pair_dist.bin +1 -0
  70. package/dist/puzzles/cube4/reduction/generated/center2-manifest.json +36 -0
  71. package/dist/puzzles/cube4/reduction/generated/center2-pruning-wide.bin +1 -0
  72. package/dist/puzzles/cube4/reduction/generated/hc-distances.bin +1 -0
  73. package/dist/puzzles/cube4/reduction/generated/hc-manifest.json +44 -0
  74. package/dist/puzzles/cube4/reduction/generated/hc-move.bin +0 -0
  75. package/dist/puzzles/cube4/reduction/hc-pdb.d.ts +52 -0
  76. package/dist/puzzles/cube4/reduction/hc-pdb.d.ts.map +1 -0
  77. package/dist/puzzles/cube4/reduction/hc-pdb.js +220 -0
  78. package/dist/puzzles/cube4/reduction/node-loader.d.ts +15 -1
  79. package/dist/puzzles/cube4/reduction/node-loader.d.ts.map +1 -1
  80. package/dist/puzzles/cube4/reduction/node-loader.js +199 -25
  81. package/dist/puzzles/cube4/reduction/pair-transversal.d.ts +28 -0
  82. package/dist/puzzles/cube4/reduction/pair-transversal.d.ts.map +1 -0
  83. package/dist/puzzles/cube4/reduction/pair-transversal.js +107 -0
  84. package/dist/puzzles/cube4/reduction/pairing-coordinate.js +5 -5
  85. package/dist/puzzles/cube4/reduction/phase3-search.d.ts +116 -7
  86. package/dist/puzzles/cube4/reduction/phase3-search.d.ts.map +1 -1
  87. package/dist/puzzles/cube4/reduction/phase3-search.js +458 -32
  88. package/dist/puzzles/cube4/reduction/rotation-fix.d.ts +28 -0
  89. package/dist/puzzles/cube4/reduction/rotation-fix.d.ts.map +1 -0
  90. package/dist/puzzles/cube4/reduction/rotation-fix.js +212 -0
  91. package/dist/puzzles/cube4/reduction/solve.d.ts +172 -2
  92. package/dist/puzzles/cube4/reduction/solve.d.ts.map +1 -1
  93. package/dist/puzzles/cube4/reduction/solve.js +1201 -180
  94. package/dist/puzzles/cube4/scramble-cache.d.ts +93 -0
  95. package/dist/puzzles/cube4/scramble-cache.d.ts.map +1 -0
  96. package/dist/puzzles/cube4/scramble-cache.js +150 -0
  97. package/dist/puzzles/cube4/scrambler.d.ts +201 -6
  98. package/dist/puzzles/cube4/scrambler.d.ts.map +1 -1
  99. package/dist/puzzles/cube4/scrambler.js +414 -176
  100. package/dist/puzzles/cube4/state.d.ts.map +1 -1
  101. package/dist/puzzles/cube4/state.js +4 -1
  102. package/dist/puzzles/cube4/worker-pool.d.ts +139 -0
  103. package/dist/puzzles/cube4/worker-pool.d.ts.map +1 -0
  104. package/dist/puzzles/cube4/worker-pool.js +405 -0
  105. package/dist/puzzles/cube4/worker-protocol.d.ts +58 -0
  106. package/dist/puzzles/cube4/worker-protocol.d.ts.map +1 -0
  107. package/dist/puzzles/cube4/worker-protocol.js +58 -0
  108. package/dist/puzzles/cube4/worker.d.ts +26 -0
  109. package/dist/puzzles/cube4/worker.d.ts.map +1 -0
  110. package/dist/puzzles/cube4/worker.js +49 -0
  111. package/dist/puzzles/pyraminx/solver/browser-loader.d.ts +4 -8
  112. package/dist/puzzles/pyraminx/solver/browser-loader.d.ts.map +1 -1
  113. package/dist/puzzles/pyraminx/solver/browser-loader.js +44 -15
  114. package/dist/puzzles/pyraminx/solver/generated-assets.d.ts.map +1 -1
  115. package/dist/puzzles/pyraminx/solver/generated-assets.js +8 -3
  116. package/dist/puzzles/pyraminx/solver/search.d.ts.map +1 -1
  117. package/dist/puzzles/pyraminx/solver/search.js +3 -6
  118. package/dist/puzzles/pyraminx/solver/tables.d.ts +6 -0
  119. package/dist/puzzles/pyraminx/solver/tables.d.ts.map +1 -1
  120. package/dist/puzzles/pyraminx/solver/tables.js +17 -0
  121. package/dist/puzzles/shared/compressed-fetch.d.ts +37 -1
  122. package/dist/puzzles/shared/compressed-fetch.d.ts.map +1 -1
  123. package/dist/puzzles/shared/compressed-fetch.js +226 -31
  124. package/dist/puzzles/shared/load-once.d.ts +16 -0
  125. package/dist/puzzles/shared/load-once.d.ts.map +1 -0
  126. package/dist/puzzles/shared/load-once.js +11 -0
  127. package/dist/puzzles/skewb/solver/browser-loader.d.ts +4 -11
  128. package/dist/puzzles/skewb/solver/browser-loader.d.ts.map +1 -1
  129. package/dist/puzzles/skewb/solver/browser-loader.js +44 -16
  130. package/dist/puzzles/skewb/solver/generated-assets.d.ts.map +1 -1
  131. package/dist/puzzles/skewb/solver/generated-assets.js +8 -3
  132. package/dist/puzzles/skewb/solver/search.js +3 -3
  133. package/dist/puzzles/skewb/solver/tables.d.ts +6 -0
  134. package/dist/puzzles/skewb/solver/tables.d.ts.map +1 -1
  135. package/dist/puzzles/skewb/solver/tables.js +17 -0
  136. package/dist/puzzles/sq1/solver/browser-loader.d.ts.map +1 -1
  137. package/dist/puzzles/sq1/solver/browser-loader.js +58 -26
  138. package/dist-cjs/core/api.js +10 -2
  139. package/dist-cjs/puzzles/cube2/solver/browser-loader.js +42 -14
  140. package/dist-cjs/puzzles/cube2/solver/generated-assets.js +8 -3
  141. package/dist-cjs/puzzles/cube2/solver/search.js +2 -2
  142. package/dist-cjs/puzzles/cube2/solver/tables.js +17 -3
  143. package/dist-cjs/puzzles/cube3/moves.js +104 -18
  144. package/dist-cjs/puzzles/cube3/scrambler.js +1 -1
  145. package/dist-cjs/puzzles/cube3/solver/browser-loader.js +48 -22
  146. package/dist-cjs/puzzles/cube3/solver/generated-assets.js +9 -3
  147. package/dist-cjs/puzzles/cube3/solver/index.js +8 -1
  148. package/dist-cjs/puzzles/cube3/solver/node-loader.js +9 -2
  149. package/dist-cjs/puzzles/cube3/solver/phase1.js +157 -15
  150. package/dist-cjs/puzzles/cube3/solver/phase2.js +276 -65
  151. package/dist-cjs/puzzles/cube3/solver/symmetry.js +80 -0
  152. package/dist-cjs/puzzles/cube3/solver/tables.js +14 -12
  153. package/dist-cjs/puzzles/cube3/validation.js +15 -7
  154. package/dist-cjs/puzzles/cube4/browser-worker-pool.js +211 -0
  155. package/dist-cjs/puzzles/cube4/index.js +23 -1
  156. package/dist-cjs/puzzles/cube4/moves.js +213 -11
  157. package/dist-cjs/puzzles/cube4/reduction/browser-loader.js +227 -32
  158. package/dist-cjs/puzzles/cube4/reduction/center2.js +155 -10
  159. package/dist-cjs/puzzles/cube4/reduction/edge3.js +24 -3
  160. package/dist-cjs/puzzles/cube4/reduction/finish3.js +398 -0
  161. package/dist-cjs/puzzles/cube4/reduction/generated/c3_pair_dist.bin +1 -0
  162. package/dist-cjs/puzzles/cube4/reduction/generated/center2-manifest.json +36 -0
  163. package/dist-cjs/puzzles/cube4/reduction/generated/center2-pruning-wide.bin +1 -0
  164. package/dist-cjs/puzzles/cube4/reduction/generated/hc-distances.bin +1 -0
  165. package/dist-cjs/puzzles/cube4/reduction/generated/hc-manifest.json +44 -0
  166. package/dist-cjs/puzzles/cube4/reduction/generated/hc-move.bin +0 -0
  167. package/dist-cjs/puzzles/cube4/reduction/hc-pdb.js +232 -0
  168. package/dist-cjs/puzzles/cube4/reduction/node-loader.js +200 -25
  169. package/dist-cjs/puzzles/cube4/reduction/pair-transversal.js +112 -0
  170. package/dist-cjs/puzzles/cube4/reduction/pairing-coordinate.js +5 -5
  171. package/dist-cjs/puzzles/cube4/reduction/phase3-search.js +460 -33
  172. package/dist-cjs/puzzles/cube4/reduction/rotation-fix.js +216 -0
  173. package/dist-cjs/puzzles/cube4/reduction/solve.js +1203 -172
  174. package/dist-cjs/puzzles/cube4/scramble-cache.js +156 -0
  175. package/dist-cjs/puzzles/cube4/scrambler.js +416 -174
  176. package/dist-cjs/puzzles/cube4/state.js +4 -1
  177. package/dist-cjs/puzzles/cube4/worker-pool.js +447 -0
  178. package/dist-cjs/puzzles/cube4/worker-protocol.js +62 -0
  179. package/dist-cjs/puzzles/pyraminx/solver/browser-loader.js +44 -15
  180. package/dist-cjs/puzzles/pyraminx/solver/generated-assets.js +8 -3
  181. package/dist-cjs/puzzles/pyraminx/solver/search.js +2 -5
  182. package/dist-cjs/puzzles/pyraminx/solver/tables.js +18 -1
  183. package/dist-cjs/puzzles/shared/compressed-fetch.js +229 -31
  184. package/dist-cjs/puzzles/shared/load-once.js +14 -0
  185. package/dist-cjs/puzzles/skewb/solver/browser-loader.js +44 -16
  186. package/dist-cjs/puzzles/skewb/solver/generated-assets.js +8 -3
  187. package/dist-cjs/puzzles/skewb/solver/search.js +2 -2
  188. package/dist-cjs/puzzles/skewb/solver/tables.js +18 -1
  189. package/dist-cjs/puzzles/sq1/solver/browser-loader.js +58 -26
  190. package/docs/development.md +19 -7
  191. package/package.json +17 -7
@@ -4,15 +4,131 @@
4
4
  * The scramble for a sampled state is the inverted solution.
5
5
  */
6
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";
7
+ import { center1Mask, getCenter1Distance, applyCenter1Move, CENTER1_MOVES, CENTER1_GOAL_MASKS } from "./center1.js";
8
+ import { center2Bridge, getWingMoveMaps, CENTER2_GOAL_RL, CENTER2_MOVES, CENTER2_SEARCH_MOVES, CENTER2_SEARCH_MOVES_WIDE, CENTER2_RL_STATES, encodeCenter2ChiralCt, generateCenter2ChiralTables } from "./center2.js";
9
9
  import { encodeCenter3 } from "./center3.js";
10
- import { encodePairingState } from "./pairing-coordinate.js";
10
+ import { encodePairingState, PAIRING_SECOND_HALVES } from "./pairing-coordinate.js";
11
+ import { encodeHcPdb, hcDenseIndex } 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";
15
- import { createSolvedCube4State } from "../state.js";
14
+ import { placeRotationFix } from "./rotation-fix.js";
15
+ import { getTransversalPairPdb, getWingPositionMoves, PAIR_INDEX, PAIR_STATES } from "./pair-transversal.js";
16
+ import { checkCube4Reduction, toCube3State } from "./phase4.js";
17
+ import { encodeCornerOrientation, encodeEdgeOrientation, encodeUdSlice } from "../../cube3/solver/coordinates.js";
18
+ import { createSolvedCube4State, isSolvedCube4State } from "../state.js";
19
+ function mulberry32(seed) {
20
+ let a = seed >>> 0;
21
+ return () => {
22
+ a |= 0;
23
+ a = (a + 0x6d2b79f5) | 0;
24
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
25
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
26
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
27
+ };
28
+ }
29
+ function hashCube4State(state) {
30
+ let h = 0x811c9dc5;
31
+ for (const arr of [state.cp, state.co, state.wp, state.centers]) {
32
+ for (let i = 0; i < arr.length; i++) {
33
+ h ^= arr[i] & 0xff;
34
+ h = Math.imul(h, 0x01000193);
35
+ }
36
+ }
37
+ return h >>> 0;
38
+ }
39
+ /**
40
+ * Fisher-Yates order, or identity when rng is null (restarts=1 keeps the
41
+ * legacy deterministic traversal bit-identical).
42
+ */
43
+ function restartOrder(n, rng) {
44
+ const order = Array.from({ length: n }, (_, i) => i);
45
+ if (rng) {
46
+ for (let i = n - 1; i > 0; i--) {
47
+ const j = Math.floor(rng() * (i + 1));
48
+ const t = order[i];
49
+ order[i] = order[j];
50
+ order[j] = t;
51
+ }
52
+ }
53
+ return order;
54
+ }
55
+ /**
56
+ * Fisher-Yates within equal-key runs of a key-sorted array, so the
57
+ * caller's sorted early-break (`value > length123`) stays valid.
58
+ */
59
+ function shuffleTies(arr, key, rng) {
60
+ if (!rng)
61
+ return;
62
+ let run = 0;
63
+ for (let i = 1; i <= arr.length; i++) {
64
+ if (i < arr.length && key(arr[i]) === key(arr[run]))
65
+ continue;
66
+ for (let k = i - 1; k > run; k--) {
67
+ const j = run + Math.floor(rng() * (k - run + 1));
68
+ const t = arr[k];
69
+ arr[k] = arr[j];
70
+ arr[j] = t;
71
+ }
72
+ run = i;
73
+ }
74
+ }
75
+ function getCube3Phase1Heuristic(cube3State, tables) {
76
+ const co = encodeCornerOrientation(cube3State);
77
+ const eo = encodeEdgeOrientation(cube3State);
78
+ const ud = encodeUdSlice(cube3State);
79
+ const combined = (co << 11) + eo;
80
+ const coeo = (tables.pruningTables.cornerOrientationEdgeOrientation.values[combined >> 1] >>
81
+ ((combined & 1) << 2)) &
82
+ 0x0f;
83
+ const udd = (tables.pruningTables.udSlice.values[ud >> 1] >> ((ud & 1) << 2)) & 0x0f;
84
+ return Math.max(coeo, udd);
85
+ }
86
+ function getTriAxialCube3Heuristic(standardReduced, tables) {
87
+ const s0 = toCube3State(standardReduced);
88
+ if (!s0)
89
+ return 99;
90
+ let minH = getCube3Phase1Heuristic(s0, tables);
91
+ if (minH <= 3)
92
+ return minH;
93
+ const sx = toCube3State(applyCubeRotation(standardReduced, ["x"]));
94
+ if (sx) {
95
+ const hx = getCube3Phase1Heuristic(sx, tables);
96
+ if (hx < minH)
97
+ minH = hx;
98
+ if (minH <= 3)
99
+ return minH;
100
+ }
101
+ const sz = toCube3State(applyCubeRotation(standardReduced, ["z"]));
102
+ if (sz) {
103
+ const hz = getCube3Phase1Heuristic(sz, tables);
104
+ if (hz < minH)
105
+ minH = hz;
106
+ }
107
+ return minH;
108
+ }
109
+ class Cube4SolveError extends Error {
110
+ }
111
+ export class Cube4Phase2CapError extends Cube4SolveError {
112
+ code = "cube4-phase2-cap";
113
+ constructor(message) {
114
+ super(message);
115
+ this.name = "Cube4Phase2CapError";
116
+ }
117
+ }
118
+ export class Cube4Phase3CapError extends Cube4SolveError {
119
+ code = "cube4-phase3-cap";
120
+ constructor(message) {
121
+ super(message);
122
+ this.name = "Cube4Phase3CapError";
123
+ }
124
+ }
125
+ export class Cube4FinishCapError extends Cube4SolveError {
126
+ code = "cube4-finish-cap";
127
+ constructor(message) {
128
+ super(message);
129
+ this.name = "Cube4FinishCapError";
130
+ }
131
+ }
16
132
  function cornerPermutationParity(cp) {
17
133
  let parity = 0;
18
134
  const seen = new Array(8).fill(false);
@@ -30,13 +146,48 @@ function cornerPermutationParity(cp) {
30
146
  }
31
147
  return parity;
32
148
  }
149
+ /**
150
+ * Computes the spatial determinant (+1 for valid 3D rotations, -1 for reflections)
151
+ * of the 3 axes defined by the center colors on faces U, R, F.
152
+ */
153
+ function getOrientationDet(uColor, rColor, fColor) {
154
+ const vec = (c) => {
155
+ switch (c) {
156
+ case 0: return [0, 0, 1];
157
+ case 3: return [0, 0, -1];
158
+ case 1: return [1, 0, 0];
159
+ case 4: return [-1, 0, 0];
160
+ case 2: return [0, 1, 0];
161
+ case 5: return [0, -1, 0];
162
+ default: return [0, 0, 0];
163
+ }
164
+ };
165
+ const [ux, uy, uz] = vec(uColor);
166
+ const [rx, ry, rz] = vec(rColor);
167
+ const [fx, fy, fz] = vec(fColor);
168
+ const cx = ry * fz - rz * fy;
169
+ const cy = rz * fx - rx * fz;
170
+ const cz = rx * fy - ry * fx;
171
+ return cx * ux + cy * uy + cz * uz;
172
+ }
173
+ function axisDet(uAxis, rAxis, fAxis) {
174
+ if ((uAxis === 0 && rAxis === 1 && fAxis === 2) ||
175
+ (uAxis === 1 && rAxis === 2 && fAxis === 0) ||
176
+ (uAxis === 2 && rAxis === 0 && fAxis === 1)) {
177
+ return 1;
178
+ }
179
+ return -1;
180
+ }
33
181
  const ROT_MOVES = {
34
182
  "x": ["Rw", "Lw'"],
35
183
  "y": ["Uw", "Dw'"],
36
184
  "z": ["Fw", "Bw'"],
37
185
  "x'": ["Rw'", "Lw"],
38
186
  "y'": ["Uw'", "Dw"],
39
- "z'": ["Fw'", "Bw"]
187
+ "z'": ["Fw'", "Bw"],
188
+ "x2": ["Rw2", "Lw2"],
189
+ "y2": ["Uw2", "Dw2"],
190
+ "z2": ["Fw2", "Bw2"]
40
191
  };
41
192
  const VALID_24_ORIENTATIONS = (() => {
42
193
  const map = new Map();
@@ -57,18 +208,24 @@ const VALID_24_ORIENTATIONS = (() => {
57
208
  }
58
209
  return map;
59
210
  })();
211
+ /** Centers of the solved state — used to verify a full (not just partial) standard orientation. */
212
+ const SOLVED_CENTERS = createSolvedCube4State().centers;
60
213
  const ROT_MAP = {
61
214
  "x": { "U": "B", "R": "R", "F": "U", "D": "F", "L": "L", "B": "D" },
62
215
  "x'": { "U": "F", "R": "R", "F": "D", "D": "B", "L": "L", "B": "U" },
63
216
  "y": { "U": "U", "R": "F", "F": "L", "D": "D", "L": "B", "B": "R" },
64
217
  "y'": { "U": "U", "R": "B", "F": "R", "D": "D", "L": "F", "B": "L" },
65
218
  "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" }
219
+ "z'": { "U": "L", "R": "U", "F": "F", "D": "R", "L": "D", "B": "B" },
220
+ "x2": { "U": "D", "R": "R", "F": "B", "D": "U", "L": "L", "B": "F" },
221
+ "y2": { "U": "U", "R": "L", "F": "B", "D": "D", "L": "R", "B": "F" },
222
+ "z2": { "U": "D", "R": "L", "F": "F", "D": "U", "L": "R", "B": "B" }
67
223
  };
68
224
  const INVERT_ROT = {
69
225
  "x": "x'", "x'": "x",
70
226
  "y": "y'", "y'": "y",
71
- "z": "z'", "z'": "z"
227
+ "z": "z'", "z'": "z",
228
+ "x2": "x2", "y2": "y2", "z2": "z2"
72
229
  };
73
230
  function rotateMove(move, rot) {
74
231
  const map = ROT_MAP[rot];
@@ -76,17 +233,26 @@ function rotateMove(move, rot) {
76
233
  const newFace = map[face];
77
234
  return (newFace + move.slice(1));
78
235
  }
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;
236
+ export function rotateAlgorithm(alg, rotSeq) {
237
+ // Single pass over the algorithm (one allocation): applying the rotation
238
+ // sequence per move instead of re-mapping the whole array per rotation.
239
+ if (rotSeq.length === 0)
240
+ return [...alg];
241
+ return alg.map((move) => {
242
+ let current = move;
243
+ for (const rot of rotSeq)
244
+ current = rotateMove(current, rot);
245
+ return current;
246
+ });
247
+ }
248
+ /** Physical wide-move sequence implementing a whole-cube rotation. */
249
+ export function cubeRotationMoves(rotSeq) {
250
+ return rotSeq.flatMap((rotation) => ROT_MOVES[rotation]);
85
251
  }
86
- function invertRotationSequence(rotSeq) {
252
+ export function invertRotationSequence(rotSeq) {
87
253
  return [...rotSeq].reverse().map((r) => INVERT_ROT[r]);
88
254
  }
89
- function applyCubeRotation(state, rotSeq) {
255
+ export function applyCubeRotation(state, rotSeq) {
90
256
  let s = state;
91
257
  for (const r of rotSeq) {
92
258
  s = applyCube4Algorithm(s, ROT_MOVES[r]);
@@ -116,196 +282,1051 @@ function isCancelled(previous, current) {
116
282
  }
117
283
  return false;
118
284
  }
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))
285
+ // Precomputed phase-2 cancellation matrix over CENTER2_SEARCH_MOVES: the
286
+ // search evaluates isCancelled per child per node (~0.3M nodes × 23 moves
287
+ // per attempt with regex + Map lookups); the table makes it one boolean
288
+ // read with a bit-identical traversal.
289
+ export const P2_CANCEL = CENTER2_SEARCH_MOVES.map((previous) => CENTER2_SEARCH_MOVES.map((current) => isCancelled(previous, current)));
290
+ // Same over the wide 28-move set (used when `center2Wide` is set).
291
+ const P2_CANCEL_WIDE = CENTER2_SEARCH_MOVES_WIDE.map((previous) => CENTER2_SEARCH_MOVES_WIDE.map((current) => isCancelled(previous, current)));
292
+ /** Flat (row-major) cancel tables for the hot DFS loop; same semantics. */
293
+ function flattenCancel(table) {
294
+ const n = table.length;
295
+ const flat = new Uint8Array(n * n);
296
+ for (let i = 0; i < n; i++) {
297
+ const row = table[i];
298
+ for (let j = 0; j < n; j++)
299
+ flat[i * n + j] = row[j] ? 1 : 0;
300
+ }
301
+ return flat;
302
+ }
303
+ const P2_CANCEL_FLAT = flattenCancel(P2_CANCEL);
304
+ const P2_CANCEL_WIDE_FLAT = flattenCancel(P2_CANCEL_WIDE);
305
+ /**
306
+ * Wing transversal mask: bit k set iff pair k occupies a second-half slot.
307
+ * `hasPairingTransversal(wp)` is equivalent to `pairingMaskOf(wp) === 0xfff`
308
+ * (12 slots, 12 pair ids in 0..11: all distinct ⟺ all 12 bits set). The mask
309
+ * form is O(1) at the millions of phase-2 goal leaves.
310
+ */
311
+ function pairingMaskOf(wp) {
312
+ let mask = 0;
313
+ for (let i = 0; i < 12; i++) {
314
+ mask |= 1 << (wp[PAIRING_SECOND_HALVES[i]] >> 1);
315
+ }
316
+ return mask;
317
+ }
318
+ /** rl side of the phase-2 goal test (same flags as `isCenter2Goal`). */
319
+ const P2_GOAL_RL = (() => {
320
+ const flags = new Uint8Array(CENTER2_RL_STATES);
321
+ for (const rl of CENTER2_GOAL_RL)
322
+ flags[rl] = 1;
323
+ return flags;
324
+ })();
325
+ /** Chiral phase-2 tables, generated once per loaded center2 table set. */
326
+ const chiralTablesCache = new WeakMap();
327
+ function getCenter2ChiralTables(center2) {
328
+ let chiral = chiralTablesCache.get(center2);
329
+ if (!chiral) {
330
+ chiral = generateCenter2ChiralTables(center2.rlMove);
331
+ chiralTablesCache.set(center2, chiral);
332
+ }
333
+ return chiral;
334
+ }
335
+ const SKIP_AXIS_2 = new Int32Array(CENTER2_SEARCH_MOVES.length);
336
+ for (let i = 0; i < CENTER2_SEARCH_MOVES.length; i++) {
337
+ const m1 = CENTER2_SEARCH_MOVES[i];
338
+ const face1 = m1.replace(/2|'|w/g, "");
339
+ const isWide1 = m1.includes("w");
340
+ SKIP_AXIS_2[i] = CENTER2_SEARCH_MOVES.length;
341
+ for (let j = i + 1; j < CENTER2_SEARCH_MOVES.length; j++) {
342
+ const m2 = CENTER2_SEARCH_MOVES[j];
343
+ const face2 = m2.replace(/2|'|w/g, "");
344
+ const isWide2 = m2.includes("w");
345
+ if (face1 !== face2 || isWide1 !== isWide2) {
346
+ SKIP_AXIS_2[i] = j;
149
347
  break;
348
+ }
150
349
  }
151
- return solutions;
152
350
  }
153
- const phase3Solver = new FastPhase3Solver();
351
+ /** Temporary instrumentation for F2 goal statistics (CUBE4_F2_STATS=1). */
352
+ export const f2Stats = { goals: 0, transversalPass: 0, axisRejects: 0, minTransversalL2: 99, minChiralL2: 99 };
353
+ export function resetF2Stats() {
354
+ f2Stats.goals = 0;
355
+ f2Stats.transversalPass = 0;
356
+ f2Stats.axisRejects = 0;
357
+ f2Stats.minTransversalL2 = 99;
358
+ f2Stats.minChiralL2 = 99;
359
+ }
360
+ /** Trigger rate for the stagnationCut early-stop (checks vs actual cuts). */
361
+ export const stagnationStats = { checks: 0, cuts: 0 };
362
+ export function resetStagnationStats() {
363
+ stagnationStats.checks = 0;
364
+ stagnationStats.cuts = 0;
365
+ }
154
366
  /**
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).
367
+ * Temporary instrumentation for the finish-skip bound (CUBE4_FINISH_STATS=1):
368
+ * `gap = totalEst - finalLen` per finished reduction. A skip
369
+ * `totalEst - SLACK >= minTotalMoves` is only sound while SLACK covers the
370
+ * observed gap maximum (junction cancellation + finish-vs-h3 slack).
157
371
  */
158
- export async function solveCube4State(state, tables, solveCube3) {
372
+ export const finishStats = {
373
+ gapMin: 99,
374
+ gapMax: -99,
375
+ gapSum: 0,
376
+ gapN: 0,
377
+ finishes: 0,
378
+ skipped: 0
379
+ };
380
+ /**
381
+ * Temporary instrumentation for the rotMoves cost (CUBE4_ROT_STATS=1):
382
+ * per built reduction records the prep frame rotation, the derived
383
+ * normalization rotation and the emitted fix length.
384
+ */
385
+ export const rotStats = [];
386
+ export async function solveCube4State(state, tables, solveCube3, options) {
387
+ // NOTE: no wall-clock deadline inside the search — all loops are bounded
388
+ // by deterministic work caps (node counts, candidate counts, length caps),
389
+ // so the same state always takes the same path.
159
390
  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
391
+ // All mutable phase-3 state (TT, epoch-node count, call IDs and search
392
+ // stacks) belongs to this invocation. The same instance spans its
393
+ // deterministic restarts, retaining useful goal-free TT entries without
394
+ // allowing concurrent solves to contaminate one another.
395
+ const phase3Solver = new FastPhase3Solver();
396
+ phase3Solver.resetEpochNodes();
397
+ const collectF2Stats = typeof process !== "undefined" && process.env?.CUBE4_F2_STATS === "1";
398
+ const totalRestarts = Math.max(1, Math.floor(options?.restarts ?? 1));
399
+ // Cross-restart work accumulators (reported in nodes/timings).
400
+ let accP2 = 0;
401
+ let accF3calls = 0;
402
+ let accF1Ms = 0;
403
+ let accF2Ms = 0;
404
+ let accF3Ms = 0;
405
+ let accFinishMs = 0;
406
+ let accPolishMs = 0;
407
+ const runOnce = async (rng) => {
408
+ const tR0 = performance.now();
409
+ const p1Sols = [];
410
+ let minOverallH = 99;
411
+ const urfDistances = [];
412
+ for (const urf of [0, 1, 2]) {
413
+ const mask = center1Mask(state.centers, urf);
414
+ const h = getCenter1Distance(mask, tables.center1);
415
+ urfDistances.push(h);
416
+ if (h < minOverallH)
417
+ minOverallH = h;
418
+ }
419
+ const path = [];
420
+ const p1Extra = options?.phase1ExtraDepths ?? 3;
421
+ const p1Cap = options?.phase1Cap ?? 400;
422
+ // Per-restart DFS traversal order (null = identity fast path when rng is null).
423
+ const p1Order = rng === null ? null : Int32Array.from(restartOrder(CENTER1_MOVES.length, rng));
424
+ for (let maxD = minOverallH; maxD <= minOverallH + p1Extra; maxD++) {
425
+ for (const urf of [0, 1, 2]) {
426
+ const minH = urfDistances[urf];
427
+ if (maxD < minH)
428
+ continue;
429
+ const mask = center1Mask(state.centers, urf);
430
+ let axisCount = 0;
431
+ const dfs = (m, depth, lm) => {
432
+ if (axisCount >= p1Cap)
433
+ return true;
434
+ const h = getCenter1Distance(m, tables.center1);
435
+ if (h === 0) {
436
+ let rotAlign = [];
437
+ if (m === CENTER1_GOAL_MASKS.rl) {
438
+ rotAlign = [];
439
+ }
440
+ else if (m === CENTER1_GOAL_MASKS.ud) {
441
+ rotAlign = ["z"];
442
+ }
443
+ else if (m === CENTER1_GOAL_MASKS.fb) {
444
+ rotAlign = ["y'"];
445
+ }
446
+ else {
447
+ return false;
448
+ }
449
+ axisCount++;
450
+ p1Sols.push({
451
+ moves: path.slice(0, depth).map((mv) => CENTER1_MOVES[mv]),
452
+ length: depth,
453
+ rotAlign
190
454
  });
191
- if (candidates.length >= 60)
455
+ return false;
456
+ }
457
+ if (depth + h > maxD)
458
+ return false;
459
+ for (let mi = 0; mi < CENTER1_MOVES.length; mi++) {
460
+ const mv = p1Order === null ? mi : p1Order[mi];
461
+ if (lm >= 0 && Math.floor(lm / 3) === Math.floor(mv / 3))
462
+ continue;
463
+ const next = applyCenter1Move(m, tables.center1.moveMaps, mv);
464
+ path[depth] = mv;
465
+ if (dfs(next, depth + 1, mv))
192
466
  return true;
193
467
  }
468
+ return false;
469
+ };
470
+ dfs(mask, 0, -1);
471
+ }
472
+ if (p1Sols.length >= p1Cap)
473
+ break;
474
+ }
475
+ p1Sols.sort((a, b) => a.moves.length - b.moves.length);
476
+ const minP1 = p1Sols[0]?.moves.length ?? 0;
477
+ const tF1End = performance.now();
478
+ const candidates = [];
479
+ const moveLog = new Int32Array(48);
480
+ // Incremental wing tracking stack for phase-2 goal transversal checks:
481
+ // avoids full 6-7 move replaying from scratch across hundreds of thousands of candidate goals.
482
+ // `wpMaskStack[d]` = pairingMaskOf(wpStack[d]) maintained in the same lazy
483
+ // fill, so the per-leaf transversal test is a single compare.
484
+ const wpStack = Array.from({ length: 32 }, () => new Uint8Array(24));
485
+ const wpMaskStack = new Int32Array(32);
486
+ let validWpDepth = 0;
487
+ const wingMaps = getWingMoveMaps();
488
+ // Transversal pruning (see pair-transversal.ts): wing positions per DFS
489
+ // depth (`posStack[d][wing]`), checked against the two-pair PDB over 6
490
+ // disjoint pair-of-pairs in the last TRANSVERSAL_DEPTH levels (the PDB's
491
+ // maximum). Prunes only branches with no transversal goal, so the
492
+ // accepted candidates are unchanged.
493
+ const posStack = Array.from({ length: 33 }, () => new Uint8Array(24));
494
+ const wingPosMove = getWingPositionMoves();
495
+ const TRANSVERSAL_DEPTH = 3;
496
+ let validPosDepth = 0;
497
+ /**
498
+ * Anti-hang work cap for the phase-2 search (successful attempts use
499
+ * ~0.1-0.3M nodes; this only aborts pathological explorations).
500
+ * Exceeding it degrades gracefully: the call returns false and the
501
+ * remaining (prep, length2) combinations still run.
502
+ */
503
+ const deep = options?.deep === true;
504
+ // Wide phase-2 set (28 moves) + its pruning table. Both sets are
505
+ // prefixes of CENTER2_MOVES, so search indices stay valid move-table
506
+ // indices in either mode.
507
+ const c2Wide = options?.center2Wide === true;
508
+ const C2_SEARCH = c2Wide ? CENTER2_SEARCH_MOVES_WIDE : CENTER2_SEARCH_MOVES;
509
+ const cancelFlat = c2Wide ? P2_CANCEL_WIDE_FLAT : P2_CANCEL_FLAT;
510
+ const c2Stride = C2_SEARCH.length;
511
+ const transversalPdb = getTransversalPairPdb(C2_SEARCH.length);
512
+ const canSkipAxis = rng === null && !c2Wide;
513
+ // Per-restart child order (null = identity fast path). Entries stay
514
+ // original move-table indices, so all table lookups are unaffected.
515
+ const p2Order = rng === null ? null : Int32Array.from(restartOrder(C2_SEARCH.length, rng));
516
+ // Default set: chiral tables (goal = ct == 0 && axisDet == 1 exactly, so
517
+ // wrong-chirality goal paths are pruned instead of enumerated). The wide
518
+ // set keeps the relative tables + the axisDet filter at the goal.
519
+ const chiral = c2Wide ? null : getCenter2ChiralTables(tables.center2);
520
+ const c2ctMove = chiral ? chiral.ctMove : tables.center2.ctMove;
521
+ const c2rlMove = tables.center2.rlMove;
522
+ const c2GoalCt = chiral ? chiral.goalCt : 0;
523
+ let c2pruning = chiral ? chiral.pruning : tables.center2.pruning;
524
+ if (c2Wide) {
525
+ if (!tables.center2.pruningWide) {
526
+ throw new Error("4x4 solve: center2Wide requested but pruningWide tables are not loaded — regenerate center2 tables.");
527
+ }
528
+ c2pruning = tables.center2.pruningWide;
529
+ }
530
+ const P2_MAX_NODES = deep ? 24_000_000 : 8_000_000;
531
+ // Hoisted out of the goal path (was read per goal leaf).
532
+ const maxP1Cand = options?.p1CandCap !== undefined ? options.p1CandCap : (deep ? 24 : 16);
533
+ // Smaller pool + shorter extension (was 180/100/14/12 on the fast path):
534
+ // the deep length2 levels are where F2 tails burn. Validated on a 44-state
535
+ // corpus: -16% nodes, identical average length (one +1 in 44).
536
+ const CAND_CAP = deep ? 300 : 120;
537
+ const CAND_MIN = deep ? 180 : 35;
538
+ const P2_MAX_ABS = deep ? 18 : 14;
539
+ const P2_MAX_MIN = deep ? 16 : 10;
540
+ const L123_CAP = options?.maxReductionLen
541
+ ? Math.min(options.maxReductionLen, deep ? 48 : 45)
542
+ : (deep ? 48 : 45);
543
+ const EXT_MX = deep ? 20 : 16;
544
+ let p2nodes = 0;
545
+ let f3calls = 0;
546
+ // Bound the whole sweep, not just each individual IDA* call. A hard
547
+ // candidate pool can otherwise spend thousands of capped calls before
548
+ // reaching the deep retry (corpus-73: 114M nodes in the fast attempt).
549
+ const phase3StartNodes = phase3Solver.epochNodes;
550
+ const phase3NodeBudget = deep ? 16_000_000 : 4_000_000;
551
+ function searchPhase2(c, r, maxl, lm, depth, bridgeState, prep) {
552
+ p2nodes++;
553
+ if (p2nodes > P2_MAX_NODES)
554
+ return false;
555
+ if (c === c2GoalCt && P2_GOAL_RL[r] === 1) {
556
+ if (maxl === 0) {
557
+ while (validWpDepth < depth) {
558
+ const m = moveLog[validWpDepth];
559
+ const base = m * 24;
560
+ const src = wpStack[validWpDepth];
561
+ const dst = wpStack[validWpDepth + 1];
562
+ for (let i = 0; i < 24; i++)
563
+ dst[i] = src[wingMaps[base + i]];
564
+ wpMaskStack[validWpDepth + 1] = pairingMaskOf(dst);
565
+ validWpDepth++;
566
+ }
567
+ if (collectF2Stats)
568
+ f2Stats.goals++;
569
+ // Bit-identical to `hasPairingTransversal(goalWp)`: all 12 pair bits
570
+ // distinct ⟺ the 12-bit mask is full (0xfff).
571
+ if (wpMaskStack[depth] !== 0xfff)
572
+ return false;
573
+ if (collectF2Stats)
574
+ f2Stats.transversalPass++;
575
+ const moves2 = [];
576
+ for (let i = 0; i < depth; i++)
577
+ moves2.push(CENTER2_MOVES[moveLog[i]]);
578
+ const s2 = applyCube4Algorithm(bridgeState, moves2);
579
+ const uAxis = s2.centers[0] % 3;
580
+ const rAxis = s2.centers[4] % 3;
581
+ const fAxis = s2.centers[8] % 3;
582
+ if (collectF2Stats) {
583
+ if (depth < f2Stats.minTransversalL2)
584
+ f2Stats.minTransversalL2 = depth;
585
+ }
586
+ if (axisDet(uAxis, rAxis, fAxis) !== 1) {
587
+ if (collectF2Stats)
588
+ f2Stats.axisRejects++;
589
+ return false;
590
+ }
591
+ if (collectF2Stats) {
592
+ if (depth < f2Stats.minChiralL2)
593
+ f2Stats.minChiralL2 = depth;
594
+ }
595
+ const pairing = encodePairingState(s2.wp);
596
+ if (pairing) {
597
+ const s2CornerParity = cornerPermutationParity(s2.cp);
598
+ const eXc = (pairing.parity ^ s2CornerParity);
599
+ const ct3 = encodeCenter3(s2, eXc).coordinate;
600
+ const cdist = tables.center3.pruning[ct3];
601
+ if (cdist !== 0xff && cdist !== undefined) {
602
+ const symIdx = getMvSymFrom(pairing.edge, pairing.edge, 20, sym.sym2Raw, sym.sym2Mask, sym.raw2Sym, sym.mvrot, sym.mvroto);
603
+ const edist = tables.edge3.distances.length >= 31006080
604
+ ? tables.edge3.distances[symIdx >> 3]
605
+ : (tables.edge3.distances[(symIdx >> 3) >> 1] >>
606
+ (((symIdx >> 3) & 1) * 4)) &
607
+ 0x0f;
608
+ const moves2Remapped = prep.totalRot.length === 0
609
+ ? moves2
610
+ : rotateAlgorithm(moves2, invertRotationSequence(prep.totalRot));
611
+ const hcCoord = tables.hc ? hcDenseIndex(tables.hc, encodeHcPdb(s2.centers)) : -1;
612
+ const hcRaw = hcCoord >= 0 && tables.hc ? tables.hc.distances[hcCoord] : 0;
613
+ const hdist = hcRaw === 0x0f ? 0 : hcRaw;
614
+ let pdist = 0;
615
+ let pdistHigh = 0;
616
+ if (tables.c3PairDist) {
617
+ const c3Base = ct3 * 144;
618
+ for (let s = 0; s < 12; s++) {
619
+ const idx = c3Base + s * 12 + pairing.edge[s];
620
+ const d = (idx & 1) === 0 ? (tables.c3PairDist[idx >> 1] & 0x0f) : (tables.c3PairDist[idx >> 1] >> 4);
621
+ if (d > pdist)
622
+ pdist = d;
623
+ if (d >= 8)
624
+ pdistHigh++;
625
+ }
626
+ }
627
+ const cand = {
628
+ moves12: [...prep.prefix, ...moves2Remapped],
629
+ length12: prep.prefix.length + moves2.length,
630
+ ct3,
631
+ cdist,
632
+ edge: pairing.edge,
633
+ edist,
634
+ hdist,
635
+ pdist,
636
+ hcCoord,
637
+ rotCost: 0,
638
+ value: prep.prefix.length + moves2.length + Math.max(cdist, edist, hdist, pdist) + (pdistHigh >= 4 ? 2 : (pdistHigh >= 2 ? 1 : 0)),
639
+ state: s2,
640
+ p1: prep.p1,
641
+ totalRot: prep.totalRot
642
+ };
643
+ if (candidates.length < CAND_CAP) {
644
+ candidates.push(cand);
645
+ if (candidates.length === CAND_CAP) {
646
+ candidates.sort((a, b) => a.value - b.value);
647
+ }
648
+ }
649
+ else if (cand.value < candidates[candidates.length - 1].value) {
650
+ candidates[candidates.length - 1] = cand;
651
+ for (let j = candidates.length - 1; j > 0 && candidates[j].value < candidates[j - 1].value; j--) {
652
+ const tmp = candidates[j];
653
+ candidates[j] = candidates[j - 1];
654
+ candidates[j - 1] = tmp;
655
+ }
656
+ }
657
+ p1CandCount++;
658
+ if (p1CandCount >= maxP1Cand)
659
+ return true;
660
+ }
661
+ }
194
662
  }
663
+ return false;
664
+ }
665
+ if (maxl === 0)
666
+ return false;
667
+ const c2RowC = c * CENTER2_MOVES.length;
668
+ const c2RowR = r * CENTER2_MOVES.length;
669
+ for (let mi = 0; mi < C2_SEARCH.length; mi++) {
670
+ const m = p2Order === null ? mi : p2Order[mi];
671
+ if (lm >= 0 && cancelFlat[lm * c2Stride + m]) {
672
+ continue;
673
+ }
674
+ const nc = c2ctMove[c2RowC + m];
675
+ const nr = c2rlMove[c2RowR + m];
676
+ const prun = c2pruning[nc * CENTER2_RL_STATES + nr];
677
+ if (prun >= maxl) {
678
+ if (prun > maxl && canSkipAxis) {
679
+ mi = SKIP_AXIS_2[m] - 1;
680
+ }
681
+ continue;
682
+ }
683
+ let childPosValid = false;
684
+ if (maxl - 1 < TRANSVERSAL_DEPTH) {
685
+ // Lazy fill (like wpStack): replay the path down to this node.
686
+ while (validPosDepth < depth) {
687
+ const src = posStack[validPosDepth];
688
+ const dst = posStack[validPosDepth + 1];
689
+ const row = moveLog[validPosDepth] * 24;
690
+ for (let w = 0; w < 24; w++)
691
+ dst[w] = wingPosMove[row + src[w]];
692
+ validPosDepth++;
693
+ }
694
+ const parentPos = posStack[depth];
695
+ const childPos = posStack[depth + 1];
696
+ const posRow = m * 24;
697
+ const limit = maxl - 1;
698
+ let blocked = false;
699
+ // Group by group (4 wings = 2 pairs each), so a blocked child only
700
+ // pays for the groups actually checked.
701
+ for (let q = 0; q < 24; q += 4) {
702
+ const a0 = wingPosMove[posRow + parentPos[q]];
703
+ const a1 = wingPosMove[posRow + parentPos[q + 1]];
704
+ const b0 = wingPosMove[posRow + parentPos[q + 2]];
705
+ const b1 = wingPosMove[posRow + parentPos[q + 3]];
706
+ if (transversalPdb[PAIR_INDEX[a0 * 24 + a1] * PAIR_STATES + PAIR_INDEX[b0 * 24 + b1]] > limit) {
707
+ blocked = true;
708
+ break;
709
+ }
710
+ childPos[q] = a0;
711
+ childPos[q + 1] = a1;
712
+ childPos[q + 2] = b0;
713
+ childPos[q + 3] = b1;
714
+ }
715
+ if (blocked)
716
+ continue;
717
+ childPosValid = true;
718
+ }
719
+ moveLog[depth] = m;
720
+ if (validWpDepth > depth)
721
+ validWpDepth = depth;
722
+ if (validPosDepth > depth)
723
+ validPosDepth = depth;
724
+ if (childPosValid)
725
+ validPosDepth = depth + 1;
726
+ if (searchPhase2(nc, nr, maxl - 1, m, depth + 1, bridgeState, prep))
727
+ return true;
195
728
  }
196
729
  return false;
197
730
  }
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])) {
731
+ let p1CandCount = 0;
732
+ let MAX_P2 = 8;
733
+ // Phase-1 application + the phase-2 bridge depend only on the phase-1
734
+ // solution, not on the phase-2 target length: compute them once instead
735
+ // of redoing the work for every length12 iteration.
736
+ // Alignment is treated purely as a coordinate frame rotation (matching
737
+ // csTimer's sym frame remapping), adding 0 physical moves to prefix.
738
+ const preps = [];
739
+ for (const p1 of p1Sols) {
740
+ const s1 = applyCube4Algorithm(state, p1.moves);
741
+ const s1Aligned = p1.rotAlign.length === 0 ? s1 : applyCubeRotation(s1, p1.rotAlign);
742
+ const bridge = center2Bridge(s1Aligned);
743
+ if (!bridge)
202
744
  continue;
745
+ const totalRot = [...p1.rotAlign, ...bridge.rotation];
746
+ const prefix = p1.moves;
747
+ const ct = chiral ? encodeCenter2ChiralCt(bridge.state) : bridge.encoded.ct;
748
+ const prun = c2pruning[ct * CENTER2_RL_STATES + bridge.encoded.rl];
749
+ // Paired wings lookahead: check how many wings are already paired in bridge.state
750
+ let pairedWings = 0;
751
+ const wp = bridge.state.wp;
752
+ for (let pair = 0; pair < 12; pair++) {
753
+ if (Math.floor(wp[pair * 2] / 2) === Math.floor(wp[pair * 2 + 1] / 2)) {
754
+ pairedWings++;
755
+ }
203
756
  }
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;
757
+ // Lookahead composite score: total estimated centers penalized by already-paired wings
758
+ const estCenters = prefix.length + prun;
759
+ const score = estCenters * 2 - Math.min(4, pairedWings);
760
+ preps.push({ p1, prefix, bridgeState: bridge.state, totalRot, ct, rl: bridge.encoded.rl, prun, score });
212
761
  }
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;
762
+ // Ascending lookahead score (lowest total estimated center moves + wing bonus),
763
+ // tie-broken by lower phase-2 pruning bound then shorter prefix length
764
+ preps.sort((a, b) => (a.score - b.score) || (a.prun - b.prun) || (a.prefix.length - b.prefix.length));
765
+ // Filter: keep the best preps to avoid wasting phase-2 DFS work on suboptimal centers
766
+ const PREP_CAP = options?.prepCap !== undefined ? options.prepCap : (deep ? 48 : 32);
767
+ if (preps.length > PREP_CAP) {
768
+ preps.length = PREP_CAP;
769
+ }
770
+ // Per-restart tie order only (the ascending order above is preserved).
771
+ shuffleTies(preps, (p) => p.score, rng);
772
+ // Passes after the first one only extend MAX_P2 by one: every smaller
773
+ // length2 was already searched (deterministic — rerunning would push the
774
+ // same goals again as duplicates and crowd the 45 cap), so skip them.
775
+ // Tracked exactly per (prep, length2): this also fills holes left when a
776
+ // pass breaks early at the 45 cap, and is reused by the diversity
777
+ // extension below.
778
+ const searchedL2 = new Set();
779
+ let lastBestValue = 999;
780
+ let stagnantLengths = 0;
781
+ do {
782
+ OUTER: for (let length12 = minP1; length12 < minP1 + 16; length12++) {
783
+ for (let pi = 0; pi < preps.length; pi++) {
784
+ const prep = preps[pi];
785
+ if (prep.prefix.length > length12)
786
+ continue;
787
+ const length2 = length12 - prep.prefix.length;
788
+ if (length2 > MAX_P2 || length2 < 0)
789
+ continue;
790
+ if (prep.prun > length2)
791
+ continue;
792
+ const key = pi * 64 + length2;
793
+ if (searchedL2.has(key))
794
+ continue;
795
+ searchedL2.add(key);
796
+ p1CandCount = 0;
797
+ wpStack[0].set(prep.bridgeState.wp);
798
+ for (let p = 0; p < 24; p++)
799
+ posStack[0][prep.bridgeState.wp[p]] = p;
800
+ validPosDepth = 0;
801
+ wpMaskStack[0] = pairingMaskOf(prep.bridgeState.wp);
802
+ validWpDepth = 0;
803
+ searchPhase2(prep.ct, prep.rl, length2, -1, 0, prep.bridgeState, prep);
804
+ if (candidates.length >= CAND_CAP &&
805
+ candidates[0].value <= length12 + 9 &&
806
+ (candidates[0].edist <= 10 || length12 >= minP1 + 3)) {
807
+ break OUTER;
808
+ }
809
+ }
810
+ if (options?.stagnationCut !== false && candidates.length >= CAND_MIN) {
811
+ stagnationStats.checks++;
812
+ // NOTE: candidates is only sorted once it reaches CAND_CAP, so
813
+ // candidates[0] is NOT the best below the cap — scan the true min.
814
+ let curBest = Infinity;
815
+ for (let ci = 0; ci < candidates.length; ci++) {
816
+ const v = candidates[ci].value;
817
+ if (v < curBest)
818
+ curBest = v;
819
+ }
820
+ if (curBest >= lastBestValue) {
821
+ stagnantLengths++;
822
+ if (stagnantLengths >= 2) {
823
+ stagnationStats.cuts++;
824
+ break OUTER;
825
+ }
826
+ }
827
+ else {
828
+ lastBestValue = curBest;
829
+ stagnantLengths = 0;
830
+ }
234
831
  }
235
832
  }
833
+ MAX_P2++;
834
+ } while ((candidates.length === 0 && MAX_P2 <= P2_MAX_ABS) || (candidates.length < CAND_MIN && MAX_P2 <= P2_MAX_MIN));
835
+ if (candidates.length === 0) {
836
+ throw new Cube4Phase2CapError("4x4 solve: no valid phase 2 candidates found.");
236
837
  }
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)
838
+ const tF2End = performance.now();
839
+ // Cheap-fix goal filter (see Cube4SolveOptions.maxFixMoves). The deep
840
+ // fallback widens it back to 4 (legacy, always satisfiable) so a hard
841
+ // state can never fail on the filter alone.
842
+ const maxFixMoves = (options?.maxFixMoves ?? 4) + (deep ? 2 : 0);
843
+ const validReductions = [];
844
+ /**
845
+ * Per-candidate IDA* proofs shared across all sweep stages: the greatest
846
+ * phase-3 length exhaustively proved empty for that candidate. Entries
847
+ * are only written on clean proofs (no cap abort, no goal seen, no TT
848
+ * hit, complete excess info), so skipping those lengths is exact.
849
+ */
850
+ const p3Proven = new Map();
851
+ /**
852
+ * Sync downstream chain for a phase-3 goal sequence: reduction check,
853
+ * orientation remap, 3x3 conversion + phase-1 heuristic. Returns the
854
+ * ValidReduction or null. Shared by the sweep validator and the polish
855
+ * pass (which retries the winner one length shorter).
856
+ */
857
+ function buildValidReduction(cand, moves3) {
858
+ const reduced = applyCube4Algorithm(cand.state, moves3);
859
+ if (checkCube4Reduction(reduced) !== null)
860
+ return null;
861
+ const totalRot = cand.totalRot;
862
+ const invTotalRot = totalRot.length === 0 ? [] : invertRotationSequence(totalRot);
863
+ const moves3Remapped = totalRot.length === 0 ? moves3 : rotateAlgorithm(moves3, invTotalRot);
864
+ const reducedOriginal = totalRot.length === 0 ? reduced : applyCubeRotation(reduced, invTotalRot);
865
+ const key = `${reducedOriginal.centers[0]},${reducedOriginal.centers[4]},${reducedOriginal.centers[8]}`;
866
+ const path = VALID_24_ORIENTATIONS.get(key);
867
+ if (!path)
868
+ return null;
869
+ const rotToStandard = invertRotationSequence(path);
870
+ const standardReduced = applyCubeRotation(reducedOriginal, rotToStandard);
871
+ const rotMoves = rotToStandard.flatMap((r) => ROT_MOVES[r]);
872
+ if (rotMoves.length > maxFixMoves)
873
+ return null;
874
+ if (typeof process !== "undefined" && process.env?.CUBE4_ROT_STATS === "1" && rotStats.length < 200) {
875
+ rotStats.push({
876
+ totalRot: totalRot.join(","),
877
+ rotToStandard: rotToStandard.join(","),
878
+ rotLen: rotToStandard.reduce((n, rr) => n + ROT_MOVES[rr].length, 0)
879
+ });
880
+ }
881
+ // The orientation key only covers 3 of the 24 center slots. A reduced
882
+ // arrangement outside the rotation orbit (e.g. a reflected one) can
883
+ // collide with a rotation's key, in which case rotating by `path` does
884
+ // NOT leave standard centers — the 3x3 finish would solve a different
885
+ // color scheme and the resulting solution would be garbage. Reject.
886
+ for (let i = 0; i < 24; i++) {
887
+ if (standardReduced.centers[i] !== SOLVED_CENTERS[i])
888
+ return null;
889
+ }
890
+ const cube3State = toCube3State(standardReduced);
891
+ if (!cube3State)
892
+ return null;
893
+ const h3 = tables.cube3Phase1 ? getTriAxialCube3Heuristic(standardReduced, tables.cube3Phase1) : 0;
894
+ // The reduction + rotation prefix as it will be emitted (original frame):
895
+ // apply(state, [...moves12, ...moves3Remapped ... rotMoves]) = standardReduced.
896
+ // Priced with the fix at its best position (see placeRotationFix).
897
+ const simplifiedReduction = placeRotationFix([...cand.moves12, ...moves3Remapped], rotToStandard, []);
898
+ return {
899
+ cand,
900
+ moves3,
901
+ moves3Remapped,
902
+ rotPath: path,
903
+ rotToStandard,
904
+ rotMoves,
905
+ standardReduced,
906
+ h3,
907
+ totalEst: simplifiedReduction.length + h3
908
+ };
909
+ }
910
+ // Defaults 1 × 5 (was 3 × 3): with the continuous finish, extra center
911
+ // candidates stopped paying. cc:0..31: 45.19 moves @ 673 ms vs 45.16 @
912
+ // 1042 ms (2×3: 45.25 @ 799; 1×8: 45.25 @ 691).
913
+ const centersBeam = Math.max(1, options?.centersBeam ?? 1);
914
+ const edgesPerCenter = Math.max(1, options?.edgesPerCenter ?? 5);
915
+ const maxReductionsTarget = options?.finishTries !== undefined
916
+ ? Math.max(1, options.finishTries)
917
+ : (centersBeam * edgesPerCenter);
918
+ /**
919
+ * One exact-length sweep over a value-sorted pool: tries increasing
920
+ * totals, collects up to maxReductionsTarget valid reductions using
921
+ * hierarchical beam search (centersBeam distinct centers x edgesPerCenter edge pairings).
922
+ * Shared across all stages below.
923
+ *
924
+ * Bounded by `maxCalls` solveLength calls (not wall-clock): easy states
925
+ * use ~100, so adversarial pools fail fast deterministically on any
926
+ * machine instead of grinding through the whole pool.
927
+ */
928
+ function sweepPool(pool, cfg) {
929
+ const candReductions = new Map();
930
+ const distinctCenters = new Set();
931
+ let foundAtLength = null;
932
+ // The rotation fix (rotMoves) is priced INTO totalEst and varies 2-4
933
+ // moves per goal PATH (the end scheme depends on the path). A goal one
934
+ // total-step deeper with a 2-move fix beats a shallow goal with a 4-move
935
+ // fix, so keep collecting a few steps past the first find and let
936
+ // totalEst decide (was: foundAtLength + 1 with needed + 3 goals per
937
+ // call, which discarded fix-cheap alternatives).
938
+ OUTER_P3: for (let length123 = pool[0].value; length123 < L123_CAP; length123++) {
939
+ if (foundAtLength !== null && length123 > foundAtLength + 3)
255
940
  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)
941
+ // Sweep the whole (sorted) pool: see sortTop rationale.
942
+ for (let i = 0; i < pool.length; i++) {
943
+ const cand = pool[i];
944
+ if (cand.value > length123)
945
+ break;
946
+ const length3 = length123 - cand.length12;
947
+ const minL3 = Math.max(cand.edist, cand.cdist, cand.hdist, cand.pdist ?? 0);
948
+ if (length3 > cfg.maxLength3 || length3 < minL3)
264
949
  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)
950
+ // IDA* threshold propagation: a previous exact-length call may have
951
+ // exhaustively proved this candidate empty through a longer length.
952
+ if ((p3Proven.get(cand) ?? -1) >= length3)
269
953
  continue;
270
- solvedCand = cand;
271
- solvedMoves3 = moves3;
272
- rotPath = path;
273
- rotToStandard = invertRotationSequence(rotPath);
274
- standardReduced = applyCubeRotation(reduced, rotToStandard);
275
- break;
954
+ const candCount = candReductions.get(cand) ?? 0;
955
+ if (candCount >= edgesPerCenter)
956
+ continue;
957
+ if (distinctCenters.size >= centersBeam && !distinctCenters.has(cand))
958
+ continue;
959
+ if (cand.edist <= length3 && cand.cdist <= length3 && cand.hdist <= length3 && (cand.pdist ?? 0) <= length3) {
960
+ const remainingNodes = phase3NodeBudget - (phase3Solver.epochNodes - phase3StartNodes);
961
+ if (remainingNodes <= 0) {
962
+ if (validReductions.length > 0)
963
+ return;
964
+ throw new Cube4Phase3CapError("4x4 solve: phase 3 total node budget exhausted.");
965
+ }
966
+ const nodeLimit = Math.min(remainingNodes, length3 <= 12 ? 80000 : Math.max(45000, cfg.maxNodes));
967
+ f3calls++;
968
+ const needed = edgesPerCenter - candCount;
969
+ const candReductionsBuffer = [];
970
+ // Collect beyond `needed`: goal paths at the same length carry
971
+ // different rotation fixes (2 vs 4 moves), and the totalEst sort
972
+ // below needs the variety to pick a cheap-fix end.
973
+ const maxToCollect = Math.min(24, needed + 9);
974
+ const result = phase3Solver.solveLengthProven(cand.edge, cand.ct3, cand.edist, length3, tables.center3, tables.edge3.distances, nodeLimit,
975
+ // Goal budget per call: with the cheap-fix filter most goal ends
976
+ // are rejected, so the walk must be allowed to examine more of
977
+ // them before giving up on this (candidate, length3).
978
+ 48, (moves3) => {
979
+ const red = buildValidReduction(cand, moves3);
980
+ if (!red)
981
+ return false;
982
+ candReductionsBuffer.push(red);
983
+ // <=-search: goals may land shorter than the length3 bound —
984
+ // track the true total for the post-find collection window.
985
+ const total = cand.length12 + moves3.length;
986
+ if (foundAtLength === null || total < foundAtLength)
987
+ foundAtLength = total;
988
+ return candReductionsBuffer.length >= maxToCollect;
989
+ },
990
+ // hc mid-search prune disabled: on a 44-state corpus the per-node
991
+ // hc lookups cost more than they prune, and the altered
992
+ // capped/success pattern shifts the stop-at-3 valid selection
993
+ // toward shorter reductions (which finish as well or better on
994
+ // average). The exact hdist call gate above, the candidate hdist
995
+ // ranking, and the polish-pass hc bounds below all stay.
996
+ undefined, -1, tables.c3PairDist);
997
+ if (candReductionsBuffer.length > 0) {
998
+ // Sort solutions for this center candidate by totalEst (cancellation-aware length + tri-axial 3x3 heuristic)
999
+ candReductionsBuffer.sort((a, b) => a.totalEst - b.totalEst);
1000
+ const toAdd = candReductionsBuffer.slice(0, needed);
1001
+ for (const red of toAdd) {
1002
+ validReductions.push(red);
1003
+ }
1004
+ candReductions.set(cand, candCount + toAdd.length);
1005
+ distinctCenters.add(cand);
1006
+ }
1007
+ // Predicate-scoped proof (same buildValidReduction filter for this
1008
+ // candidate across all its calls): skip every settled length.
1009
+ const proven = result.validatedThrough;
1010
+ if (result.moves === null && proven >= length3) {
1011
+ const prev = p3Proven.get(cand) ?? -1;
1012
+ if (proven > prev)
1013
+ p3Proven.set(cand, proven);
1014
+ }
1015
+ // The finish loop attempts reductions up to maxReductionsTarget
1016
+ // (with a wider collection cap so cheap-fix ends at later length
1017
+ // steps can still displace expensive-fix ones by totalEst).
1018
+ if (validReductions.length >= maxReductionsTarget + 9) {
1019
+ break OUTER_P3;
1020
+ }
1021
+ }
1022
+ }
1023
+ }
1024
+ }
1025
+ const sortTop = (arr) => {
1026
+ // No truncation: value misranks solvability (short bounds, hard joints),
1027
+ // and truncating demonstrably discards winners (corpus-18/49). Cost lands
1028
+ // only on hard states (early-stop rules); easy states stop early anyway.
1029
+ const sorted = [...arr].sort((a, b) => a.value - b.value);
1030
+ // Per-restart tie order only (ascending value order is preserved, so the
1031
+ // sweep's `value > length123` break stays valid).
1032
+ shuffleTies(sorted, (c) => c.value, rng);
1033
+ return sorted;
1034
+ };
1035
+ // Sweeps with growing budgets; longitudes extend dynamically (reference
1036
+ // style) while nothing is found, instead of fixed caps. Easy states only
1037
+ // pay the first sweep. The length3 caps are NOT redundant re-walks: the
1038
+ // ladder widens the pairing cap ONLY when nothing was found at all, and the
1039
+ // narrower caps keep early sweeps on short pairings (measured: a single
1040
+ // merged sweep with maxLength3 24 is ~20% SLOWER with identical output).
1041
+ // NOTE: lowering these caps was tried (20k/16k) and reverted: capped calls
1042
+ // change which valids are found (±2 moves on the corpus). Only admissible
1043
+ // heuristic strengthenings are length-safe here.
1044
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 14 });
1045
+ if (validReductions.length === 0) {
1046
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 16 });
1047
+ }
1048
+ if (validReductions.length === 0) {
1049
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 18 });
1050
+ }
1051
+ if (validReductions.length === 0) {
1052
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 20 });
1053
+ }
1054
+ if (validReductions.length === 0) {
1055
+ sweepPool(sortTop(candidates), { maxNodes: 30000, maxLength3: 24 });
1056
+ }
1057
+ if (validReductions.length === 0 && deep) {
1058
+ sweepPool(sortTop(candidates), { maxNodes: 60000, maxLength3: 27 });
1059
+ }
1060
+ // Diversity extension (only when both sweeps found nothing): the pool's
1061
+ // joints are jointly hard, so gather DEEPER phase-2 solutions (longer
1062
+ // length2 = different wings) and sweep those. Only hard states pay this.
1063
+ if (validReductions.length === 0 && !options?.maxReductionLen) {
1064
+ const poolStart = candidates.length;
1065
+ let MX = MAX_P2;
1066
+ EXTEND: while (candidates.length - poolStart < 40 && MX <= EXT_MX) {
1067
+ for (let length12 = minP1; length12 < minP1 + 18; length12++) {
1068
+ for (let pi = 0; pi < preps.length; pi++) {
1069
+ const prep = preps[pi];
1070
+ if (prep.prefix.length > length12)
1071
+ break;
1072
+ const length2 = length12 - prep.prefix.length;
1073
+ if (length2 > MX || length2 < 0)
1074
+ continue;
1075
+ if (prep.prun > length2)
1076
+ continue;
1077
+ const key = pi * 64 + length2;
1078
+ if (searchedL2.has(key))
1079
+ continue;
1080
+ searchedL2.add(key);
1081
+ p1CandCount = 0;
1082
+ wpStack[0].set(prep.bridgeState.wp);
1083
+ for (let p = 0; p < 24; p++)
1084
+ posStack[0][prep.bridgeState.wp[p]] = p;
1085
+ validPosDepth = 0;
1086
+ wpMaskStack[0] = pairingMaskOf(prep.bridgeState.wp);
1087
+ validWpDepth = 0;
1088
+ searchPhase2(prep.ct, prep.rl, length2, -1, 0, prep.bridgeState, prep);
1089
+ if (candidates.length - poolStart >= 40)
1090
+ break EXTEND;
1091
+ }
276
1092
  }
1093
+ MX++;
1094
+ }
1095
+ const fresh = sortTop(candidates.slice(poolStart));
1096
+ if (fresh.length > 0) {
1097
+ sweepPool(fresh, { maxNodes: 15000, maxLength3: 18 });
1098
+ }
1099
+ if (validReductions.length === 0 && fresh.length > 0) {
1100
+ sweepPool(fresh, { maxNodes: 30000, maxLength3: 20 });
1101
+ }
1102
+ }
1103
+ if (validReductions.length === 0) {
1104
+ throw new Cube4Phase3CapError("4x4 solve: phase 3 reduction failed across all candidates.");
1105
+ }
1106
+ // Sort reductions by Total Estimated Moves (Reduction length + 3x3 Phase 1 lower bound)
1107
+ validReductions.sort((a, b) => a.totalEst - b.totalEst);
1108
+ const tFinishStart = performance.now();
1109
+ let bestSolution = null;
1110
+ let minTotalMoves = 999;
1111
+ let bestPhases;
1112
+ let bestRed = null;
1113
+ // Best-of among the first two (as before); any further reductions are
1114
+ // only attempted when those both failed, so a flaky 3x3 finish cannot
1115
+ // sink the whole attempt while the common case costs nothing extra.
1116
+ // Best-of among the first three (phase-4 is cheap now); further
1117
+ // reductions are only attempted when those all failed.
1118
+ const finishTries = options?.finishTries ?? maxReductionsTarget;
1119
+ const collectFinishStats = typeof process !== "undefined" && process.env?.CUBE4_FINISH_STATS === "1";
1120
+ // Empirical finish lower bound (see finishStats): every observed finish
1121
+ // ran 11-16 moves ABOVE `totalEst` (continuous finish: 67 finishes over 16
1122
+ // seeds, gap = totalEst - finalLen in [-16, -11]; the legacy finish was
1123
+ // [-16, -12]) because `h3` only bounds the cube3 PHASE-1 length while the
1124
+ // finish is two-phase. A reduction whose totalEst + 11 cannot strictly
1125
+ // beat the current best therefore cannot win, and its finish is skipped
1126
+ // entirely. If a state ever lands a finish within 11 of the phase-1 bound,
1127
+ // this degrades to a slightly longer (still exact,
1128
+ // still valid) scramble for that state — never an incorrect one.
1129
+ const FINISH_LB_BIAS = 11;
1130
+ const screenTop = Math.max(0, Math.floor(options?.finishScreenTop ?? 0));
1131
+ const screened = [];
1132
+ /** Finishes one reduction; records it as the best when shorter. */
1133
+ async function finishReduction(red, effort) {
1134
+ const cube3State = toCube3State(red.standardReduced);
1135
+ if (!cube3State)
1136
+ return null;
1137
+ let cube3Solution;
1138
+ try {
1139
+ cube3Solution = await solveCube3(cube3State, effort);
1140
+ }
1141
+ catch {
1142
+ return null;
1143
+ }
1144
+ // Frame invariant (verified): apply(state, [...moves12, ...moves3Remapped])
1145
+ // is exactly `reducedOriginal`, and `reducedOriginal · rotMoves(r)`
1146
+ // (= applyCubeRotation(_, r)) is `standardReduced`, which the cube3
1147
+ // finish C solves. So the solution in the ORIGINAL frame is
1148
+ // X ++ rotMoves(r) ++ C.
1149
+ // Two previously-tried assemblies are WRONG:
1150
+ // - [rot_r(X), C] solves ρ_r(state), not state (the observed adaptive
1151
+ // whole-cube-rotation bug: apply(solved, invert(moves)) = ρ_r(T));
1152
+ // - [X, rot_{-r}(C)] lands on ρ_{-r}(solved) ≠ solved, because a
1153
+ // whole-cube rotation does NOT leave the canonical solved state
1154
+ // invariant (it permutes face colors in the absolute frame).
1155
+ // `placeRotationFix` keeps that effect but may move the rotMoves(r)
1156
+ // block anywhere in the sequence (re-mapping what follows it) where it
1157
+ // cancels against adjacent wide moves.
1158
+ const simplified = placeRotationFix([...red.cand.moves12, ...red.moves3Remapped], red.rotToStandard, cube3Solution.moves);
1159
+ if (collectFinishStats) {
1160
+ finishStats.finishes++;
1161
+ const gap = red.totalEst - simplified.length;
1162
+ if (gap < finishStats.gapMin)
1163
+ finishStats.gapMin = gap;
1164
+ if (gap > finishStats.gapMax)
1165
+ finishStats.gapMax = gap;
1166
+ finishStats.gapSum += gap;
1167
+ finishStats.gapN++;
277
1168
  }
278
- if (solvedCand)
1169
+ if (simplified.length < minTotalMoves) {
1170
+ minTotalMoves = simplified.length;
1171
+ bestSolution = simplified;
1172
+ bestPhases = {
1173
+ length12: red.cand.length12,
1174
+ length1: red.cand.p1.moves.length,
1175
+ length2: red.cand.length12 - red.cand.p1.moves.length,
1176
+ length3: red.moves3.length,
1177
+ finish: cube3Solution.moves.length
1178
+ };
1179
+ bestRed = red;
1180
+ }
1181
+ return simplified;
1182
+ }
1183
+ for (let i = 0; i < validReductions.length; i++) {
1184
+ if (i >= finishTries && bestSolution)
279
1185
  break;
1186
+ const red = validReductions[i];
1187
+ if (bestSolution !== null && red.totalEst + FINISH_LB_BIAS >= minTotalMoves) {
1188
+ finishStats.skipped++;
1189
+ continue;
1190
+ }
1191
+ const done = await finishReduction(red, screenTop > 0 ? "screen" : "full");
1192
+ if (done)
1193
+ screened.push({ red, total: done.length });
1194
+ }
1195
+ // Stage 2: the best screened reductions get the full-effort finish.
1196
+ if (screenTop > 0) {
1197
+ screened.sort((a, b) => a.total - b.total);
1198
+ for (const { red } of screened.slice(0, screenTop)) {
1199
+ if (red.totalEst + FINISH_LB_BIAS >= minTotalMoves)
1200
+ continue;
1201
+ await finishReduction(red, "full");
1202
+ }
1203
+ }
1204
+ if (!bestSolution || !bestRed) {
1205
+ throw new Cube4FinishCapError("4x4 solve: reduction failed during the 3x3 finish across all valid reductions.");
1206
+ }
1207
+ // Polish pass: the sweep takes the first valid sequence per exact
1208
+ // length, which is often one above optimal. Retry the winner one length
1209
+ // shorter with a large budget (up to 2 iterations). Gated on totals
1210
+ // above target so easy states never pay it.
1211
+ const tPolishStart = performance.now();
1212
+ // Polish the winner plus the runner-up by totalEst (was: winner only).
1213
+ // Runner-up shortenings get their own finish and can only lower the min
1214
+ // over finished totals; easy states skip the inner loop via the length
1215
+ // gate below, so the extra pass costs ~nothing there.
1216
+ const redToPolish = options?.deepPolish
1217
+ ? validReductions.slice(0, 3)
1218
+ : [bestRed, ...validReductions.filter((r) => r !== bestRed)].slice(0, 2);
1219
+ for (const r of redToPolish) {
1220
+ let curRed = r;
1221
+ // The runner-up gets a cheap probe budget: its shortening is a bonus,
1222
+ // and a full 150k grind on tail states cost seconds for nothing. It is
1223
+ // also skipped entirely unless the total is high enough to matter.
1224
+ const polishBudget = r === bestRed ? 150000 : 30000;
1225
+ // NOTE: with the <=-length phase-3 search the sweep already enumerates
1226
+ // shorter goals, so the polish is a second-chance pass only (measured:
1227
+ // a wider gate/budget found nothing and cost +32% p3 nodes).
1228
+ for (let iter = 0; iter < 4 && (minTotalMoves > 43 || curRed.moves3.length > 11); iter++) {
1229
+ const cand = curRed.cand;
1230
+ const shorterLen = curRed.moves3.length - 1;
1231
+ if (shorterLen < cand.edist || shorterLen < cand.cdist || shorterLen < cand.hdist || shorterLen < (cand.pdist ?? 0))
1232
+ break;
1233
+ f3calls++;
1234
+ // Unified polish: accept any goal path with a strictly better
1235
+ // totalEst at the same or shorter length — covers both a shorter
1236
+ // phase-3 path and a cheaper rotation fix (the fix is priced into
1237
+ // totalEst and varies 2-4 moves per goal path).
1238
+ const shorter = phase3Solver.solveLengthValid(cand.edge, cand.ct3, cand.edist, curRed.moves3.length, tables.center3, tables.edge3.distances, polishBudget, 64, (moves3) => {
1239
+ const nr = buildValidReduction(cand, moves3);
1240
+ return nr !== null && nr.totalEst < curRed.totalEst;
1241
+ }, tables.hc, cand.hcCoord, tables.c3PairDist);
1242
+ if (!shorter)
1243
+ break;
1244
+ const red = buildValidReduction(cand, shorter);
1245
+ if (!red)
1246
+ break;
1247
+ const cube3State = toCube3State(red.standardReduced);
1248
+ if (!cube3State)
1249
+ break;
1250
+ let cube3Solution;
1251
+ try {
1252
+ cube3Solution = await solveCube3(cube3State);
1253
+ }
1254
+ catch {
1255
+ break;
1256
+ }
1257
+ // Same frame invariant as the finish loop: X ++ rotMoves(r) ++ C.
1258
+ const simplified = placeRotationFix([...red.cand.moves12, ...red.moves3Remapped], red.rotToStandard, cube3Solution.moves);
1259
+ if (simplified.length < minTotalMoves) {
1260
+ minTotalMoves = simplified.length;
1261
+ bestSolution = simplified;
1262
+ curRed = red;
1263
+ bestPhases = {
1264
+ length12: red.cand.length12,
1265
+ length1: red.cand.p1.moves.length,
1266
+ length2: red.cand.length12 - red.cand.p1.moves.length,
1267
+ length3: red.moves3.length,
1268
+ finish: cube3Solution.moves.length
1269
+ };
1270
+ }
1271
+ else {
1272
+ break;
1273
+ }
1274
+ }
1275
+ }
1276
+ accP2 += p2nodes;
1277
+ accF3calls += f3calls;
1278
+ accF1Ms += tF1End - tR0;
1279
+ accF2Ms += tF2End - tF1End;
1280
+ accF3Ms += tFinishStart - tF2End;
1281
+ accFinishMs += tPolishStart - tFinishStart;
1282
+ accPolishMs += performance.now() - tPolishStart;
1283
+ // Final invariant: the emitted solution must solve the INPUT state
1284
+ // exactly (no rotation tolerance). Fail loudly rather than return a
1285
+ // solution that does not resolve. One replay of ~45 moves — negligible
1286
+ // next to the search cost.
1287
+ if (!isSolvedCube4State(applyCube4Algorithm(state, bestSolution))) {
1288
+ throw new Error("4x4 solve: internal verification failed — the solution does not solve the input state.");
1289
+ }
1290
+ return { moves: bestSolution, phases: bestPhases };
1291
+ };
1292
+ let bestMoves = null;
1293
+ let bestPhasesOverall;
1294
+ let lastRestartError = null;
1295
+ for (let restart = 0; restart < totalRestarts; restart++) {
1296
+ const rng = totalRestarts > 1
1297
+ ? mulberry32((hashCube4State(state) ^ Math.imul(restart + 1, 0x9e3779b9)) >>> 0)
1298
+ : null;
1299
+ try {
1300
+ const one = await runOnce(rng);
1301
+ if (!bestMoves || one.moves.length < bestMoves.length) {
1302
+ bestMoves = one.moves;
1303
+ bestPhasesOverall = one.phases;
1304
+ }
1305
+ }
1306
+ catch (error) {
1307
+ lastRestartError = error;
280
1308
  }
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
1309
  }
290
- let cube3Solution;
291
- try {
292
- cube3Solution = await solveCube3(cube3State);
1310
+ if (!bestMoves) {
1311
+ throw lastRestartError instanceof Error
1312
+ ? lastRestartError
1313
+ : new Error(`4x4 solve: all ${totalRestarts} restarts failed: ${String(lastRestartError)}`);
293
1314
  }
294
- catch (error) {
295
- if (error instanceof Cube3Phase2SearchError) {
296
- throw error;
1315
+ const scramble = invertCube4Algorithm(bestMoves);
1316
+ const result = {
1317
+ moves: bestMoves,
1318
+ scramble,
1319
+ nodes: { p2: accP2, p3: phase3Solver.epochNodes, f3calls: accF3calls },
1320
+ timings: {
1321
+ reductionMs: accF1Ms + accF2Ms + accF3Ms,
1322
+ f1Ms: accF1Ms,
1323
+ f2Ms: accF2Ms,
1324
+ f3Ms: accF3Ms,
1325
+ finishMs: accFinishMs,
1326
+ polishMs: accPolishMs
297
1327
  }
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 };
1328
+ };
1329
+ if (bestPhasesOverall)
1330
+ result.phases = bestPhasesOverall;
1331
+ return result;
311
1332
  }