// Enumerate strict rankings and committee subsets in deterministic candidate order.
// Generate ordered voter profiles: voters are distinct, so row permutations remain distinct profiles.
// Plurality and Borda use ordinal tie-breaking; returned committees are sorted for stable comparison.
// Chamberlin-Courant maximizes each voter\x27s utility from their best-ranked committee member.
// Monroe searches voter assignments subject to balanced seat quotas.
// STV repeatedly elects a quota-qualified candidate or eliminates the lowest tally.
// Shared combinatorial helpers feed both the five voting rules and the exhaustive verifier.
static class Election
{
public static List<string[]> Permutations(string[] items)
{
var result = new List<string[]>();
void Visit(List<string> prefix, List<string> rest)
{
if (rest.Count == 0) { result.Add(prefix.ToArray()); return; }
foreach (var item in rest.ToArray()) { var next = new List<string>(rest); next.Remove(item); var p = new List<string>(prefix) { item }; Visit(p, next); }
}
Visit(new List<string>(), items.ToList()); return result;
}
public static IEnumerable<string[]> Combinations(string[] items, int k, int start = 0)
{
if (k == 0) { yield return Array.Empty<string>(); yield break; }
for (int i = start; i <= items.Length - k; i++) foreach (var tail in Combinations(items, k - 1, i + 1)) yield return new[] { items[i] }.Concat(tail).ToArray();
}
public static IEnumerable<string[][]> Profiles(List<string[]> ballots, int n)
{
var prefix = new List<string[]>();
IEnumerable<string[][]> Visit()
{ if (prefix.Count == n) { yield return prefix.ToArray(); yield break; } foreach (var ballot in ballots) { prefix.Add(ballot); foreach (var p in Visit()) yield return p; prefix.RemoveAt(prefix.Count - 1); } }
return Visit();
}
public static int Rank(string[] ballot, string candidate) => Array.IndexOf(ballot, candidate) + 1;
public static int Utility(string[] trueBallot, string[] committee, int m) => committee.Length == 0 ? 0 : m - committee.Min(c => Rank(trueBallot, c));
public static string Key(IEnumerable<string> committee) => string.Join("|", committee.OrderBy(c => c, StringComparer.Ordinal));
// Compare sorted committees lexicographically; this same tie-break is encoded in Z3 below.
public static int Compare(string[] a, string[] b)
{ for (int i = 0; i < Math.Min(a.Length, b.Length); i++) { int c = StringComparer.Ordinal.Compare(a[i], b[i]); if (c != 0) return c; } return a.Length.CompareTo(b.Length); }
public static string[] Plurality(string[][] profile, int k)
{
var candidates = profile.SelectMany(x => x).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray(); var votes = profile.GroupBy(x => x[0]).ToDictionary(g => g.Key, g => g.Count());
return candidates.OrderByDescending(c => votes.GetValueOrDefault(c)).ThenBy(c => c, StringComparer.Ordinal).Take(k).OrderBy(c => c, StringComparer.Ordinal).ToArray();
}
public static string[] Borda(string[][] profile, int k)
{
var candidates = profile.SelectMany(x => x).Distinct().OrderBy(x => x, StringComparer.Ordinal).ToArray(); int m = candidates.Length; var scores = candidates.ToDictionary(c => c, c => profile.Sum(b => m - Rank(b, c)));
return candidates.OrderByDescending(c => scores[c]).ThenBy(c => c, StringComparer.Ordinal).Take(k).OrderBy(c => c, StringComparer.Ordinal).ToArray();
}
public static string[] ChamberlinCourant(string[][] profile, int k)
{
int m = profile[0].Length; string[] best = null; int bestScore = int.MinValue;
foreach (var w in Combinations(profile[0].OrderBy(c => c, StringComparer.Ordinal).ToArray(), k)) { int score = profile.Sum(b => Utility(b, w, m)); if (score > bestScore || (score == bestScore && (best == null || Compare(w, best) < 0))) { best = w; bestScore = score; } }
return best ?? Array.Empty<string>();
}
public static string[] Monroe(string[][] profile, int k)
{
int n = profile.Length, m = profile[0].Length, low = n / k, high = (n + k - 1) / k; string[] best = null; int bestScore = int.MinValue; // Each committee member receives floor(n/k) or ceil(n/k) voters.
foreach (var w in Combinations(profile[0].OrderBy(c => c, StringComparer.Ordinal).ToArray(), k))
{
int[] counts = new int[k]; int score = int.MinValue;
void Assign(int voter, int total) { if (voter == n) { if (counts.All(c => c >= low)) score = Math.Max(score, total); return; } for (int j = 0; j < k; j++) if (counts[j] < high) { counts[j]++; Assign(voter + 1, total + m - Rank(profile[voter], w[j])); counts[j]--; } }
Assign(0, 0); if (score > bestScore || (score == bestScore && score != int.MinValue && (best == null || Compare(w, best) < 0))) { best = w; bestScore = score; }
}
return best ?? Array.Empty<string>();
}
public static string[] Stv(string[][] profile, int k)
{
int n = profile.Length; var candidates = profile[0].OrderBy(c => c, StringComparer.Ordinal).ToList(); int quota = n / (k + 1) + 1; // Droop quota; ties use ordinal candidate order.
var elected = new List<string>(); var alive = new HashSet<string>(candidates); var votes = candidates.ToDictionary(c => c, c => 0.0);
void Recount() { foreach (var c in candidates) votes[c] = 0; foreach (var b in profile) { var first = b.FirstOrDefault(alive.Contains); if (first != null) votes[first] += 1; } }
Recount();
while (elected.Count < k)
{
var qualified = alive.Where(c => votes[c] >= quota).OrderByDescending(c => votes[c]).ThenBy(c => c, StringComparer.Ordinal).FirstOrDefault();
if (qualified != null)
{
double tally = votes[qualified]; elected.Add(qualified); alive.Remove(qualified); double surplus = tally - quota;
if (surplus > 0 && tally > 0) foreach (var b in profile) { bool seen = false; foreach (var c in b) { if (c == qualified) { seen = true; continue; } if (seen && alive.Contains(c) && !elected.Contains(c)) { votes[c] += surplus / tally; break; } } }
votes[qualified] = quota; continue;
}
if (alive.Count <= k - elected.Count) break;
var eliminated = alive.OrderBy(c => votes[c]).ThenBy(c => c, StringComparer.Ordinal).First();
var holders = profile.Select(b => b.First(c => alive.Contains(c) || elected.Contains(c))).ToArray();
alive.Remove(eliminated);
for (int i = 0; i < profile.Length; i++) if (holders[i] == eliminated)
foreach (var c in profile[i]) if (alive.Contains(c) && !elected.Contains(c)) { votes[c] += 1; break; }
votes[eliminated] = 0;
}
elected.AddRange(alive.OrderByDescending(c => votes[c]).ThenBy(c => c, StringComparer.Ordinal).Take(k - elected.Count));
if (elected.Count != k) throw new InvalidOperationException("Le STV doit élire exactement k candidats.");
return elected.OrderBy(c => c, StringComparer.Ordinal).ToArray();
}
public static Dictionary<string, Func<string[][], int, string[]>> Rules = new() { ["Pluralité"] = Plurality, ["Borda"] = Borda, ["Chamberlin-Courant"] = ChamberlinCourant, ["Monroe"] = Monroe, ["STV"] = Stv };
public static bool HasProfitableDeviation(string[][] profile, int k, Func<string[][], int, string[]> rule, List<string[]> ballots)
{
int m = profile[0].Length; var honest = rule(profile, k).OrderBy(c => c, StringComparer.Ordinal).ToArray();
// Enumerate unilateral reports; evaluate both outcomes with the voter's true preferences.
for (int i = 0; i < profile.Length; i++) foreach (var falseBallot in ballots) { if (profile[i].SequenceEqual(falseBallot)) continue; var changed = (string[][])profile.Clone(); changed[i] = falseBallot; var outcome = rule(changed, k); if (!honest.SequenceEqual(outcome) && Utility(profile[i], outcome, m) > Utility(profile[i], honest, m)) return true; }
return false;
}
public static (int total, int manipulable) Enumerate(int n, string[] candidates, int k, Func<string[][], int, string[]> rule)
{ int total = 0, manipulable = 0; var ballots = Permutations(candidates); foreach (var p in Profiles(ballots, n)) { total++; if (HasProfitableDeviation(p, k, rule, ballots)) manipulable++; } return (total, manipulable); }
}
Console.WriteLine("Outils de scrutin prêts : pluralité, Borda, Chamberlin-Courant, Monroe, STV.");