using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Security.Cryptography;
Console.WriteLine($"Runtime : {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}");
// Noyau de propagation et recherche MRV : meme portage que le carnet 20.
public static class Sudoku {
const string Digits = "123456789";
public static readonly int[][] Units = Enumerable.Range(0,9).Select(r => Enumerable.Range(0,9).Select(c => 9*r+c).ToArray())
.Concat(Enumerable.Range(0,9).Select(c => Enumerable.Range(0,9).Select(r => 9*r+c).ToArray()))
.Concat(Enumerable.Range(0,9).Select(b => Enumerable.Range(0,9).Select(k => 9*((b/3)*3+k/3)+(b%3)*3+k%3).ToArray())).ToArray();
public static readonly int[][][] CellUnits = Enumerable.Range(0,81).Select(i => Units.Where(u => u.Contains(i)).ToArray()).ToArray();
public static readonly int[][] Peers = Enumerable.Range(0,81).Select(i => CellUnits[i].SelectMany(u => u).Where(j => j != i).Distinct().OrderBy(j => j).ToArray()).ToArray();
public static int[] Parse(string line) {
var s = line.Trim();
if (s.Length != 81 || s.Any(c => c != '.' && (c < '0' || c > '9'))) throw new FormatException("Grille invalide : 81 caracteres 0-9 ou point requis");
return s.Select(c => c == '.' ? 0 : c-'0').ToArray();
}
public static bool Valid(int[] p) => p.Length == 81 && p.All(x => x >= 0 && x <= 9) && Units.All(u => { var a = u.Select(i => p[i]).Where(x => x != 0).ToArray(); return a.Distinct().Count() == a.Length; });
static bool Fill(string[] g, int s, char d) {
if (g[s] == d.ToString()) return true;
foreach (char x in g[s].Replace(d.ToString(), "").ToArray()) if (!Eliminate(g,s,x)) return false;
return true;
}
static bool Eliminate(string[] g, int s, char d) {
if (!g[s].Contains(d)) return true;
g[s] = g[s].Replace(d.ToString(), "");
if (g[s].Length == 0) return false;
if (g[s].Length == 1) foreach (int p in Peers[s]) if (!Eliminate(g,p,g[s][0])) return false;
foreach (var u in CellUnits[s]) {
var places = u.Where(i => g[i].Contains(d)).ToArray();
if (places.Length == 0) return false;
if (places.Length == 1 && !Fill(g,places[0],d)) return false;
}
return true;
}
static string[] Propagate(int[] p) {
if (p.Length != 81 || p.Any(x => x < 0 || x > 9)) throw new ArgumentException("81 chiffres requis");
var g = Enumerable.Repeat(Digits,81).ToArray();
for (int i=0;i<81;i++) if (p[i] != 0 && !Fill(g,i,(char)('0'+p[i]))) return null;
return g;
}
static (int count,int decisions,string[] solution) Search(string[] g,int limit) {
if (g == null) return (0,0,null);
int best=-1,min=10;
for (int i=0;i<81;i++) if (g[i].Length > 1 && g[i].Length < min) { min = g[i].Length; best = i; }
if (best < 0) return (1,0,g);
int count=0, decisions=0; string[] first=null;
foreach (char d in g[best]) {
var copy=(string[])g.Clone();
var result=Search(Fill(copy,best,d) ? copy : null,limit-count);
count+=result.count; decisions+=1+result.decisions; first ??= result.solution;
if (count>=limit) break;
}
return (count,decisions,first);
}
public static (int count,int decisions,string[] solution) Run(int[] p,int limit) {
if (limit < 1) throw new ArgumentOutOfRangeException(nameof(limit));
return Search(Propagate(p),limit);
}
}
// Portage de l'organe `symmetry.py` : le groupe D4 et les mesures de
// distribution. Meme semantique, memes noms d'operations.
public static class Symetrie {
public const int Side = 9;
public static readonly string[] Noms = { "identity","rot90","rot180","rot270","flip_columns","flip_rows","transpose","antitranspose" };
public static readonly Dictionary<string,int[]> Permutations = BuildPerms();
static Dictionary<string,int[]> BuildPerms() {
int last = Side - 1;
Func<int,int,(int,int)>[] maps =
{
(r,c) => (r, c), (r,c) => (c, last - r), (r,c) => (last - r, last - c),
(r,c) => (last - c, r), (r,c) => (r, last - c), (r,c) => (last - r, c),
(r,c) => (c, r), (r,c) => (last - c, last - r)
};
var result = new Dictionary<string,int[]>();
for (int k = 0; k < Noms.Length; k++) {
var m = maps[k]; var perm = new int[Side*Side];
for (int i = 0; i < Side*Side; i++) { int r = i / Side, c = i % Side; var (tr, tc) = m(r, c); perm[i] = tr * Side + tc; }
result[Noms[k]] = perm;
}
return result;
}
public static int[] ApplySymmetry(int[] g, string s) { var perm = Permutations[s]; var image = new int[Side*Side]; for (int i = 0; i < Side*Side; i++) image[i] = g[perm[i]]; return image; }
public static Dictionary<string,int[]> SymmetryImages(int[] g) => Noms.ToDictionary(s => s, s => ApplySymmetry(g, s));
public static string Encode(int[] g) => new string(g.Select(v => (char)('0'+v)).ToArray());
public static string CanonicalForm(int[] g) => SymmetryImages(g).Values.Select(Encode).Min(StringComparer.Ordinal);
public static int OrbitSize(int[] g) => SymmetryImages(g).Values.Select(Encode).Distinct().Count();
public static List<string> InvariantSymmetries(int[] g) => Noms.Where(s => s != "identity" && ApplySymmetry(g, s).SequenceEqual(g)).ToList();
public static Dictionary<string,List<int>> EquivalenceClasses(IList<int[]> puzzles) { var map = new Dictionary<string,List<int>>(); for (int i = 0; i < puzzles.Count; i++) { var key = CanonicalForm(puzzles[i]); if (!map.TryGetValue(key, out var members)) { members = new List<int>(); map[key] = members; } members.Add(i); } return map; }
public static (int duplicates, int distinct) CountExactDuplicates(IList<int[]> puzzles) { int distinct = puzzles.Select(Encode).Distinct().Count(); return (puzzles.Count - distinct, distinct); }
public static List<List<int>> DuplicatePairs(IList<int[]> puzzles) { var seen = new Dictionary<string,int>(); var pairs = new List<List<int>>(); for (int i = 0; i < puzzles.Count; i++) { string key = Encode(puzzles[i]); if (seen.TryGetValue(key, out var first)) pairs.Add(new List<int>{ first + 1, i + 1 }); else seen[key] = i; } return pairs; }
public static List<List<int>> CyclesOf(int[] perm) { var seen = new bool[Side*Side]; var cycles = new List<List<int>>(); for (int s = 0; s < Side*Side; s++) { if (seen[s]) continue; var c = new List<int>(); int node = s; while (!seen[node]) { seen[node] = true; c.Add(node); node = perm[node]; } cycles.Add(c); } return cycles; }
public static int BoxOf(int i) { int r = i / Side, c = i % Side; return (r / 3) * 3 + (c / 3); }
public static string FmtPairs(IList<List<int>> ps) => "[" + string.Join(", ", ps.Select(l => "[" + string.Join(", ", l) + "]")) + "]";
public static string FmtList(IList<int> xs) => "[" + string.Join(", ", xs) + "]";
}
Console.WriteLine("Noyau de propagation, recherche MRV et groupe D4 charges.");
// Chargement des six corpus de la serie.
var root = new DirectoryInfo(Directory.GetCurrentDirectory());
while (root != null && !Directory.Exists(Path.Combine(root.FullName,"MyIA.AI.Notebooks","Sudoku","Puzzles"))) root = root.Parent;
if (root == null) throw new DirectoryNotFoundException("Repertoire des corpus Sudoku introuvable depuis le repertoire courant");
string PuzzleDir = Path.Combine(root.FullName,"MyIA.AI.Notebooks","Sudoku","Puzzles");
// Chemin affiche relatif au depot : une sortie committée ne doit pas porter
// le chemin machine du poste de travail.
string cheminRelatif = Path.GetRelativePath(root.FullName, PuzzleDir).Replace(Path.DirectorySeparatorChar, '/');
var corpusNames = new[]{"Sudoku_Easy51.txt","Sudoku_hardest.txt","Sudoku_top95.txt","Sudoku_gen_facile.txt","Sudoku_gen_moyen.txt","Sudoku_gen_difficile.txt"};
var corpora = corpusNames.ToDictionary(n => n, n => File.ReadAllLines(Path.Combine(PuzzleDir,n)).Where(s => !string.IsNullOrWhiteSpace(s)).Select(Sudoku.Parse).ToArray());
Console.WriteLine($"{corpora.Count} corpus charges depuis {cheminRelatif}");
foreach (var n in corpusNames)
Console.WriteLine($" {n,-24} {corpora[n].Length,4} grille(s)");
// Grille de demonstration : la premiere du corpus Easy51.
var demo = corpora["Sudoku_Easy51.txt"][0];
var images = Symetrie.SymmetryImages(demo);
Console.WriteLine();
Console.WriteLine($"grille de demonstration : {demo.Length} cases, {demo.Count(x => x != 0)} indices");
Console.WriteLine($"orbite sous les {Symetrie.Noms.Length} symetries : {Symetrie.OrbitSize(demo)} images distinctes");
var invariantes = Symetrie.InvariantSymmetries(demo);
Console.WriteLine($"symetries invariantes (hors identite) : {(invariantes.Count == 0 ? "aucune" : string.Join(", ", invariantes))}");
foreach (var kv in images) {
Console.WriteLine($"--- {kv.Key} ---");
for (int r = 0; r < 9; r++)
Console.WriteLine(" " + string.Join(" ", Enumerable.Range(0,9).Select(c => { int v = kv.Value[r*9+c]; return v == 0 ? "." : v.ToString(); })));
}