using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CryptanalysisCore { class WordsFilter { public delegate bool FilterFunction(KeyValuePair word1, KeyValuePair word2); /// /// Obsahuje nalezené unikátní dvojice /// private Dictionary uniquePairs; /// /// Obsahuje nejlepší dvojice /// public Dictionary BestPairs { get; private set; } /// /// True v případě, že bylo nalezeno více odpovídajících si dvojic /// False v případě, že byla nalezena jen jedna. /// public bool Checked { get; private set; } public WordsFilter(Dictionary uniquePairs) { this.uniquePairs = uniquePairs; } /// /// Vyfiltruje z unikátních dvojic ty dvojice, které nesedí s ostatními. /// /// public Dictionary Filter(FilterFunction filterFunction) { var pairsCount = CountMatchesPairs(filterFunction); var bestCountPairs = TakeBestCountPairs(pairsCount); var bestPair = TakeBestPairs(bestCountPairs); return bestPair; } /*public Dictionary Filter() { return Filter(ArePairsMatch); }*/ /// /// Na základě předaných indexů vybere z unikátních dvojic ty nejlepší. /// /// /// private Dictionary TakeBestPairs(int[] bestIndexes) { int counter = 0; Dictionary bestPairs = new Dictionary(); foreach (var pair in uniquePairs) { if (bestIndexes.Contains(counter)) bestPairs[pair.Key] = pair.Value; counter++; } BestPairs = bestPairs; return bestPairs; } /// /// Vrátí indexy nejlepších dvojic /// /// /// private int[] TakeBestCountPairs(Dictionary pairsCount) { var taken = pairsCount.OrderByDescending(x => x.Value).Take(1).ToArray(); int max = taken.Length > 0 ? taken[0].Value : 0; Checked = max < 2 ? false : true; return pairsCount.Where(x => x.Value == max).Select(x => x.Key).ToArray(); } /// /// Spočítá, kolik unikátních dvojic si navzájem neodporuje. /// /// private Dictionary CountMatchesPairs(FilterFunction filterFunction) { Dictionary pairsCounter = new Dictionary(); int index = 0, counter; foreach (var pair in uniquePairs) { counter = 0; foreach (var testPair in uniquePairs) { if (filterFunction(pair, testPair)) counter++; } pairsCounter[index++] = counter; } return pairsCounter; } } }