Key.cs (2684B)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Cypher 8 { 9 internal class Key 10 { 11 public void createKey() 12 { 13 int count; 14 double[] ints = new double[1000]; 15 for(int i = 0; i < 1000; i++) 16 { 17 ints[i] = i; 18 } 19 double[] order = new double[1000]; 20 order = GeneratKey(); 21 22 Console.WriteLine("Now genarating key..."); 23 //相関係数が0.5より小さくなるまで鍵ファイルを生成し続ける。 24 count = 0; 25 while (ComputeCoeff(order.ToArray(), ints.ToArray()) > 0.5) 26 { 27 order = GeneratKey(); 28 count++; 29 Console.WriteLine(count); 30 } 31 32 Question question = new Question(); 33 string whereKeyFile = question.Questions("Where will you want to create the keyFile?", false); 34 35 36 //keyFileに書き出し 37 StreamWriter streamWriter = new StreamWriter(whereKeyFile); 38 for (count = 0; count < order.Length; count++) 39 { 40 streamWriter.WriteLine(order[count]); 41 } 42 streamWriter.Close(); 43 } 44 45 46 public double[] GeneratKey() 47 { 48 //順序ファイルの生成 49 int random; 50 int count = 1; 51 double[] order = new double[1000]; 52 //1000個数字が埋められるまで繰り返す。 53 while (count < 1000) 54 { 55 var randomer = new Random(); 56 random = randomer.Next(minValue: 0, maxValue: 1000); 57 58 //今までにない数かどうかを評価 59 if (Array.IndexOf(order, random) < 0) 60 { 61 //生成した変数を"order"に代入 62 order[count] = random; 63 count++; 64 } 65 } 66 return order; 67 } 68 public double ComputeCoeff(double[] values1, double[] values2) 69 { 70 if (values1.Length != values2.Length) 71 throw new ArgumentException("values must be the same length"); 72 73 var avg1 = values1.Average(); 74 var avg2 = values2.Average(); 75 76 var sum1 = values1.Zip(values2, (x1, y1) => (x1 - avg1) * (y1 - avg2)).Sum(); 77 78 var sumSqr1 = values1.Sum(x => Math.Pow((x - avg1), 2.0)); 79 var sumSqr2 = values2.Sum(y => Math.Pow((y - avg2), 2.0)); 80 81 var result = sum1 / Math.Sqrt(sumSqr1 * sumSqr2); 82 83 return result; 84 } 85 } 86 }