#nullable enable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
// Illustration 8 -- Gate G2 : FAQ 7
// Le stub de l'exercice reste ci-dessous, sans solution revelee.
// L'attestation qui le suit est externe au stub : elle reenumeres les deux
// bornes avec un simulateur de reference independant, puis compare chaque
// resultat au moteur des gates avant de publier les comptes.
public sealed class InstructionDef
{
public string Name { get; }
public int Cost { get; }
public InstructionDef(string name, int cost) { Name = name; Cost = cost; }
}
public static class ToyTables
{
public const int HaltCost = 7;
public const int LMax = 5;
public static readonly InstructionDef[] Cheap =
{
new InstructionDef("GETAX", 1),
new InstructionDef("RULE", 2),
new InstructionDef("CHECK", 3),
new InstructionDef("BOGUS", 4),
new InstructionDef("STATE2THM", 5),
new InstructionDef("SETSW", 6),
};
public static readonly InstructionDef[] Expensive =
{
new InstructionDef("BOGUS", 1),
new InstructionDef("STATE2THM", 2),
new InstructionDef("GETAX", 3),
new InstructionDef("RULE", 4),
new InstructionDef("CHECK", 5),
new InstructionDef("SETSW", 6),
};
public static readonly int[] WLever = { 0, 1, 5, 1, 2 };
public static readonly int[] WBogus = { 3, 0, 1, 5, 2 };
}
public sealed class MondeJouet
{
public static readonly string[] Policies = { "keep", "lever", "setup_forever" };
public string Label { get; }
public int T { get; }
public int K { get; }
public int T1 { get; }
public string CurrentPolicy { get; }
public string[] Axioms { get; }
public (string Mode, int Setups)? StateAtT1 { get; }
public MondeJouet(string label, int t = 20, int k = 2, int t1 = 4,
string currentPolicy = "keep", (string Mode, int Setups)? stateAtT1 = null)
{
Label = label; T = t; K = k; T1 = t1;
CurrentPolicy = currentPolicy; StateAtT1 = stateAtT1;
Axioms = new[] { "world" };
}
public (string Mode, int Setups) InitialState()
{
if (StateAtT1.HasValue) { return StateAtT1.Value; }
return ("setup", 0);
}
public int SimCost() => Policies.Length * (T - T1);
public int Simulate(string policy, int fromT, string mode, int setups)
{
int total = 0;
for (int cycle = fromT + 1; cycle <= T; cycle++)
{
string action = policy switch
{
"keep" => "press",
"setup_forever" => "setup",
"lever" => (mode == "setup") ? "setup" : "press",
_ => throw new ArgumentException("politique inconnue : " + policy)
};
if (action == "setup")
{
setups += 1;
if (setups >= K) { mode = "ready"; }
}
else
{
if (mode == "ready") { total += 1; }
setups = 0;
}
}
return total;
}
}
public sealed class ToyOutcome
{
public bool Fired { get; set; }
public int FireCost { get; set; }
public int NaturalCost { get; set; }
public int Margin { get; set; }
public string SwitchProgram { get; set; } = "";
public bool ContainsBogus { get; set; }
public bool ExecutedBogus { get; set; }
public bool UsedBogusInProof { get; set; }
public int TechniqueLength { get; set; }
public string Outcome { get; set; } = "end";
}
public sealed class ToyResult
{
public bool Fired { get; set; }
public int[] Technique { get; set; } = Array.Empty<int>();
public int CodeCost { get; set; }
public int Phase { get; set; }
public long TotalSteps { get; set; }
public int FireSteps { get; set; }
public int Margin { get; set; }
public string SwitchProgram { get; set; } = "";
public int TechniquesRun { get; set; }
public int FiringTechniques { get; set; }
public int BogusFires { get; set; }
}
public sealed class G2Summary
{
public int SpaceSize { get; set; }
public int FiringTechniques { get; set; }
public int FiringWithBogusPresent { get; set; }
public int FiringWithBogusExecuted { get; set; }
public int FiringWithBogusUsed { get; set; }
public List<int> BogusFiringMargins { get; set; } = new List<int>();
}
public sealed class G2AuditSummary
{
public int LMax { get; set; }
public long ExpectedSpaceSize { get; set; }
public int ActualSpaceSize { get; set; }
public int FiringTechniques { get; set; }
public int FiringWithBogusPresent { get; set; }
public int FiringWithBogusExecuted { get; set; }
public int FiringWithBogusUsed { get; set; }
public int ReferenceMismatches { get; set; }
public List<int> BogusFiringMargins { get; set; } = new List<int>();
}
public static class ToyEngine
{
private sealed class Theorem
{
public string Kind { get; set; } = "";
public string Name { get; set; } = "";
public int Value { get; set; }
public bool Proven { get; set; }
public bool Bogus { get; set; }
}
public static int Cost(int[] technique, InstructionDef[] table)
{
int cost = ToyTables.HaltCost;
foreach (int index in technique) { cost += table[index].Cost; }
return cost;
}
public static List<int[]> Space(InstructionDef[] table, int lMax)
{
var all = new List<int[]>();
var current = new List<int>();
void Walk(int depth)
{
all.Add(current.ToArray());
if (depth == lMax) { return; }
for (int i = 0; i < table.Length; i++)
{
current.Add(i);
Walk(depth + 1);
current.RemoveAt(current.Count - 1);
}
}
Walk(0);
return all.OrderBy(t => Cost(t, table)).ThenBy(t => string.Join(",", t)).ToList();
}
public static ToyOutcome Run(int[] technique, MondeJouet world, InstructionDef[] table)
{
var theorems = new List<Theorem>();
int steps = 0, fetched = 0;
string nominated = "";
bool simulated = false;
bool containsBogus = technique.Any(index => table[index].Name == "BOGUS");
bool executedBogus = false;
foreach (int index in technique)
{
steps++;
switch (table[index].Name)
{
case "GETAX":
if (fetched < world.Axioms.Length)
{
theorems.Add(new Theorem { Kind = "axiom", Name = world.Axioms[fetched++] });
}
break;
case "RULE":
if (!simulated && theorems.Any(t => t.Kind == "axiom" && t.Name == "world"))
{
steps += world.SimCost();
var state = world.InitialState();
foreach (string policy in MondeJouet.Policies)
{
theorems.Add(new Theorem
{
Kind = "u",
Name = policy,
Value = world.Simulate(policy, world.T1, state.Mode, state.Setups),
Proven = true
});
}
simulated = true;
}
else if (nominated.Length > 0)
{
steps++;
Theorem? chosen = theorems.FirstOrDefault(t => t.Kind == "u" && t.Name == nominated && t.Proven);
Theorem? current = theorems.FirstOrDefault(t => t.Kind == "u" && t.Name == world.CurrentPolicy && t.Proven);
if (chosen != null && current != null && chosen.Value > current.Value)
{
theorems.Add(new Theorem
{
Kind = "target",
Name = chosen.Name,
Value = chosen.Value - current.Value,
Proven = true,
Bogus = chosen.Bogus
});
}
}
else { steps++; }
break;
case "CHECK":
{
Theorem? target = theorems.FirstOrDefault(t => t.Kind == "target" && t.Proven);
if (target != null)
{
return new ToyOutcome
{
Fired = true,
FireCost = steps,
NaturalCost = steps,
Margin = target.Value,
SwitchProgram = target.Name,
ContainsBogus = containsBogus,
ExecutedBogus = executedBogus,
UsedBogusInProof = target.Bogus,
TechniqueLength = technique.Length
};
}
break;
}
case "BOGUS":
executedBogus = true;
theorems.Add(new Theorem { Kind = "u", Name = "lever", Value = 100 * (world.T - world.T1), Bogus = true });
break;
case "STATE2THM":
{
var state = world.InitialState();
theorems.Add(new Theorem { Kind = "state", Name = state.Mode, Value = state.Setups });
break;
}
case "SETSW":
{
Theorem? best = theorems.Where(t => t.Kind == "u" && t.Proven)
.OrderByDescending(t => t.Value).FirstOrDefault();
nominated = best?.Name ?? "";
break;
}
}
}
return new ToyOutcome
{
Fired = false,
NaturalCost = steps,
ContainsBogus = containsBogus,
ExecutedBogus = executedBogus,
UsedBogusInProof = false,
TechniqueLength = technique.Length,
Outcome = "end"
};
}
public static ToyResult BioPS(MondeJouet world, InstructionDef[] table,
int iMax = 40, int lMax = ToyTables.LMax, int[]? frozen = null)
{
var space = Space(table, lMax);
var memo = space.ToDictionary(t => string.Join(",", t), t => Run(t, world, table));
int firing = memo.Values.Count(o => o.Fired);
int bogusFires = memo.Values.Count(o => o.Fired && o.UsedBogusInProof);
long total = 0;
ToyResult? winner = null;
for (int phase = 1; phase <= iMax && winner == null; phase++)
{
if (frozen != null && memo.ContainsKey(string.Join(",", frozen)))
{
int codeCost = Cost(frozen, table);
long budget = 1L << (phase - 1);
var outcome = memo[string.Join(",", frozen)];
long charge = Math.Min(outcome.NaturalCost, budget);
if (outcome.Fired && budget >= outcome.FireCost)
{
winner = new ToyResult
{
Fired = true, Technique = frozen, CodeCost = codeCost, Phase = phase,
TotalSteps = total + charge, FireSteps = outcome.FireCost, Margin = outcome.Margin,
SwitchProgram = outcome.SwitchProgram, TechniquesRun = space.Count,
FiringTechniques = firing, BogusFires = bogusFires
};
break;
}
total += charge;
}
foreach (var technique in space)
{
if (frozen != null && technique.SequenceEqual(frozen)) { continue; }
int codeCost = Cost(technique, table);
if (phase < codeCost) { continue; }
long budget = 1L << (phase - codeCost);
var outcome = memo[string.Join(",", technique)];
total += Math.Min((long)outcome.NaturalCost, budget);
if (winner == null && outcome.Fired && budget >= outcome.FireCost)
{
winner = new ToyResult
{
Fired = true, Technique = technique, CodeCost = codeCost, Phase = phase,
TotalSteps = total, FireSteps = outcome.FireCost, Margin = outcome.Margin,
SwitchProgram = outcome.SwitchProgram, TechniquesRun = space.Count,
FiringTechniques = firing, BogusFires = bogusFires
};
break;
}
}
}
return winner ?? new ToyResult
{ TotalSteps = total, TechniquesRun = space.Count, FiringTechniques = firing, BogusFires = bogusFires };
}
}
// Simulateur de reference de l'attestation, distinct de ToyEngine.
// Il conserve les u prouves et les faux u dans deux tables distinctes, puis
// exige un u prouve pour SETSW et pour le theoreme cible.
public static class G2Reference
{
public static ToyOutcome Run(int[] technique, MondeJouet world, InstructionDef[] table)
{
var proven = new Dictionary<string, int>();
bool axiomFetched = false;
bool simulated = false;
bool containsBogus = technique.Any(index => table[index].Name == "BOGUS");
bool executedBogus = false;
bool usedBogus = false;
string nominated = "";
bool hasTarget = false;
int targetMargin = 0;
int steps = 0;
foreach (int index in technique)
{
steps++;
switch (table[index].Name)
{
case "GETAX":
axiomFetched = true;
break;
case "RULE":
if (!simulated && axiomFetched)
{
var state = world.InitialState();
foreach (string policy in MondeJouet.Policies)
{
proven[policy] = world.Simulate(policy, world.T1, state.Mode, state.Setups);
}
simulated = true;
}
else if (nominated.Length > 0)
{
if (proven.TryGetValue(nominated, out int chosen) &&
proven.TryGetValue(world.CurrentPolicy, out int current) &&
chosen > current)
{
hasTarget = true;
targetMargin = chosen - current;
usedBogus = false;
}
}
break;
case "CHECK":
if (hasTarget)
{
return new ToyOutcome
{
Fired = true,
FireCost = steps,
NaturalCost = steps,
Margin = targetMargin,
SwitchProgram = nominated,
ContainsBogus = containsBogus,
ExecutedBogus = executedBogus,
UsedBogusInProof = usedBogus,
TechniqueLength = technique.Length
};
}
break;
case "BOGUS":
executedBogus = true;
break;
case "SETSW":
if (proven.Count > 0)
{
nominated = proven.OrderByDescending(pair => pair.Value).First().Key;
}
break;
}
}
return new ToyOutcome
{
Fired = false,
NaturalCost = steps,
ContainsBogus = containsBogus,
ExecutedBogus = executedBogus,
UsedBogusInProof = usedBogus,
TechniqueLength = technique.Length,
Outcome = "end"
};
}
public static G2AuditSummary Audit(int lMax)
{
var world = new MondeJouet("A");
var space = ToyEngine.Space(ToyTables.Cheap, lMax);
var outcomes = space.ToDictionary(sequence => string.Join(",", sequence),
sequence => ToyEngine.Run(sequence, world, ToyTables.Cheap));
var reference = space.ToDictionary(sequence => string.Join(",", sequence),
sequence => G2Reference.Run(sequence, world, ToyTables.Cheap));
int mismatches = space.Count(sequence =>
{
string key = string.Join(",", sequence);
var actual = outcomes[key];
var expected = reference[key];
return actual.Fired != expected.Fired ||
actual.Margin != expected.Margin ||
actual.ContainsBogus != expected.ContainsBogus ||
actual.ExecutedBogus != expected.ExecutedBogus ||
actual.UsedBogusInProof != expected.UsedBogusInProof;
});
var firing = reference.Values.Where(outcome => outcome.Fired).ToList();
long expectedSpace = Enumerable.Range(0, lMax + 1)
.Sum(length => (long)Math.Pow(ToyTables.Cheap.Length, length));
return new G2AuditSummary
{
LMax = lMax,
ExpectedSpaceSize = expectedSpace,
ActualSpaceSize = space.Count,
FiringTechniques = firing.Count,
FiringWithBogusPresent = firing.Count(outcome => outcome.ContainsBogus),
FiringWithBogusExecuted = firing.Count(outcome => outcome.ExecutedBogus),
FiringWithBogusUsed = firing.Count(outcome => outcome.UsedBogusInProof),
ReferenceMismatches = mismatches,
BogusFiringMargins = firing.Where(outcome => outcome.ContainsBogus)
.Select(outcome => outcome.Margin).Distinct().OrderBy(margin => margin).ToList()
};
}
}
// Exercice 3 -- stub de l'enumeration exhaustive demandee par la source.
// TODO etudiant : utiliser ToyEngine.Space et ToyEngine.Run, puis distinguer
// ContainsBogus, ExecutedBogus et UsedBogusInProof. Ne pas confondre la presence
// d'une instruction avec son effet sur le theoreme cible.
public static G2Summary G2BogusExhaustive(int lMax)
{
// TODO etudiant
return new G2Summary();
}
var stubG2 = G2BogusExhaustive(ToyTables.LMax);
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Exercice a completer : espace {0}, feux {1}, Bogus present/execute/utilise = {2}/{3}/{4}.",
stubG2.SpaceSize,
stubG2.FiringTechniques,
stubG2.FiringWithBogusPresent,
stubG2.FiringWithBogusExecuted,
stubG2.FiringWithBogusUsed));
var mondeG2 = new MondeJouet("A");
var resG2 = ToyEngine.BioPS(mondeG2, ToyTables.Cheap, 40);
var outBogus = ToyEngine.Run(ToyTables.WBogus, mondeG2, ToyTables.Cheap);
Console.WriteLine();
Console.WriteLine("=== Gate G2 : FAQ 7 ===");
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Feux dont la preuve utilise BOGUS : {0}", resG2.BogusFires));
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Technique [BOGUS, GETAX, RULE, SETSW, CHECK] : present = {0}, execute = {1}, utilise = {2}, feu = {3}",
outBogus.ContainsBogus, outBogus.ExecutedBogus, outBogus.UsedBogusInProof, outBogus.Fired));
Console.WriteLine();
Console.WriteLine("=== Attestation exhaustive de G2 (controle externe au stub) ===");
foreach (int bound in new[] { ToyTables.LMax, ToyTables.LMax + 1 })
{
var audit = G2Reference.Audit(bound);
string margins = string.Join(", ", audit.BogusFiringMargins
.Select(margin => margin.ToString(CultureInfo.InvariantCulture)));
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Longueur <= {0} : espace geometrique = {1}, espace enumere = {2}, concordance = {3}",
bound, audit.ExpectedSpaceSize, audit.ActualSpaceSize,
audit.ExpectedSpaceSize == audit.ActualSpaceSize));
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Longueur <= {0} : feux = {1}, gains contenant BOGUS = {2}, dont BOGUS execute = {3}, dont BOGUS utilise dans la preuve = {4}",
bound, audit.FiringTechniques, audit.FiringWithBogusPresent,
audit.FiringWithBogusExecuted, audit.FiringWithBogusUsed));
Console.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Longueur <= {0} : marges distinctes des gains contenant BOGUS = [{1}], ecarts simulateur de reference = {2}",
bound, margins, audit.ReferenceMismatches));
}