// Noyau du port : BCL uniquement, arithmétique rationnelle exacte et graphes par masques.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.IO;
using System.Text;
using System.Diagnostics;
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
readonly struct Rational : IComparable<Rational>, IEquatable<Rational>
{
public static readonly Rational Zero = new Rational(BigInteger.Zero, BigInteger.One);
public Rational(BigInteger n) : this(n, BigInteger.One) { }
public BigInteger Num { get; }
public BigInteger Den { get; }
public Rational(BigInteger n, BigInteger d)
{
if (d.IsZero) throw new ArgumentException("Dénominateur nul.");
if (d.Sign < 0) { n = -n; d = -d; }
BigInteger g = BigInteger.GreatestCommonDivisor(BigInteger.Abs(n), d);
if (!g.IsOne) { n /= g; d /= g; }
Num = n; Den = d;
}
public static Rational operator +(Rational a, Rational b)
{
BigInteger g = BigInteger.GreatestCommonDivisor(a.Den, b.Den);
BigInteger bd = b.Den / g, ad = a.Den / g;
return new Rational(a.Num * bd + b.Num * ad, a.Den * bd);
}
public static Rational operator -(Rational a, Rational b) => a + new Rational(-b.Num, b.Den);
public static Rational operator -(Rational a) => new Rational(-a.Num, a.Den);
public static Rational operator *(Rational a, Rational b)
{
BigInteger g1 = BigInteger.GreatestCommonDivisor(BigInteger.Abs(a.Num), b.Den);
BigInteger g2 = BigInteger.GreatestCommonDivisor(BigInteger.Abs(b.Num), a.Den);
return new Rational((a.Num / g1) * (b.Num / g2), (a.Den / g2) * (b.Den / g1));
}
public static Rational operator /(Rational a, Rational b) => a * new Rational(b.Den, b.Num);
public static Rational operator *(Rational a, int b) => a * new Rational(b, BigInteger.One);
public static bool operator ==(Rational a, Rational b) => a.Num == b.Num && a.Den == b.Den;
public static bool operator !=(Rational a, Rational b) => !(a == b);
public static bool operator <(Rational a, Rational b) => a.Num * b.Den < b.Num * a.Den;
public static bool operator >(Rational a, Rational b) => b < a;
public double ToDouble() => (double)Num / (double)Den;
public int CompareTo(Rational other) => (Num * other.Den).CompareTo(other.Num * Den);
public override string ToString() => Den.IsOne ? Num.ToString() : $"{Num}/{Den}";
public override bool Equals(object obj) => obj is Rational r && this == r;
public bool Equals(Rational other) => this == other;
public override int GetHashCode() => HashCode.Combine(Num, Den);
}
static Rational R(int n, int d = 1) => new Rational(n, d);
static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static void RequireExact(Rational actual, Rational expected, string label)
{
if (actual != expected) throw new InvalidOperationException($"{label} : {actual}, attendu {expected}.");
}
static void RequireNear(double actual, double expected, double tolerance, string label)
{
if (!double.IsFinite(actual) || Math.Abs(actual - expected) > tolerance)
throw new InvalidOperationException($"{label} : {actual:G12}, attendu {expected} ± {tolerance}.");
}
static string Fmt(double x, int digits = 4) => x.ToString("F" + digits, CultureInfo.InvariantCulture);
static string Signed(double x) => x.ToString("+0.0000;-0.0000", CultureInfo.InvariantCulture);
static long Mask(params int[] players) => players.Aggregate(0L, (m, i) => m | (1L << i));
static int[] Indices(long mask, int n)
{
var result = new List<int>();
for (int i = 0; i < n; i++) if ((mask & (1L << i)) != 0) result.Add(i);
return result.ToArray();
}
static int[] Idx(params int[] nodes) => nodes.Select(k => k - 1).ToArray();
static Rational[] ShapleyWeights(int n)
{
var fact = new BigInteger[n + 1]; fact[0] = BigInteger.One;
for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
return Enumerable.Range(0, n).Select(s => new Rational(fact[s] * fact[n - s - 1], fact[n])).ToArray();
}
class CoalitionGameCs
{
public int N { get; }
public string[] Names { get; }
private readonly Func<long, Rational> characteristic;
public CoalitionGameCs(int n, Func<long, Rational> value, string[] names = null)
{
N = n; Names = names ?? Enumerable.Range(0, n).Select(i => $"Player_{i}").ToArray();
characteristic = value;
Require(characteristic(0) == R(0), "La coalition vide doit valoir zéro.");
}
public Rational Value(long mask) => characteristic(mask);
}
static CoalitionGameCs ConnectivityGameCs(int n, (int A, int B)[] edges, string[] names = null)
{
var adjacency = new long[n];
foreach (var (a, b) in edges)
{
Require(a >= 0 && a < n && b >= 0 && b < n && a != b, "Arête invalide.");
adjacency[a] |= 1L << b; adjacency[b] |= 1L << a;
}
Rational Value(long mask)
{
int size = BitOperations.PopCount((ulong)mask);
if (size < 2) return R(0);
int first = BitOperations.TrailingZeroCount((ulong)mask);
long reached = 1L << first, frontier = reached;
while (frontier != 0)
{
long next = 0, f = frontier;
while (f != 0)
{
int node = BitOperations.TrailingZeroCount((ulong)f);
next |= adjacency[node]; f &= f - 1;
}
frontier = next & mask & ~reached; reached |= frontier;
}
return R(reached == mask ? 1 : 0);
}
return new CoalitionGameCs(n, Value, names);
}
static Rational GroupValueCs(CoalitionGameCs game, long group)
{
Require(group != 0 && (group >> game.N) == 0, "Groupe vide ou hors jeu.");
Require(game.N <= 24, "Formule exacte limitée à 24 joueurs : employer MonteCarloCs.");
int m = game.N - BitOperations.PopCount((ulong)group) + 1;
var weights = ShapleyWeights(m); Rational total = R(0);
for (int t = 0; t < (1 << game.N); t++)
if ((t & group) == 0) total += weights[BitOperations.PopCount((uint)t)] * (game.Value((long)t | group) - game.Value(t));
return total;
}
static (CoalitionGameCs Game, int[] Mapping) MergingGameCs(CoalitionGameCs game, long group)
{
var rest = Enumerable.Range(0, game.N).Where(i => (group & (1L << i)) == 0).ToArray();
int proxy = rest.Length;
Rational Value(long mask)
{
long original = ((mask & (1L << proxy)) != 0) ? group : 0L;
for (int k = 0; k < rest.Length; k++) if ((mask & (1L << k)) != 0) original |= 1L << rest[k];
return game.Value(original);
}
string proxyName = "{" + string.Join(", ", Indices(group, game.N).Select(i => game.Names[i])) + "}";
return (new CoalitionGameCs(proxy + 1, Value, rest.Select(i => game.Names[i]).Append(proxyName).ToArray()), rest.Append(-1).ToArray());
}
static (double Estimate, double Se) MonteCarloCs(CoalitionGameCs game, long group, int samples, int seed)
{
Require(group != 0 && samples >= 2, "Groupe non vide et au moins deux échantillons requis.");
var rng = new Random(seed);
int m = game.N - BitOperations.PopCount((ulong)group) + 1; double mean = 0, m2 = 0;
for (int k = 1; k <= samples; k++)
{
var rest = Indices(-1L & ~group, game.N);
int t = rng.Next(m); // .NET PRNG : tirage natif, distinct de NumPy.
for (int j = rest.Length - 1; j > rest.Length - 1 - t; j--)
{
int p = rng.Next(j + 1);
(rest[j], rest[p]) = (rest[p], rest[j]);
}
long predecessor = 0L;
for (int j = rest.Length - 1; j > rest.Length - 1 - t; j--) predecessor |= 1L << rest[j];
double x = (game.Value(predecessor | group) - game.Value(predecessor)).ToDouble();
double delta = x - mean; mean += delta / k; m2 += delta * (x - mean);
}
return (mean, Math.Sqrt(m2 / (samples - 1) / samples));
}
class GroupValueTableCs
{
public CoalitionGameCs Game { get; }
public int N { get; }
public Rational[] V { get; }
public int[] Pop { get; }
// Valeurs du jeu mises au dénominateur commun : numérateurs entiers exacts, sans réduction par terme.
private readonly BigInteger[] numerators;
private readonly BigInteger commonDenominator;
private readonly BigInteger[] factorials;
private readonly Dictionary<int, Rational[]> weights = new();
private readonly Dictionary<int, BigInteger[]> weightNumerators = new();
public GroupValueTableCs(CoalitionGameCs game)
{
Require(game.N <= 22, "Au-delà de 22 joueurs, employer Monte Carlo.");
Game = game; N = game.N; int size = 1 << N;
V = new Rational[size]; Pop = new int[size];
for (int mask = 0; mask < size; mask++) V[mask] = game.Value(mask);
for (int mask = 0; mask < size; mask++) Pop[mask] = BitOperations.PopCount((uint)mask);
commonDenominator = V.Aggregate(BigInteger.One, (lcm, v) => lcm / BigInteger.GreatestCommonDivisor(lcm, v.Den) * v.Den);
numerators = V.Select(v => v.Num * (commonDenominator / v.Den)).ToArray();
factorials = new BigInteger[N + 1]; factorials[0] = BigInteger.One;
for (int i = 1; i <= N; i++) factorials[i] = factorials[i - 1] * i;
}
private Rational[] W(int n)
{
if (!weights.ContainsKey(n)) weights[n] = ShapleyWeights(n);
return weights[n];
}
// Numérateurs des poids de Shapley de m acteurs : s!(m - s - 1)!, le dénominateur commun étant m!.
private BigInteger[] WeightNumerators(int m)
{
if (!weightNumerators.ContainsKey(m))
weightNumerators[m] = Enumerable.Range(0, m).Select(s => factorials[s] * factorials[m - s - 1]).ToArray();
return weightNumerators[m];
}
public Rational GroupValue(long group)
{
int g = checked((int)group);
Require(g != 0, "Groupe vide.");
var rest = Indices(V.Length - 1 - g, N); int m = rest.Length + 1;
var w = WeightNumerators(m);
// Seuls les sous-ensembles T de N - C ont un poids non nul : 2^(n - |C|) termes au lieu de 2^n.
// t[sub] est la coalition T du sous-ensemble sub, obtenue en O(1) depuis sub privé de son plus petit bit.
var bits = rest.Select(i => 1 << i).ToArray();
var t = new int[1 << rest.Length];
for (int sub = 1; sub < t.Length; sub++) t[sub] = t[sub ^ (sub & -sub)] | bits[BitOperations.TrailingZeroCount((uint)sub)];
BigInteger numerator = BigInteger.Zero;
for (int sub = 0; sub < t.Length; sub++)
{
var delta = numerators[t[sub] | g] - numerators[t[sub]];
if (!delta.IsZero) numerator += w[Pop[sub]] * delta;
}
return new Rational(numerator, commonDenominator * factorials[m]);
}
public Rational[] Shapley()
{
var phi = new Rational[N]; var w = W(N);
for (int i = 0; i < N; i++)
{
int bit = 1 << i; Rational total = R(0);
for (int s = 0; s < V.Length; s++) if ((s & bit) == 0)
total += w[Pop[s]] * (V[s | bit] - V[s]);
phi[i] = total;
}
return phi;
}
public Rational AdditiveValue(long group, Rational[] phi) => Indices(group, N).Aggregate(R(0), (sum, i) => sum + phi[i]);
public Rational Profitability(long group, Rational[] phi) => GroupValue(group) - AdditiveValue(group, phi);
public Rational RestrictedShapley(int player, long removedSet)
{
int removed = checked((int)removedSet);
Require((removed & (1 << player)) == 0, "Le joueur ne peut pas être retiré.");
int nSub = N - BitOperations.PopCount((uint)removed); var w = W(nSub);
Rational total = R(0); int bit = 1 << player;
for (int s = 0; s < V.Length; s++) if ((s & (removed | bit)) == 0)
total += w[Pop[s]] * (V[s | bit] - V[s]);
return total;
}
public Rational GroupComplementarity(long groupSet, int player)
{
int group = checked((int)groupSet);
Require(group != 0 && (group & (1 << player)) == 0, "Entrant invalide.");
int m = N - BitOperations.PopCount((uint)group) + 1, bit = 1 << player;
var w = W(m); Rational total = R(0);
for (int s = 0; s < V.Length; s++) if ((s & (group | bit)) == 0)
total += w[Pop[s]] * (V[s | group | bit] - V[s | group] - V[s | bit] + V[s]);
return total;
}
public Rational Complementarity(int i, int j) => GroupComplementarity(1L << i, j);
public List<(long Group, Rational Value)> BestGroups(int k)
{
var result = new List<(long, Rational)>();
for (int mask = 1; mask < V.Length; mask++) if (Pop[mask] == k) result.Add((mask, GroupValue(mask)));
return result.OrderByDescending(x => x.Item2).ThenBy(x => x.Item1).ToList();
}
public List<int> GreedyGroup(int k)
{
var members = new List<int>();
for (int step = 0; step < k; step++)
{
int best = -1; Rational bestValue = R(-1000);
long group = members.Aggregate(0L, (mask, i) => mask | (1L << i));
for (int i = 0; i < N; i++) if ((group & (1L << i)) == 0)
{
Rational value = GroupValue(group | (1L << i));
if (best < 0 || value > bestValue) { best = i; bestValue = value; }
}
members.Add(best);
}
return members;
}
public string Names(long group) => string.Join(" + ", Indices(group, N).Select(i => Game.Names[i]));
}
record SvgImage(string Html);
// L'espace Formatting n'est pas importé au niveau du script : sa présence fait passer la recherche
// des méthodes d'extension (Append notamment) par ses classes, et lève un avertissement CS1701
// (identité d'assembly Html.Abstractions 2.3.0.0 contre 10.0.0.0). L'appel est pleinement qualifié.
Microsoft.DotNet.Interactive.Formatting.Formatter.Register<SvgImage>((SvgImage image, TextWriter writer) => writer.Write(image.Html), "text/html");
static string EscapeSvg(string text) => text.Replace("&", "&").Replace("<", "<").Replace(">", ">");
static SvgImage SvgEmbed(string svg)
{
string encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(svg));
return new SvgImage($"<img alt=\"Figure SVG\" src=\"data:image/svg+xml;base64,{encoded}\">");
}
static string SvgOpen(int width, int height, string title) =>
$"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 {width} {height}' role='img' aria-label='{EscapeSvg(title)}'>" +
$"<rect width='{width}' height='{height}' fill='white'/><text x='{width / 2}' y='24' text-anchor='middle' font-family='sans-serif' font-size='15' font-weight='bold'>{EscapeSvg(title)}</text>";
static string GraphSvg(int n, (int A, int B)[] edges, double[,] positions, Func<int, string> color, string title)
{
var sb = new StringBuilder(SvgOpen(700, 360, title));
foreach (var (a, b) in edges)
sb.Append(FormattableString.Invariant($"<line x1='{positions[a, 0]:F1}' y1='{positions[a, 1]:F1}' x2='{positions[b, 0]:F1}' y2='{positions[b, 1]:F1}' stroke='#8a949c' stroke-width='1.5'/>"));
for (int i = 0; i < n; i++)
sb.Append(FormattableString.Invariant($"<circle cx='{positions[i, 0]:F1}' cy='{positions[i, 1]:F1}' r='16' fill='{color(i)}' stroke='#25313a'/><text x='{positions[i, 0]:F1}' y='{positions[i, 1] + 4:F1}' text-anchor='middle' font-family='sans-serif' font-size='11' fill='#18242c'>{i}</text>"));
return sb.Append("</svg>").ToString();
}
static int[] Degrees(int n, (int A, int B)[] edges)
{
var degree = new int[n]; foreach (var (a, b) in edges) { degree[a]++; degree[b]++; } return degree;
}
static double[] Betweenness(int n, (int A, int B)[] edges)
{
var adj = Enumerable.Range(0, n).Select(_ => new List<int>()).ToArray();
foreach (var (a, b) in edges) { adj[a].Add(b); adj[b].Add(a); }
var centrality = new double[n];
for (int source = 0; source < n; source++)
{
var stack = new Stack<int>(); var predecessors = Enumerable.Range(0, n).Select(_ => new List<int>()).ToArray();
var paths = new double[n]; var distance = Enumerable.Repeat(-1, n).ToArray(); paths[source] = 1; distance[source] = 0;
var queue = new Queue<int>(); queue.Enqueue(source);
while (queue.Count > 0)
{
int v = queue.Dequeue(); stack.Push(v);
foreach (int w in adj[v])
{
if (distance[w] < 0) { queue.Enqueue(w); distance[w] = distance[v] + 1; }
if (distance[w] == distance[v] + 1) { paths[w] += paths[v]; predecessors[w].Add(v); }
}
}
var dependency = new double[n];
while (stack.Count > 0)
{
int w = stack.Pop();
foreach (int v in predecessors[w]) dependency[v] += paths[v] / paths[w] * (1 + dependency[w]);
if (w != source) centrality[w] += dependency[w];
}
}
double normalization = (n - 1.0) * (n - 2.0);
return centrality.Select(x => x / normalization).ToArray();
}
static double Spearman(double[] x, double[] y)
{
Require(x.Length == y.Length, "Séries de tailles différentes.");
double[] Ranks(double[] values)
{
var order = Enumerable.Range(0, values.Length).OrderBy(i => values[i]).ToArray();
var rank = new double[values.Length];
for (int start = 0; start < order.Length;)
{
int end = start + 1;
while (end < order.Length && values[order[end]] == values[order[start]]) end++;
double average = (start + end - 1) / 2.0 + 1;
for (int k = start; k < end; k++) rank[order[k]] = average;
start = end;
}
return rank;
}
var rx = Ranks(x); var ry = Ranks(y); double mx = rx.Average(), my = ry.Average();
double covariance = 0, vx = 0, vy = 0;
for (int i = 0; i < x.Length; i++) { covariance += (rx[i] - mx) * (ry[i] - my); vx += (rx[i] - mx) * (rx[i] - mx); vy += (ry[i] - my) * (ry[i] - my); }
return covariance / Math.Sqrt(vx * vy);
}
Console.WriteLine($"C# / .NET {Environment.Version} | BCL seulement, zéro NuGet");
Console.WriteLine("Rational (BigInteger), jeux de connectivité, Shapley exact et Monte Carlo .NET chargés.");C# / .NET 10.0.12 | BCL seulement, zéro NuGet
Rational (BigInteger), jeux de connectivité, Shapley exact et Monte Carlo .NET chargés.