// ---------- Étape 3 : construire les PDB additives du 24-puzzle ----------
// Rang compact SANS allocation (PermRank/RankAbstract créent des listes à chaque appel : trop lent
// pour des millions d'états). Même principe : chiffre i = position de la i-ème tuile parmi les cases
// encore libres (base 25-i), dernier chiffre = case vide parmi les 25-k cases restantes.
long Rank24(int[] pos, int k, int blank) {
long r = 0;
for (int i = 0; i < k; i++) {
int smaller = 0;
for (int j = 0; j < i; j++) if (pos[j] < pos[i]) smaller++;
r = r * (CELLS5 - i) + (pos[i] - smaller);
}
int blankSmaller = 0;
for (int j = 0; j < k; j++) if (pos[j] < blank) blankSmaller++;
return r * (CELLS5 - k) + (blank - blankSmaller);
}
// Test exhaustif pour k = 3 : chaque état abstrait doit recevoir un rang distinct dans [0, taille).
{
var seenRank = new bool[PdbSize24(3)]; int collisions = 0, horsBornes = 0, nb = 0;
for (int a = 0; a < CELLS5; a++) for (int b = 0; b < CELLS5; b++) for (int c = 0; c < CELLS5; c++) for (int v = 0; v < CELLS5; v++) {
if (a == b || a == c || b == c || v == a || v == b || v == c) continue;
long rk = Rank24(new[] { a, b, c }, 3, v); nb++;
if (rk < 0 || rk >= seenRank.Length) { horsBornes++; continue; }
if (seenRank[rk]) collisions++; else seenRank[rk] = true;
}
Console.WriteLine($"Rang24 : {nb:N0} états abstraits (k=3), {collisions} collision, {horsBornes} hors bornes (attendu 0 et 0)");
}
// Un état abstrait (positions des k tuiles + case vide) tient dans un long : 5 bits par case (0..24).
long Pack24(int[] pos, int k, int blank) { long c = blank; for (int i = 0; i < k; i++) c |= (long)pos[i] << (5 * (i + 1)); return c; }
int Unpack24(long code, int[] pos, int k) { for (int i = 0; i < k; i++) pos[i] = (int)((code >> (5 * (i + 1))) & 31); return (int)(code & 31); }
// 0-1 BFS rétrograde, comme BuildAdditivePdb : déplacer une tuile du groupe coûte 1, déplacer la
// case vide à travers un joker coûte 0. Traitement couche par couche : "cur" = distance d, "next" = d+1.
// Si un état est retrouvé plus tard avec un coût plus faible, on le corrige (vrai plus court chemin).
byte[] BuildPdb24(int[] group) {
int k = group.Length;
long size = PdbSize24(k);
if (size > Array.MaxLength)
throw new InvalidOperationException($"Groupe de {k} tuiles : {size:N0} états, trop gros pour un tableau .NET.");
var dist = new byte[size];
Array.Fill(dist, (byte)255); // 255 = pas encore atteint
int[] pos = group.Select(t => Array.IndexOf(GOAL24, t)).ToArray();
int blank = Array.IndexOf(GOAL24, 0);
dist[Rank24(pos, k, blank)] = 0;
var cur = new Queue<long>();
var next = new Queue<long>();
cur.Enqueue(Pack24(pos, k, blank));
int d = 0;
while (cur.Count > 0) {
while (cur.Count > 0) {
int b = Unpack24(cur.Dequeue(), pos, k);
if (dist[Rank24(pos, k, b)] != d) continue; // entrée périmée : déjà atteinte moins cher
foreach (int n in NEIGH24[b]) {
int ti = Array.IndexOf(pos, n); // la case n contient-elle une tuile du groupe ?
int w = ti >= 0 ? 1 : 0;
if (ti >= 0) pos[ti] = b; // la tuile glisse dans l'ancienne case vide
long rk = Rank24(pos, k, n);
if (d + w < dist[rk]) {
dist[rk] = (byte)(d + w);
(w == 0 ? cur : next).Enqueue(Pack24(pos, k, n));
}
if (ti >= 0) pos[ti] = n; // on annule avant de tester le voisin suivant
}
}
(cur, next) = (next, cur);
d++;
}
return dist;
}
// Heuristique additive : somme des tables (groupes disjoints => admissible, cf. section 6).
int[] POS_OF24 = new int[CELLS5];
int[] PAT_BUF24 = new int[8];
int HAdditive24(int[] state, int[][] groups, byte[][] tables) {
for (int c = 0; c < CELLS5; c++) POS_OF24[state[c]] = c;
int h = 0;
for (int g = 0; g < groups.Length; g++) {
int k = groups[g].Length;
for (int i = 0; i < k; i++) PAT_BUF24[i] = POS_OF24[groups[g][i]];
h += tables[g][Rank24(PAT_BUF24, k, POS_OF24[0])];
}
return h;
}
// Partitions (groupes compacts, en blocs sur la grille du but) :
// 1 2 3 4 5
// 6 7 8 9 10
// 11 12 13 14 15
// 16 17 18 19 20
// 21 22 23 24 _
int[][] GROUPS24_3 = { new[]{1,2,6}, new[]{3,4,5}, new[]{7,8,9}, new[]{10,15,20}, new[]{11,12,16}, new[]{13,14,19}, new[]{17,18,22}, new[]{21,23,24} };
int[][] GROUPS24_4 = { new[]{1,2,6,7}, new[]{3,4,8,9}, new[]{5,10,15,20}, new[]{11,12,16,17}, new[]{13,14,18,19}, new[]{21,22,23,24} };
int[][] GROUPS24_5 = { new[]{1,2,3,6,7}, new[]{4,5,8,9,10}, new[]{11,12,16,17,21}, new[]{13,14,15,18,19}, new[]{20,22,23,24} };
// Bonus : la partition 5-5-5-5-4 demande ~0,5 Go de RAM et plusieurs minutes de construction.
bool AVEC_5 = true;
bool IsPartition24(int[][] groups) => groups.SelectMany(g => g).OrderBy(t => t).SequenceEqual(Enumerable.Range(1, 24));
var partitions24 = new List<(string name, int[][] groups)> { ("3x8", GROUPS24_3), ("4x6", GROUPS24_4) };
if (AVEC_5) partitions24.Add(("5-5-5-5-4", GROUPS24_5));
var PDB24 = new List<(string name, int[][] groups, byte[][] tables, long states, double sec)>();
foreach (var (name, groups) in partitions24) {
if (!IsPartition24(groups)) throw new InvalidOperationException($"{name} n'est pas une partition disjointe de 1..24");
var swB = System.Diagnostics.Stopwatch.StartNew();
byte[][] tables = groups.Select(g => BuildPdb24(g)).ToArray();
swB.Stop();
long states = groups.Sum(g => PdbSize24(g.Length));
bool complet = tables.All(t => Array.IndexOf(t, (byte)255) < 0);
PDB24.Add((name, groups, tables, states, swB.Elapsed.TotalSeconds));
Console.WriteLine($"PDB {name,-10}: {states,13:N0} états (~{states / 1e6:F0} Mo), construite en {swB.Elapsed.TotalSeconds,6:F1} s, " +
$"dist max par groupe = [{string.Join(", ", tables.Select(t => t.Max()))}], tous les états atteints : {complet}, h(but) = {HAdditive24(GOAL24, groups, tables)}");
}