④エニグマ暗号機のローター結線解読プロジェクト(コードを変更するも...)
プログラムの意味は分かるものの、まだ偶然性に頼っている。
もう少し、自分で群論を勉強してみますか。
以下はサンプルとして残しておくが、再チャレンジだ。
(* Define helper functions *)
cycleStructure[perm_] := Sort[Length /@ (Cycles[perm])];
(* Function to generate random permutation with prioritized 2-character cycles *)
randomPermWithPrioritized2Cycles[n_, prob2Cycle_:0.7] := Module[
{perm = Range[n], unused = Range[n], cycle},
While[Length[unused] > 1,
If[RandomReal[] < prob2Cycle || Length[unused] == 2,
cycle = RandomSample[unused, 2],
cycle = RandomSample[unused, RandomInteger[{2, Min[4, Length[unused]]}]]
];
perm[[cycle]] = RotateLeft[perm[[cycle]]];
unused = Complement[unused, cycle];
];
perm
]
(* Function to apply permutation *)
applyPerm[perm_, x_] := perm[[x]]
(* Function to calculate match score *)
matchScore[a_, b_, plaintext_, ciphertext_] := Module[
{m = Length[plaintext], scores},
scores = Table[
Count[
Table[
applyPerm[a, applyPerm[RotateLeft[b, r], plaintext[[i]]]] == ciphertext[[i]],
{i, 1, m}
],
True
]/m,
{r, 0, 25}
];
Max[scores]
]
(* Main cryptanalysis function *)
cryptanalysis[plaintext_, ciphertext_, sampleSize_:1000, matchThreshold_:0.5] := Module[
{n = 26, bestA, bestB, bestScore = 0, currentScore, allResults = {}},
(* Iterative sampling and scoring *)
Do[
Module[{a = randomPermWithPrioritized2Cycles[n],
b = randomPermWithPrioritized2Cycles[n]},
currentScore = matchScore[a, b, plaintext, ciphertext];
AppendTo[allResults, <|"A" -> a, "B" -> b, "Score" -> currentScore|>];
If[currentScore > bestScore,
bestScore = currentScore;
bestA = a;
bestB = b;
];
],
{sampleSize}
];
(* Sort results *)
allResults = SortBy[allResults, -#["Score"] &];
(* Return results *)
<|
"BestA" -> bestA,
"BestB" -> bestB,
"BestMatchScore" -> bestScore,
"AllResults" -> allResults
|>
]
(* Example usage *)
plaintext = {1, 2, 3, 4, 5, 6};
ciphertext = {15, 22, 3, 18, 9, 7};
result = cryptanalysis[plaintext, ciphertext, 1000, 0.3];
(* Print results *)
Print["Best match score: ", result["BestMatchScore"]];
Print["Best A permutation: ", result["BestA"]];
Print["Best B permutation: ", result["BestB"]];
Print["Best A cycle structure: ", cycleStructure[result["BestA"]]];
Print["Best B cycle structure: ", cycleStructure[result["BestB"]]];
Print["\nTop 5 results:"];
Do[
With[{r = result["AllResults"][[i]]},
Print["Rank ", i, ":"];
Print[" Score: ", r["Score"]];
Print[" A cycle structure: ", cycleStructure[r["A"]]];
Print[" B cycle structure: ", cycleStructure[r["B"]]];
],
{i, 1, Min[5, Length[result["AllResults"]]]}
]