Advertisement
OlgaPuzikova

Untitled

May 23rd, 2022
820
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace lab_6_met
  5. {
  6.     class Person
  7.     {
  8.         public string Name;
  9.         public List<int> Genotip ;   //генотип
  10.         public int Fenotip;    // фенотип, максимальный критерий
  11.  
  12.         public List<Person> Perents;//родитель
  13.         public bool Mutation;//мутировал ли
  14.         public int Index_mutation;//индекс мутации
  15.  
  16.         public Person(string name, List<int> genotip, int fenotip) { Name = name; Genotip = genotip; Fenotip = fenotip; }
  17.         public Person(string name, List<int> genotip, int fenotip, List<Person> perens) { Name = name; Genotip = genotip; Fenotip = fenotip;  Perents = perens;  }
  18.  
  19.         public Person(string name, List<int> genotip, int fenotip, bool mutation, int index_mutation) { Name = name; Genotip = genotip; Fenotip = fenotip; Mutation=mutation; Index_mutation=index_mutation;}
  20.  
  21.     }
  22.     class Program
  23.     {
  24.         public static List<int> Matrix(int m, int t1, int t2)
  25.         {
  26.             var rnd = new Random();
  27.             List<int> matrix = new List<int>();
  28.             for (int i = 0; i < m; i++)
  29.             {
  30.                 int lot = rnd.Next(t1, t2);
  31.                 matrix.Add(lot);
  32.                 //Console.Write($"{lot}{'\t'}");
  33.             }
  34.             Console.WriteLine();
  35.             matrix.Sort();
  36.             foreach (int i in matrix)
  37.             {
  38.                // Console.Write($"{i}{'\t'}");
  39.             }
  40.             return  matrix;
  41.         }
  42.  
  43.         public static List<int> Genotip(int m)
  44.         {
  45.             var rnd = new Random();
  46.             List<int> genotip = new List<int>();
  47.             for (int i = 0; i < m; i++)
  48.             {
  49.                 int gen = rnd.Next(0, 255);
  50.                 genotip.Add(gen);
  51.                // Console.Write($"{gen}{'\t'}");
  52.             }
  53.             return genotip;
  54.         }
  55.  
  56.         public static int Fenotip(List<int> matrix, List<int> genotip, int n)
  57.         {
  58.             int[] interval = new int [n]; // интервалы верхнии границы
  59.             int iter = Convert.ToInt32(Math.Floor(255 / Convert.ToDouble(n))); // округление промежутка интервала в меньшую сторону
  60.             int last = iter;
  61.             for (int i = 0; i < n; i++)
  62.             {  
  63.                 interval[i] = last;
  64.                 last += iter;
  65.             }
  66.  
  67.             int[] rez = new int[n];
  68.             for (int i = 0; i < genotip.Count; i++)
  69.             {
  70.                 int index = 0;
  71.                 for (int j = 0; j < n; j++)
  72.                 {
  73.                    if((genotip[i] <= interval[j]) & (genotip[i] >= interval[j]-iter))
  74.                    {
  75.                         index = j;
  76.                    }
  77.                    else if((genotip[i]>=iter*n) & (genotip[i] <= 255))
  78.                    {
  79.                         index = n - 1;
  80.                    }
  81.                 }
  82.                 rez[index] += matrix[i];
  83.             }
  84.            
  85.             int kriter = rez[0];
  86.             for (int i = 0; i < n; i++)
  87.             {
  88.                 if(kriter < rez[i])
  89.                 {
  90.                     kriter = rez[i];
  91.                 }
  92.             }
  93.  
  94.             return kriter;
  95.         }
  96.  
  97.         public static Person Star( List<Person> persons) //лучшая особь
  98.         {
  99.             Person stars = persons[0];
  100.             int star = persons[0].Fenotip;
  101.             foreach (var item in persons)
  102.             {
  103.                 if (star > item.Fenotip)
  104.                 {
  105.                     star = item.Fenotip;
  106.                     stars = item;
  107.                 }
  108.             }
  109.             Console.WriteLine($"Лучшая особь  в поколении:{stars.Name} Фенотип:{stars.Fenotip}");
  110.             return stars;
  111.         }
  112.  
  113.         public static bool Veroyat(double pk, string person) //метод вероятности участия красовера
  114.         {
  115.             int n = 10;
  116.             int[] mas = new int[n];
  117.             var rnd = new Random();
  118.             double kol = 10 * pk;
  119.            
  120.             for (int i = 0; i < 10; i++)
  121.             {
  122.                 if (i < kol)
  123.                 {
  124.                     mas[i] = 1;
  125.                 }
  126.                 else { mas[i] = 0;}
  127.             }
  128.  
  129.             while (n > 0)
  130.             {
  131.                 n--;
  132.                 int k = rnd.Next(n + 1);
  133.                 int value = mas[k];
  134.                 mas[k] = mas[n];
  135.                 mas[n] = value;
  136.             }
  137.  
  138.             bool ver;
  139.             int val_ver = rnd.Next(0, 10);
  140.             if (mas[val_ver] == 1)
  141.             {
  142.                 ver = true;
  143.             } else { ver = false; }
  144.            
  145.             if (ver)
  146.             {
  147.                 Console.WriteLine($"Особь:{person} в скрешевании участвует!");
  148.             }
  149.             else { Console.WriteLine($"Особь:{person} в скрешевании не участвует!"); }
  150.            
  151.             return ver;
  152.         }
  153.  
  154.         public static bool Veroyat_M(double pm) //вероятность мутации
  155.         {
  156.             int n = 10;
  157.             int[] mas = new int[n];
  158.             var rnd = new Random();
  159.             double kol = 10 * pm;
  160.  
  161.             for (int i = 0; i < 10; i++)
  162.             {
  163.                 if (i < kol)
  164.                 {
  165.                     mas[i] = 1;
  166.                 }
  167.                 else { mas[i] = 0; }
  168.             }
  169.  
  170.             while (n > 0)
  171.             {
  172.                 n--;
  173.                 int k = rnd.Next(n + 1);
  174.                 int value = mas[k];
  175.                 mas[k] = mas[n];
  176.                 mas[n] = value;
  177.             }
  178.             bool ver;
  179.             int val_ver = rnd.Next(0, 10);
  180.             if (mas[val_ver] == 1)
  181.             {
  182.                 ver = true;
  183.             }
  184.             else { ver = false; }
  185.  
  186.             return ver;
  187.         }
  188.  
  189.  
  190.         public static void Mutation(Person person) // мутация
  191.         {
  192.             var rnd = new Random();
  193.             int index_mut = rnd.Next(0, person.Genotip.Count);
  194.             int gen_mut = person.Genotip[index_mut];
  195.             Console.WriteLine($"Индекс: {index_mut}: Ген: {gen_mut}");
  196.             person.Index_mutation = index_mut;
  197.  
  198.             string BinaryCode = Convert.ToString(gen_mut, 2);
  199.             Console.WriteLine($"{BinaryCode}");
  200.             char[] convert_str = BinaryCode.ToCharArray();
  201.             int [] bit = new int [8];
  202.             int kol_elem = convert_str.Length;
  203.             int iter = 7;
  204.            
  205.             for (int i = convert_str.Length-1; i >=0 ; i--)
  206.             {
  207.                 bit[iter] = convert_str[i]-'0';
  208.                 iter--;
  209.             }
  210.             for (int i = iter; i >= 0; i--)
  211.             {
  212.                 bit[i] = 0;
  213.             }
  214.            
  215.             int index_change = rnd.Next(0, bit.Length);
  216.             if (bit[index_change] == 0)
  217.             {
  218.                 bit[index_change] = 1;
  219.             }
  220.             else
  221.             {
  222.                 bit[index_change] = 0;
  223.             }
  224.  
  225.             string bit_change = String.Join("", bit);
  226.             int gen_change = Convert.ToInt32(bit_change, 2);
  227.             Console.WriteLine($"строка {bit_change}, После перевода {gen_change}");
  228.             person.Genotip[index_mut] = gen_change;
  229.  
  230.         }
  231.  
  232.         public static Person Crossing(Person person1, Person person2, double pm, List<int> matrix, int n)
  233.         {
  234.            
  235.             string new_name = person1.Name+"_"+ person2.Name;
  236.             var rnd = new Random();
  237.             int k = rnd.Next(0, person1.Genotip.Count); // точка разбиения
  238.  
  239.             List<int> genotip_cild1 = new List<int>();
  240.             List<int> genotip_cild2 = new List<int>();
  241.  
  242.             for (int i = 0; i < person1.Genotip.Count; i++)
  243.             {
  244.                 if (i < k)
  245.                 {
  246.                     genotip_cild1.Add(person1.Genotip[i]);
  247.                     genotip_cild2.Add(person2.Genotip[i]);
  248.                 }
  249.                 else
  250.                 {
  251.                     genotip_cild1.Add(person2.Genotip[i]);
  252.                     genotip_cild2.Add(person1.Genotip[i]);
  253.                 }
  254.             }
  255.  
  256.             List<Person> P = new List<Person>();
  257.             P.Add(new Person(new_name, genotip_cild1, Fenotip(matrix, genotip_cild1, n), new List<Person>{person1, person2}));
  258.             P.Add(new Person(new_name, genotip_cild2, Fenotip(matrix, genotip_cild2, n), new List<Person> { person1, person2 }));
  259.  
  260.             if (Veroyat_M(pm))
  261.             {
  262.                 Mutation(P[0]);
  263.                 P[0].Mutation = true;
  264.             }
  265.             if (Veroyat_M(pm))
  266.             {
  267.                 Mutation(P[1]);
  268.                 P[1].Mutation = true;
  269.             }
  270.             int new_fenotip_1 = Fenotip(matrix, P[0].Genotip, n);
  271.             P[0].Fenotip = new_fenotip_1;
  272.             int new_fenotip_2 = Fenotip(matrix, P[1].Genotip, n);
  273.             P[1].Fenotip = new_fenotip_2;
  274.  
  275.  
  276.             if (new_fenotip_1 < new_fenotip_2)
  277.             {
  278.                 return P[0];
  279.             }
  280.             else
  281.             {
  282.  
  283.                 return P[1];
  284.  
  285.             }
  286.  
  287.         }
  288.  
  289.         public static void Print(Dictionary<int,List<Person>> generation)
  290.         {
  291.             foreach (var val in generation)
  292.             {
  293.                 Console.WriteLine();
  294.                 Console.WriteLine($"Поколение: {val.Key}");
  295.                 foreach (var item in val.Value)
  296.                 {
  297.                     Console.WriteLine($"Имя:{item.Name}; Фенотип: {item.Fenotip}; Мутация:{item.Mutation}; Индек мутации:{item.Index_mutation}");
  298.                     Console.WriteLine("Генотип:");
  299.                     foreach (var gen in item.Genotip)
  300.                     {
  301.                         Console.Write($"{gen} {'\t'}");
  302.                     }
  303.                     Console.WriteLine();
  304.                     Console.Write("Родители:");
  305.                     foreach (var pen in item.Perents)
  306.                     {
  307.                         if(pen==null)
  308.                         {
  309.                             Console.Write($"Начальное поколение!");
  310.                             break;
  311.                         }
  312.                         else
  313.                         {
  314.                             Console.Write($"{pen.Name} {'\t'}");
  315.                         }
  316.                        
  317.                     }
  318.                     Console.WriteLine();
  319.                     Console.WriteLine();
  320.                 }
  321.                 Console.WriteLine();
  322.                
  323.             }
  324.             Console.WriteLine();
  325.         }
  326.         static void Main(string[] args)
  327.         {
  328.             Console.WriteLine("Введите данные:");
  329.             Console.WriteLine("Число задач:");
  330.             int m = Convert.ToInt32(Console.ReadLine());
  331.             Console.WriteLine("Число процессоров:");
  332.             int n = Convert.ToInt32(Console.ReadLine());
  333.             Console.WriteLine("Диапазон 1:");
  334.             int t1= Convert.ToInt32(Console.ReadLine());
  335.             Console.WriteLine("Диапазон 2:");
  336.             int t2 = Convert.ToInt32(Console.ReadLine());
  337.             Console.WriteLine("Вероятность красовера (указывать значение через запятую):");
  338.             double pk = Convert.ToDouble(Console.ReadLine()); //вероятность кросовера
  339.             Console.WriteLine("Вероятность мутации:");
  340.             double pm= Convert.ToDouble(Console.ReadLine()); //вероятность мутации
  341.             Console.WriteLine("Количество особей в начале:");
  342.             int k = Convert.ToInt32(Console.ReadLine()); // количесвто особей в поколении
  343.             Console.WriteLine("Колличество раз повторений особей в поколениях:");
  344.             int kpovtor = Convert.ToInt32(Console.ReadLine()); // количество раз сколько особь повторяется в поколениях
  345.  
  346.             List<int> matrix = Matrix(m, t1, t2);
  347.            
  348.             Dictionary<int, List<Person>> generation = new Dictionary<int, List<Person>>(); //библиотека поколений
  349.            
  350.             int key = 0;
  351.             List<Person> persons = new List<Person>();
  352.             for (int i= 0; i < k; i++)
  353.             {
  354.                 string name = "O" + Convert.ToString(i);
  355.                 List<int> genotip = Genotip(m);
  356.                 int fen = Fenotip(matrix, genotip, n);
  357.                 List<Person> parens = new List<Person> { null, null };
  358.                 persons.Add(new Person(name, genotip, fen,parens));
  359.             }
  360.             generation.Add(key, persons);
  361.  
  362.             foreach (var item in generation[0])
  363.             {
  364.                 Console.WriteLine();
  365.                 Console.WriteLine($"Name:{item.Name}");
  366.                 Console.WriteLine("Genotip:");
  367.                 foreach (var i in item.Genotip)
  368.                 {
  369.                     Console.Write($"{i} {'\t'}");
  370.                 }
  371.                 Console.WriteLine();
  372.                 Console.WriteLine($"Fenotip:{ item.Fenotip}");
  373.             }
  374.             Console.WriteLine();
  375.             List<Person> person_star_gener = new List<Person>();
  376.             person_star_gener.Add(Star(generation[0])); // лучшая особь среди первого поколения
  377.  
  378.             //слудующие поколения
  379.             var rnd = new Random();
  380.             int index_pokolen = 1;
  381.  
  382.             string lastBestGenotype = "";
  383.             int sameGenotypeCount = 0;
  384.  
  385.             while (sameGenotypeCount <= kpovtor)
  386.             {
  387.                
  388.                 List<Person> Gener = new List<Person>();
  389.  
  390.                 for (int i = 0; i < k; i++)
  391.                 {
  392.                     bool flag_one = false;
  393.                     Person person_gen1 = generation[index_pokolen-1][0];
  394.  
  395.                     while (flag_one == false)
  396.                     {
  397.  
  398.                         int index_gener1 = rnd.Next(0, k);
  399.  
  400.                         flag_one = Veroyat(pk, generation[index_pokolen-1][index_gener1].Name);
  401.                         if (flag_one)
  402.                         {
  403.                             Gener.Add(generation[index_pokolen - 1][index_gener1]);
  404.                             person_gen1 = generation[index_pokolen - 1][index_gener1];
  405.                             break;
  406.                         }
  407.  
  408.                     }
  409.  
  410.                     List<Person> sort_person = generation[index_pokolen - 1].GetRange(0, persons.Count); //индекс 0 поколения ключ
  411.                     sort_person.Remove(person_gen1);
  412.  
  413.                     bool flag_tuo = false;
  414.  
  415.                     while (flag_tuo == false)
  416.                     {
  417.                         int index_gener2 = rnd.Next(0, sort_person.Count);
  418.                         Person person_gener = sort_person[index_gener2];
  419.  
  420.                         flag_one = Veroyat(pk, person_gener.Name);
  421.                         if (flag_one)
  422.                         {
  423.                             Gener.Add(person_gener);
  424.                             break;
  425.                         }
  426.  
  427.                     }
  428.  
  429.                 }
  430.  
  431.                 int index_k = 0;
  432.                 List<Person> next_generation = new List<Person>();
  433.  
  434.                 for (int i = 0; i < Gener.Count - 1; i++)
  435.                 {
  436.  
  437.                     Person star_person = generation[index_pokolen - 1][index_k];
  438.  
  439.                     Console.WriteLine();
  440.  
  441.                     if (i % 2 == 0)
  442.                     {
  443.                         Console.WriteLine();
  444.                         Person cildren1 = Gener[i];
  445.                         Person cildren2 = Gener[i + 1];
  446.  
  447.                         Person cildren_rez = Crossing(cildren1, cildren2, pm, matrix, n);
  448.                         Console.WriteLine(cildren_rez.Name, cildren_rez.Fenotip, cildren_rez.Perents);
  449.                         Console.WriteLine();
  450.                         index_k++;
  451.  
  452.                         if (star_person.Fenotip < cildren_rez.Fenotip)
  453.                         {
  454.                             next_generation.Add(star_person);
  455.                             Console.WriteLine($"{star_person.Name}:{star_person.Fenotip}");
  456.                         }
  457.                         else
  458.                         {
  459.                             next_generation.Add(cildren_rez);
  460.                             Console.WriteLine($"{cildren_rez.Name}:{cildren_rez.Fenotip}");
  461.                         }
  462.  
  463.                     }
  464.                 }
  465.                 generation.Add(index_pokolen, next_generation);
  466.  
  467.                 var bestPerson = Star(next_generation);
  468.                 person_star_gener.Add(bestPerson);// лучшая особь следующего поколения
  469.  
  470.                 if(!(String.Equals(lastBestGenotype, String.Join("", bestPerson.Genotip))))
  471.                 {
  472.                     lastBestGenotype = String.Join("", bestPerson.Genotip);
  473.                     sameGenotypeCount = 0;
  474.                 }
  475.                 else
  476.                 {
  477.                     sameGenotypeCount++;
  478.                 }
  479.  
  480.                 index_pokolen =index_pokolen+1;
  481.  
  482.             }
  483.             Print(generation);
  484.             foreach (var item in person_star_gener)
  485.             {
  486.                 Console.WriteLine($"Имя:{item.Name}; Фенотип: {item.Fenotip}; Мутация:{item.Mutation}; Индек мутации:{item.Index_mutation}");
  487.                 Console.WriteLine("Генотип:");
  488.                 foreach (var gen in item.Genotip)
  489.                 {
  490.                     Console.Write($"{gen} {'\t'}");
  491.                 }
  492.                 Console.WriteLine();
  493.             }
  494.             Console.WriteLine();
  495.                
  496.  
  497.            
  498.  
  499.         }
  500.     }
  501. }
  502.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement