Ejemplo n.º 1
0
        static decimal NewtonPolinom( decimal x, List<Tuple<decimal, decimal>> fAns, int n )
        {
            List<decimal> splitDiff = new List<decimal>();

            for( int i = 0; i < n; i++ )
                splitDiff.Add( fAns[i].Item2 );

            for( int k = 1; k < n; k++ )
                for( int i = n - 1; i >= k; i-- )
                    splitDiff[i] = (splitDiff[i] - splitDiff[i - 1]) / (fAns[i].Item1 - fAns[i - k].Item1);

            decimal ans = splitDiff[0];

            for( int i = 1; i < n; i++ )
            {
                decimal buf = splitDiff[i];

                for( int j = 0; j < i; j++ )
                    buf *= x - fAns[j].Item1;

                ans += buf;
            }

            return ans;
        }
Ejemplo n.º 2
0
        public string[] DecodeImage(Bitmap bmp)
        {
            var decodedSymbolsList = new List<string>();

            int objectMaxHeight = 0;
            int objectMaxWidth = 0;

            foreach (Standart standart in Standarts)
            {
                if (standart.IdealStandart.Height > objectMaxHeight)
                    objectMaxHeight = standart.IdealStandart.Height;
                if (standart.IdealStandart.Width > objectMaxWidth)
                    objectMaxWidth = standart.IdealStandart.Width;
            }

            int rows = bmp.Height/objectMaxHeight;
            int colls = bmp.Width/objectMaxWidth;

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < colls; j++)
                {
                    int x = j*objectMaxWidth;
                    int y = i*objectMaxHeight;
                    string symbol;
                    decodedSymbolsList.Add(DecodeSymbol(bmp, x, y, out symbol) ? symbol : "ERR");
                }
            }

            return decodedSymbolsList.ToArray();
        }
Ejemplo n.º 3
0
 static void Main(string[] args)
 {
     Genom genom = Incubator.CreateGenom(12, 10);
     List<Cell> cells = new List<Cell>();
     cells.Add(new Cell(1L));
     long counter = 2L;
     for (int j = 0; j < 12; j++)
     {
         List<Cell> newCells = new List<Cell>();
         for (int i = 0; i < cells.Count; i++)
         {
             if (cells[i].fissing)
             {
                 //Console.WriteLine("Fissing: " + cells[i].id);
                 newCells.Add(new Cell(counter++, cells[i]));
                 if (cells[i].id % (genom.genes[j] + 1) == 0)
                 {
                     //Console.WriteLine("Toggling: " + cells[i].id + ", gene: " + (genom.genes[j] + 1));
                     cells[i].fissing = !cells[i].fissing;
                 }
             }
         }
         cells.AddRange(newCells);
     }
     cells[0].neighbors.Add(cells[cells.Count - 1]);
     Dictionary<long, long> book = new Dictionary<long, long>();
     TextWriter tw = new StreamWriter("nodes.gml");
     tw.WriteLine("graph\n[\n\tnode\n\t[\n\t\tid 1 label 1\n\t]");
     foreach (Cell cell in cells)
     {
         foreach (Cell neighbor in cell.neighbors)
         {
             if (cell.id > neighbor.id)
             {
                 tw.WriteLine("\tnode\n\t[\n\t\tid " + cell.id + " label " + cell.id + "\n\t]\n\tedge\n\t[\n\t\tsource " + cell.id + " target " + neighbor.id + "\n\t]");
             }
         }
         //if (cell.ancestor != null)
         //{
         //    if (book.Keys.Contains(cell.ancestor.id))
         //    {
         //        book[cell.ancestor.id]++;
         //    }
         //    else
         //    {
         //        book.Add(cell.ancestor.id, 1);
         //    }
         //    Console.WriteLine(cell.id + ": " + cell.ancestor.id);
         //}
     }
     tw.WriteLine("]");
     tw.Flush();
     foreach (KeyValuePair<long, long> entry in book)
     {
         Console.WriteLine(entry.Key + " has " + entry.Value + " children");
     }
     Console.ReadKey();
 }
Ejemplo n.º 4
0
        //Обчислення матриці подібності
        public void calcResultMatrix(TextBox[][] valueEl, int sizeMatrix, NumericUpDown[] numUpDnArray)
        {
            mas = new List<HashSet<string>>();//Копіюю елементи з TextBox[][] в  List

            for (int i = 0; i < sizeMatrix; i++)
            {
                mas.Add(new HashSet<string>());

                for (int j = 0; j < (int)numUpDnArray[i].Value; j++)
                {
                    if (valueEl[i][j].Text == "") continue;

                    mas[i].Add(valueEl[i][j].Text);
                }
            }

            for (int i = 0; i < mas.Count; i++)//Видалення пустих рядків
            {
                if (mas.ElementAt(i).Count == 0)
                    mas.RemoveAt(i);
            }
            ////////////////////////////////////////////////////////////////////////////////////////
            resultMatrix = new List<List<int>>();
            for (int i = 0; i < mas.Count; i++)
            {
                resultMatrix.Add(new List<int>());
                for (int j = 0; j < mas.Count; j++)
                {
                    resultMatrix[i].Add(0);
                }
            }
            List<String> list; //List для злиття 2 рядків елементів
            for (int i = 0; i < mas.Count - 1; i++)
            {
                list = new List<String>();

                for (int j = 1; j < mas.Count; j++)
                {
                    if (i == j) continue;

                    list.AddRange(mas[i]);//Копіюю 1 рядок
                    list.AddRange(mas[j]);//Копіюю 2 рядок

                    /* list.Distinct() видаляє елементи, які повторюються, залишаючи перший з них.
                     * (list.Count - list.Distinct().Count()))*2 - дізнаюсь скільки спільних елементів
                     * (list.Count - (list.Count - list.Distinct().Count()) * 2) - дізнаюсь скільки унікальних елементів
                     * countUEl - (list.Count - (list.Count - list.Distinct().Count()) * 2) - від загальної кількості віднімаю унікальні в 2 рядках
                     */

                    resultMatrix[i][j] = countUEl - (list.Count - (list.Count - list.Distinct().Count()) * 2);

                    resultMatrix[j][i] = countUEl - (list.Count - (list.Count - list.Distinct().Count()) * 2);

                    list.Clear();//Очищаю для наступної пари рядків
                }
            }
        }
Ejemplo n.º 5
0
 public static string[] Split(this string str, string exp)
 {
     List<string> list = new List<string>();
     int s_index = 0;
     int end_index = 0;
     while (true)
     {
         s_index = str.IndexOf(exp, s_index);
         if (s_index == -1)
         {
             if (end_index < str.Length)
             {
                 list.Add(str.Substring(end_index, str.Length - end_index));
             }
             break;
         }
         list.Add(str.Substring(end_index, s_index - end_index));
         end_index = s_index + exp.Length;
         s_index++;
     }
     return list.ToArray();
 }
Ejemplo n.º 6
0
        protected ConcurrencyTest(Int32 threadCount)
        {
            if (threadCount <= 0)
                throw new ArgumentOutOfRangeException("threadCount");

            _threads = new List<Thread>(threadCount);
            _cancellationTokenSource = new CancellationTokenSource();
            for (int i = 0; i < threadCount; i++)
            {
                var thread = new Thread(ImitateWork) { Name = i.ToString(CultureInfo.InvariantCulture) };
                _threads.Add(thread);
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            Console.WriteLine("Podaj ilosc Kremowek: ");
            int intTemp = Convert.ToInt32(Console.ReadLine());
            List<Ciastka> lista_ciastek = new List<Ciastka>();
            lista_ciastek.Add(new Kremowka(intTemp));
            Console.WriteLine("Podaj ilosc Piegusek: ");
            intTemp = Convert.ToInt32(Console.ReadLine());
            lista_ciastek.Add(new Pieguski(intTemp));

            foreach (Ciastka ciacho in lista_ciastek)
            {
                ciacho.skladniki();
                ciacho.przygotowanie();
                ciacho.jedz();
            }

            //Kremowka jakkolwiek = new Kremowka(7);
            //jakkolwiek.skladniki();
            //jakkolwiek.przygotowanie();
            //jakkolwiek.jedz();
            Console.ReadKey();
        }
Ejemplo n.º 8
0
        private Standart[] InitStandarts()
        {
            var standarts = new List<Standart>(Constants.StandartResourseNames.Length);

            for (int i = 0; i < Constants.StandartResourseNames.Length; i++)
            {
                string standartResourseName = Constants.StandartResourseNames[i];
                var bmp = (Bitmap) Lab1.Standarts.ResourceManager.GetObject(standartResourseName);
                Standart standart = InitStandart(bmp);
                standart.Symbol = Constants.StandartSymbols[i];
                standarts.Add(standart);
            }

            return standarts.ToArray();
        }
 private void generateStartPoints()
 {
     long internalPeriod = T / n;
     startPoints = new long[n];
     startPoints[0] = Xk;
     List<Action> actionsList = new List<Action>();
     for (int i = 1; i < n; ++i)
     {
         int v = i;
         actionsList.Add(() => {
             startPoints[v] = GetSkipResult(v * internalPeriod);
         });
     }
     Parallel.ForEach(actionsList, (action => action.DynamicInvoke()));
     curPoint = 0;
 }
Ejemplo n.º 10
0
 public void Start()
 {
     StreamReader sr = new StreamReader(_inPath);
     StreamWriter sw = new StreamWriter(_outPath);
     string read;
     int i = 0;
     Solve solve;
     List<string> buffer = new List<string>();
     while ((read = sr.ReadLine()) != null)
     {
         try
         {
             i++;
             solve = new Solve(read);
             solve.Calculate();
             Console.WriteLine(String.Format("Line {0}: Beta = {1}; Gamma = {2}", i, solve.Beta, solve.Gamma));
             buffer.Add(String.Format("{0};{1};{2}", solve.A, solve.B, solve.C));
             if (buffer.Count == 100)
             {
                 foreach (string s in buffer)
                     sw.WriteLine(s);
                 buffer.Clear();
             }
         }
         catch (DataException de)
         {
             Console.WriteLine(String.Format("Line {0}: {1}", i, de.Message));
         }
         catch (ArgumentException ae)
         {
             Console.WriteLine(String.Format("Line {0}: Error! Need three arguments!", i));
         }
         catch (Exception e)
         {
             Console.WriteLine(String.Format("Line {0}: {1}", i, e.Message));
         }
         
     }
     foreach (string s in buffer)
         sw.WriteLine(s);
 }
Ejemplo n.º 11
0
        private int[] GetSamples(Bitmap bmp, int x, int y)
        {
            if (Standarts.Length == 0) return new int[0];

            var samples = new List<int>();

            unsafe
            {
                BitmapData bitmapData = bmp.LockBits(
                    new Rectangle(x, y, Standarts[0].IdealStandart.Width, Standarts[0].IdealStandart.Height),
                    ImageLockMode.ReadWrite, bmp.PixelFormat);

                int bytesPerPixel = Image.GetPixelFormatSize(bmp.PixelFormat)/8;
                int heightInPixels = bitmapData.Height;
                int widthInBytes = bitmapData.Width*bytesPerPixel;
                var ptrFirstPixel = (byte*) bitmapData.Scan0;

                for (int row = 0; row < heightInPixels; row++)
                {
                    int number = 0;
                    byte* currentLine = ptrFirstPixel + (row*bitmapData.Stride);
                    for (int startByte = 0, cell = 0;
                        startByte < widthInBytes;
                        startByte = startByte + bytesPerPixel, cell++)
                    {
                        int blue = currentLine[startByte];
                        int green = currentLine[startByte + 1];
                        int red = currentLine[startByte + 2];

                        if (blue + green + red == 0)
                        {
                            number |= 1 << cell;
                        }
                    }

                    samples.Add(number);
                }
                bmp.UnlockBits(bitmapData);
            }
            return samples.ToArray();
        }
Ejemplo n.º 12
0
        static void Main( string[] args )
        {
            List<Tuple<decimal, decimal>> fAns = new List<Tuple<decimal, decimal>>();

            decimal p = a;

            for( int t = n; t < 80; t++ )
            {
                if( t % 10 == 0 )
                    continue;

                Console.Write( "n = " + t + ": " );

                for( int i = 0; i < t; i++ )
                {
                    p = ((decimal)b - a) / 2 * (decimal)Math.Cos( (2 * (double)i + 1) / (2 * (t + 1)) * Math.PI) + ((decimal)b + a) / 2;

                    fAns.Add( new Tuple<decimal, decimal>( p, Func( p, e ) ) );

                    //p += (b - a) / (double)(t - 1);
                }

                decimal maxE = 0;

                for( decimal i = a; i <= b; i += (decimal)0.3 )
                {
                    decimal bufE = Math.Abs( Func( i, e ) - NewtonPolinom( i, fAns, t ) );

                    if( maxE < bufE )
                        maxE = bufE;
                }

                Console.WriteLine( maxE );

                fAns.Clear();
                p = a;
            }
        }
Ejemplo n.º 13
0
 public static int Add(string str)
 {
     Match m = Regex.Match(str, @"//(?<delimiter>.)\n(?<secgroup>\d(\k<delimiter>\d)*)*");
     Match m2 = Regex.Match(str, @"//(\[(?<delimiter>[^\[\]0-9]+)\])+\n(?<secgroup>(\d(?<delimiter>[^\[\]0-9]+)*)*)");
     string[] mass = m.Success ? m.Groups["secgroup"].Value.Split(m.Groups["delimiter"].Value) : m2.Success ? m2.Groups["secgroup"].Value.Split(m2.Groups["delimiter"].Captures.ToStringArray()) : str.Split(',', '\n');
     int[] mass_i = new int[mass.Length];
     int summ = 0;
     List<int> negatives = new List<int>();
     for (int i = 0; i < mass_i.Length; i++)
     {
         if (mass[i].Length == 0)
             return 0;
         Int32.TryParse(mass[i], out mass_i[i]);
         if (mass_i[i] < 0)
             negatives.Add(mass_i[i]);
         if (mass_i[i] > 1000)
             continue;
         else
             summ += mass_i[i];
     }
     if (negatives.Count > 1)
         throw new NegativeNumnerException(negatives);
     return summ;
 }
Ejemplo n.º 14
0
        //Вершини, які мають взаємозв'язок
        private List<List<DataVertex>> thirdСondition(Graph graph)
        {
            var vertices = graph.Vertices.ToList();
            var edges = graph.Edges.ToList();

            DataVertex v1 = new DataVertex();
            DataVertex v2 = new DataVertex();

            List<List<DataVertex>> listV = new List<List<DataVertex>>();
            for (int i = 0; i < vertices.Count; i++)//Йду по вершинах
            {
                var target = edges.FindAll(x => x.Source == vertices[i]);//Всі сини для даної вершини
                for (int j = 0; j < target.Count; j++)//Йду по всіх синах для поточної вершини
                {
                    var target2 = edges.FindAll(x => x.Source == target[j].Target);//Всі сини сина поточної вершини

                    for (int k = 0; k < target2.Count; k++)
                    {
                        if (target2[k].Target == vertices[i])//Якщо поточна вершина є сином її сина(тобто є взаємозв'язок)
                        {
                            v1 = vertices[i];
                            v2 = target2[k].Source;

                            List<DataVertex> list = new List<DataVertex>();
                            list.Add(v1);
                            list.Add(v2);

                            listV.Add(list);
                        }
                    }
                }
            }
            if (listV.Count == 0)
                return null;
            return listV;
        }
Ejemplo n.º 15
0
        //Створює графи на основі уточнених груп
        private Graph GenerateGraph()
        {
            graphs = new List<Graph>();//Лист графів для кожної групи
            for (int i = 0; i < calc.setElAfterV.Count; i++)
            {
                var Graph = new Graph();

                HashSet<string> tempSet = new HashSet<string>();

                foreach (string k in calc.setElAfterV[i])//Формування вершин
                {
                    var Vertex = new DataVertex(k);
                    Graph.AddVertex(Vertex);
                }

                var vlist = Graph.Vertices.ToList();

                for (int j = 0; j < calc.groupsAfterV[i].Count; j++)//Формування ребер
                {
                    for (int t = 0; t < calc.mas[calc.groupsAfterV[i].ElementAt(j)].Count - 1; t++)
                    {
                        var dataVertex1 = new DataVertex(calc.mas[calc.groupsAfterV[i].ElementAt(j)].ElementAt(t));
                        var dataVertex2 = new DataVertex(calc.mas[calc.groupsAfterV[i].ElementAt(j)].ElementAt(t + 1));

                        var Edge = new DataEdge(vlist.Find(x => x.Text == dataVertex1.Text), vlist.Find(x => x.Text == dataVertex2.Text))
                        { Text = string.Format("{0} -> {1}", vlist.Find(x => x.Text == dataVertex1.Text), vlist.Find(x => x.Text == dataVertex2.Text)) };

                        //Перевіряю чи є вже таке ребро
                        DataEdge temp = new DataEdge();
                        if (Graph.TryGetEdge(Edge.Source, Edge.Target, out temp) == false)
                            Graph.AddEdge(Edge);

                    }

                }
                graphs.Add(Graph);
            }
            totalGraph = new Graph();//Граф для відображення(об'єднує всі графи)
            for (int i = 0; i < graphs.Count; i++)
            {
                totalGraph.AddVertexRange(graphs.ElementAt(i).Vertices.ToList());
                totalGraph.AddEdgeRange(graphs.ElementAt(i).Edges.ToList());
            }
            return totalGraph;
        }
Ejemplo n.º 16
0
        private void genEdges(List<string> first, List<string> last)
        {
            ///////Поставлю модулі на відповідні місця
            List<List<string>> firstOrder = new List<List<string>>();
            firstOrder.Add(first);
            firstOrder.Add(last);

            foreach (List<string> list in calc.modulsAfterVerification)
            {
                if (list != first && list != last)
                    firstOrder.Insert(1, list);
            }
            //Проставляю зв'язки
            createEdgesAndFindMinFeedBack(firstOrder);
            //Виводжу результати створення зв'язків і уточнені модулі з першою та останньою групою
            outVModulsFrom(firstOrder);
            textBox2.Text += "\r\nКількість зворотніх зв'язків: " + createEdgesAndFindMinFeedBack(firstOrder);
            _gArea.GenerateGraph(true, true);//Перемальовую граф
        }
Ejemplo n.º 17
0
        //Пошук циклів
        private List<List<DataVertex>> fourthCondition(Graph graph)
        {
            var V = graph.Vertices.ToList();
            var E = graph.Edges.ToList();

            int[] color = new int[V.Count];//Масив, який містить кольори вершин
            for (int i = 0; i < V.Count; i++)
            {
                for (int k = 0; k < V.Count; k++)
                    color[k] = 1;
                List<int> cycle = new List<int>();
                cycle.Add(i);
                DFScycle(i, i, E, V, color, -1, cycle);//Пошук в глибину
            }

            catalogCycles.RemoveAll(x => x.Count == 2);//Видаляю ті, які не знайшли шляху до вершини
            catalogCycles.RemoveAll(x => x.Count > 5);//Видаляю ті, які мають більше 5 елементів(вони всеодно не згорнуться)
            if (catalogCycles.Count == 0)
                return null;
            return catalogCycles;
        }
Ejemplo n.º 18
0
        //Не має сенсу застосовувати(поки залишаю)
        private void firstAndSecondСondition(Graph graph, int indexOfGroup)
        {
            List<DataVertex> vertexInGraph = graph.Vertices.ToList();

            foreach (DataVertex v in vertexInGraph)
            {
                var outE = graph.OutEdges(v);
                var inE = graph.InEdges(v);

                if (outE.Count() > 0 && inE.Count() == 0)//Вершина має тільки ребра, що виходять
                {
                    var modul = new List<string>();
                    modul.Add(v.Text);

                    calc.moduls[indexOfGroup].Add(modul);

                }
                if (outE.Count() == 0 && inE.Count() > 0)//Вершина має тільки ребра, що входять
                {
                    var modul = new List<string>();
                    modul.Add(v.Text);

                    calc.moduls[indexOfGroup].Add(modul);
                }
            }
        }
Ejemplo n.º 19
0
        //Сортую групи і множини елементів за кількістю елементів(разом щоб співпадали)
        private void sortV(List<HashSet<int>> groupsAfterV, List<HashSet<string>> setElAfterV)
        {
            List<HashSet<int>> temp = new List<HashSet<int>>();
            List<HashSet<string>> temp2 = new List<HashSet<string>>();
            for (int i = 0; i < groupsAfterV.Count; i++)
            {
                for (int j = 0; j < groupsAfterV.Count - 1; j++)
                {
                    if (setElAfterV.ElementAt(j).Count < setElAfterV.ElementAt(j + 1).Count)
                    {
                        temp.Add(groupsAfterV.ElementAt(j));
                        groupsAfterV.Insert(j, groupsAfterV.ElementAt(j + 1));
                        groupsAfterV.RemoveAt(j + 1);
                        groupsAfterV.Insert(j + 1, temp.ElementAt(0));
                        groupsAfterV.RemoveAt(j + 2);
                        temp.Clear();

                        temp2.Add(setElAfterV.ElementAt(j));
                        setElAfterV.Insert(j, setElAfterV.ElementAt(j + 1));
                        setElAfterV.RemoveAt(j + 1);
                        setElAfterV.Insert(j + 1, temp2.ElementAt(0));
                        setElAfterV.RemoveAt(j + 2);
                        temp2.Clear();
                    }
                }
            }
        }
Ejemplo n.º 20
0
        //Вершини, які мають інший шлях до сина
        private List<List<DataVertex>> fifthCondition(Graph graph)
        {
            var V = graph.Vertices.ToList();
            var E = graph.Edges.ToList();

            int[] color = new int[V.Count];
            for (int i = 0; i < V.Count; i++)//Йду по всіх вершина
            {
                var eSonForV = E.FindAll(x => x.Source == V[i]);
                for (int j = 0; j < eSonForV.Count; j++)//Йду по всіх синах поточної вершини
                {
                    for (int k = 0; k < V.Count; k++)
                        color[k] = 1;
                    List<int> cycle = new List<int>();
                    int endV = V.FindIndex(0, V.Count, x => x == eSonForV[j].Target);
                    cycle.Add(i);
                    cycle.Add(endV);

                    DFScycleForFifth(i, endV, E, V, color, -1, cycle, graph);//Шукаю так само як в 4 умові але кінцевою вершиною є не початкова вершина, а її син
                    catalogCycles.RemoveAll(x => x.Count == 2);
                }
            }
            catalogCycles.RemoveAll(x => x.Count == 2);//Видаляю ті, які не знайшли шляху до вершини
            catalogCycles.RemoveAll(x => x.Count > 5);//Видаляю ті, які мають більше 5 елементів(вони всеодно не згорнуться)
            if (catalogCycles.Count == 0)
                return null;
            return catalogCycles;
        }
Ejemplo n.º 21
0
        //Пошук в глибину(для 5 умови)
        private void DFScycleForFifth(int u, int endV, List<DataEdge> E, List<DataVertex> V, int[] color, int unavailableEdge, List<int> cycle, Graph graph)
        {
            //если u == endV, то эту вершину перекрашивать не нужно, иначе мы в нее не вернемся, а вернуться необходимо
            if (u != endV)
                color[u] = 2;
            else if (cycle.Count >= 2)
            {
                cycle.Reverse();
                string s = cycle[0].ToString();
                for (int i = 1; i < cycle.Count; i++)
                    s += "-" + cycle[i].ToString();
                ///////////////////////
                List<DataVertex> list = new List<DataVertex>();//Додаю вершину в цикл
                list.Add(V.ElementAt(cycle[0]));
                for (int i = 1; i < cycle.Count - 1; i++)
                    list.Add(V.ElementAt(cycle[i]));
                ///////////////////////
                bool flag = false; //есть ли палиндром для этого цикла графа в List<string> catalogCycles?
                for (int i = 0; i < catalogCycles.Count; i++)
                    if (catalogCycles[i].ToString() == s)
                    {
                        flag = true;
                        break;
                    }
                if (!flag)
                {
                    cycle.Reverse();
                    list = new List<DataVertex>();
                    list.Add(V.ElementAt(cycle[0]));
                    for (int i = 1; i < cycle.Count - 1; i++)
                        list.Add(V.ElementAt(cycle[i]));
                    catalogCycles.Add(list);
                }
                return;
            }
            for (int w = 0; w < E.Count; w++)
            {
                var q = graph.OutEdges(V[V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text)]);
                if (w == unavailableEdge || (graph.InEdges(V[V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text)]).Count() > 1
                    || graph.OutEdges(V[V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text)]).Count() > 1) && V.FindIndex(x => x.Text == E[w].Target.Text) != endV)

                    continue;
                if (color[V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text)] == 1 && V.FindIndex(0, V.Count, x => x.Text == E[w].Source.Text) == u)
                {
                    List<int> cycleNEW = new List<int>(cycle);
                    cycleNEW.Add(V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text));
                    DFScycleForFifth(V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text), endV, E, V, color, w, cycleNEW, graph);
                    color[V.FindIndex(0, V.Count, x => x.Text == E[w].Target.Text)] = 1;
                }
            }
        }
Ejemplo n.º 22
0
        //Формування модулів(повна згортка всіх графів)
        private void createModuls()
        {
            //Роблю кожен елемент модулем
            for (int i = 0; i < graphs.Count; i++)
            {
                Dictionary<string, List<string>> nameVertexAndModul = new Dictionary<string, List<string>>();//Назва вершини в графі(key) і відповідні їй модулі(value)
                var vert = graphs[i].Vertices.ToList();
                calc.moduls.Add(i, new List<List<string>>());

                foreach (DataVertex v in vert)
                {
                    var modul = new List<string>();
                    modul.Add(v.Text);

                    calc.moduls[i].Add(modul);

                    nameVertexAndModul.Add(v.Text, new List<string>(modul));//Зв'язую назву вершини графа з модулями, які вона містить
                }
                nameVertexAndModuls.Add(nameVertexAndModul);
            }
            //Повна згортка графів
            for (int i = 0; i < graphs.Count; i++)
            {
                ///////////////////////////////
                createStepGraph(i);
                //////////////////////////////
                bool flag;//Продовжую згортати поки true(false означає, що більше граф згорнути не можна)
                do
                {
                    flag = false;
                    if (thirdСondition(graphs[i]) != null)//Якщо знайдено вершини, які задовольняють умову
                    {
                        foreach (List<DataVertex> v in thirdСondition(graphs[i]))//Згортаю почерзі вершини до першого успішного згортання
                        {
                            if (mergeVertex(graphs[i], i, v.ToArray()))//Поверне true, якщо згортка відбулася
                            {
                                flag = true;//Отже згортка відбуваля і могли з'явитися нові вершини, які задовольняють умові
                                ///////////////////////////////////////
                                createStepGraph(i);
                                //////////////////////////////////////////
                                break;
                            }
                        }

                    }

                    if (fourthCondition(graphs[i]) != null)
                    {
                        foreach (List<DataVertex> v in fourthCondition(graphs[i]))
                        {
                            if (mergeVertex(graphs[i], i, v.ToArray()))
                            {
                                flag = true;
                                ////////////////////////////////////
                                createStepGraph(i);
                                ///////////////////////////////////
                                break;
                            }
                        }
                        catalogCycles.Clear();
                    }

                    if (fifthCondition(graphs[i]) != null)
                    {
                        foreach (List<DataVertex> v in fifthCondition(graphs[i]))
                        {
                            if (mergeVertex(graphs[i], i, v.ToArray()))
                            {
                                flag = true;
                                /////////////////////////////////////////////
                                createStepGraph(i);
                                ////////////////////////////
                                break;
                            }
                        }
                        catalogCycles.Clear();
                    }

                } while (flag);
            }
            //////////////////////////////
            allGraphs.Add(totalGraph);
            _gArea.GenerateGraph(true, true);//Перемальовую граф

            currentGraph = allGraphs.Count - 1;//Поточний проміжний граф(повністю згорнутий)
        }
Ejemplo n.º 23
0
        //Розбиття на групи
        ////////////////До 2 лаби
        public void createGroups()
        {
            groups = new List<HashSet<int>>();
            int currentGroup = 0;
            do//Виконуємо поки всі елементи не розподілили по групам
            {
                int[] maxElIndex = maxEl(resultMatrix.Count, resultMatrix);
                if (maxElIndex == null && containsAllIndex() == false)//Якщо не можемо знайти максимальний елемент, який не входить в групи, але ще залишилися елементи
                {
                    createLastGroup();//Елементи, що залишилися об'єднуємо в одну групу
                    return;
                }
                groups.Add(new HashSet<int>());//Створюю нову групу
                groups.ElementAt(currentGroup).Add(maxElIndex[0]);//Записую в групу індекси максимального елемента (i)
                groups.ElementAt(currentGroup).Add(maxElIndex[1]);//(j)

                createGroupsNext(currentGroup, maxElIndex[0], maxElIndex[1]);

                currentGroup++;
            } while (containsAllIndex() == false);
        }
Ejemplo n.º 24
0
        //Сортування груп з однаковою кількістю елементів за перекриванням найбільшої кількості об'єктів
        private void sortWithEqualL(List<HashSet<string>> setElAfterV)
        {
            List<HashSet<string>> tempSet = new List<HashSet<string>>();
            tempSet.Add(setElAfterV[0]);
            for (int i = 0; i < setElAfterV.Count-1; i++ )
            {
                if (setElAfterV[i].Count == setElAfterV[i + 1].Count)
                {
                    tempSet.Add(setElAfterV[i + 1]);
                }
                else
                    break;
            }
            if(tempSet.Count > 1)
            {
                List<int> numberOverlapped = new List<int>();//Кількість перекритих об'єктів

                for (int i = 0; i < tempSet.Count(); i++)//Знаходжу скільки об'єктів перекриває кожна група
                {
                    numberOverlapped.Add(0);//Початкова кількість перекритих об'єктів
                    for (int k = 0; k < tempSet.Count(); k++)
                    {
                        if (i == k) continue;
                        for (int j = 0; j < groupsAfterV[k].Count; j++)
                        {
                            if (tempSet[i].IsSupersetOf(mas[groupsAfterV[k].ElementAt(j)]))//Являється підмножиною?
                            {
                                numberOverlapped[i]++;
                            }
                        }
                    }
                }

                for(int i = 0; i < tempSet.Count; i++)
                {
                    for (int j = i+1; j < tempSet.Count; j++)
                    {
                        if(numberOverlapped[i] > numberOverlapped[j])
                        {
                            int temp = numberOverlapped[i];
                            numberOverlapped[i] = numberOverlapped[j];
                            numberOverlapped[j] = temp;

                            List<HashSet<int>> tempGroup = new List<HashSet<int>>();
                            tempGroup.Add(groupsAfterV[i]);
                            groupsAfterV[i] = groupsAfterV[j];
                            groupsAfterV[j] = tempGroup[0];

                            List<HashSet<string>> tempEl = new List<HashSet<string>>();
                            tempEl.Add(setElAfterV[i]);
                            setElAfterV[i] = setElAfterV[j];
                            setElAfterV[j] = tempEl[0];
                        }
                    }
                }
            }
        }
Ejemplo n.º 25
0
        private int[] IncedenceMatrixRowFill(bool[] mask, bool[] idealStandart)
        {
            var realises = new List<int>();

            int number = 0;
            for (int i = 0; i < idealStandart.Length; i++)
            {
                if (idealStandart[i])
                {
                    number |= 1 << i;
                }
            }
            CreateRealises(realises, number, mask, 0);
            if (realises.Count == 0) realises.Add(number);
            return realises.ToArray();
        }
Ejemplo n.º 26
0
        ////////////6 Лаба
        private List<List<string>> findFirstAndLast()
        {
            List<string> listEl = new List<string>();
            for (int i = 0; i < calc.mas.Count; i++ )//Записую перші елементи кожного модуля
            {
                listEl.Add(calc.mas[i].First());
            }

            string elementFirst = listEl[0];//Елемент, який найчастіше є першим

            int elCount = 0;
            foreach(string el in listEl)
            {

                if (listEl.FindAll(x => x == el).Count > elCount)
                {
                    elCount = listEl.FindAll(x => x == el).Count;
                    elementFirst = el;
                }
            }
            List<string> first = calc.modulsAfterVerification.Find(x => x.Contains(elementFirst));
            /////////////////////////////////////////
            listEl.Clear();
            for (int i = 0; i < calc.mas.Count; i++ )//Записую останні елементи кожного модуля
            {
                listEl.Add(calc.mas[i].Last());
            }
            string elementLast = listEl[0];//Елемент, який найчастіше є останнім

            elCount = 0;
            foreach (string el in listEl)
            {

                if (listEl.FindAll(x => x == el).Count > elCount && first.Contains(el) == false)
                {
                    elCount = listEl.FindAll(x => x == el).Count;
                    elementLast = el;
                }
            }

            List<string> last = calc.modulsAfterVerification.Find(x => x.Contains(elementLast));
               /////////////////////

            List<List<string>> result = new List<List<string>>();
            result.Add(first);
            result.Add(last);

            return result;
        }
Ejemplo n.º 27
0
        private void CreateRealises(List<int> realises, int realise, bool[] mask, int startIndex)
        {
            for (int i = startIndex; i < mask.Length; i++)
            {
                if (mask[i])
                {
                    int localBitMask = 1 << i;

                    int number = realise | localBitMask;
                    if (!realises.Contains(number))
                        realises.Add(number);
                    CreateRealises(realises, number, mask, i + 1);

                    number = realise & ~localBitMask;
                    if (!realises.Contains(number))
                        realises.Add(number);
                    CreateRealises(realises, number, mask, i + 1);
                }
            }
        }
Ejemplo n.º 28
0
        //Уточнення модулів
        ////////////////5 Лаба
        public void createVerificationModuls()
        {
            totalGraph = allGraphs.Last();
            //Зливаю назви вершин і модулі в один словник
            nameVertexAndM = new Dictionary<string, List<string>>();

            for (int i = 0; i < nameVertexAndModuls.Count; i++)
            {
                for (int j = 0; j < nameVertexAndModuls[i].Count; j++)
                {
                    try//Ключ, який вже є в словнику не додаємо
                    {
                        nameVertexAndM.Add(nameVertexAndModuls[i].ElementAt(j).Key, nameVertexAndModuls[i].ElementAt(j).Value);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            nameVertexAndM = nameVertexAndM.OrderBy(a => a.Value.Count).ToDictionary(pair => pair.Key, pair => pair.Value);

            //Зливаю модулі для кожної групи в один List
            for (int i = 0; i < calc.moduls.Count; i++)
            {
                foreach (List<string> list in calc.moduls[i])
                {
                    calc.modulsAfterVerification.Add(list);
                }
            }

            calc.modulsAfterVerification.Sort((a, b) => a.Count - b.Count);//Сортую за кількістю елементів
            //Формую такі самі множини для перевірки підмножин
            List<HashSet<string>> setModuls = new List<HashSet<string>>();
            for (int i = 0; i < calc.modulsAfterVerification.Count; i++)
            {
                setModuls.Add(new HashSet<string>());
                for (int j = 0; j < calc.modulsAfterVerification[i].Count; j++)
                {

                    setModuls[i].Add(calc.modulsAfterVerification[i][j]);
                }
            }
            //Видаляю модулі, які є підмножиною інших модулів
            for (int i = 0; i < calc.modulsAfterVerification.Count - 1; i++)
            {
                for (int j = i + 1; j < calc.modulsAfterVerification.Count; j++)
                {

                    if (setModuls[i].IsSubsetOf(setModuls[j]))//Являється підмножиною?
                    {
                        calc.modulsAfterVerification.RemoveAt(i);
                        setModuls.RemoveAt(i);
                        //////
                        string temp = "";
                        foreach(string str in setModuls[i])
                        {
                            temp += str;
                        }
                        /////

                        totalGraph.RemoveVertex(totalGraph.Vertices.First(x => x.Text == temp));
                        nameVertexAndM.Remove(temp);
                        i--;
                        break;
                    }
                }
            }
            //Видаляю елементи, які є в інших модулях(з більшого)
            for (int i = 0; i < calc.modulsAfterVerification.Count - 1; i++)
            {
                for (int j = 0; j < calc.modulsAfterVerification[i].Count; j++)
                {
                    for (int k = 1; k < calc.modulsAfterVerification.Count; k++)
                    {
                        if (calc.modulsAfterVerification[k].Contains(calc.modulsAfterVerification[i][j]))
                        {
                            if (k == i) continue;
                            ///////////////////
                            if (calc.modulsAfterVerification[k].Count >= calc.modulsAfterVerification[i].Count)
                                calc.modulsAfterVerification[k].Remove(calc.modulsAfterVerification[i][j]);
                            else
                            {
                                calc.modulsAfterVerification[i].Remove(calc.modulsAfterVerification[i][j]);
                                j--;
                            }
                            ///////////////////
                            if (calc.modulsAfterVerification[i].Count == 0) calc.modulsAfterVerification.RemoveAt(i);
                            //////
                            string namev = "";
                            foreach (string s in calc.modulsAfterVerification[k])
                            {
                                namev += s;
                            }
                            totalGraph.Vertices.ElementAt(k).Text = namev;
                        }
                    }
                }
            }
             //Перезаписую назви вершин і відповідні їм модулі
            nameVertexAndM.Clear();

            foreach(List<string> list in calc.modulsAfterVerification)
            {
                string key = "";
                foreach(string name in list)
                   {
                       key += name;
                   }
                nameVertexAndM.Add(key, list);
            }
            /////////////////////////////////////////////
            totalGraph.RemoveEdgeIf(x => x.Text != "");//Видаляю всі зв'язки
            //Розтавляю нові вершини
            totalGraph.RemoveVertexIf(x => x.Text != "");

            foreach(string name in nameVertexAndM.Keys)
            {
                totalGraph.AddVertex(new DataVertex(name));
            }
        }
Ejemplo n.º 29
0
Archivo: Form1.cs Proyecto: Sh-alex/FCS
        private void Form1_Load(object sender, EventArgs e)
        {
            numericRows.Value = 14;
            numericCols.Value = 8;
            button1_Click(sender, e);
            string line = "";

            System.IO.StreamReader file =
                new System.IO.StreamReader("myVar.txt", Encoding.Default);
            int index = 0;
            while ((line = file.ReadLine()) != null)
            {
                List<string> list = new List<string>();

                for (int i = 0; i < line.Length - 1; i++)
                {
                    list.Add(line.Substring(i, 2));
                    i++;
                }

                for (int i = 0; i < list.Count; i++)
                {
                    valueEl[index][i].Text = list[i];
                }
                index++;
            }

            file.Close();
        }
Ejemplo n.º 30
0
        //Зливаю елементи в одну множину за результатами групування
        ////////////3 Лаба
        private List<HashSet<string>> createSet(List<HashSet<int>> groups)
        {
            List<HashSet<string>> setElOfGroups = new List<HashSet<string>>();

            for(int i = 0; i < groups.Count(); i++)
            {
                setElOfGroups.Add(new HashSet<string>());
                for(int j = 0; j < groups[i].Count(); j++)
                {
                    for (int k = 0; k < mas[groups[i].ElementAt(j)].Count; k++)
                    {
                        setElOfGroups[i].Add(mas[groups[i].ElementAt(j)].ElementAt(k));
                    }
                }
            }

            //setElOfGroups.Sort((a, b) => b.Count - a.Count);//Сортую за кількістю елементів (DESC)

            return setElOfGroups;
        }