Example #1
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();
        }
Example #2
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;
        }
Example #3
0
 /// <summary>
 /// Метод AddClosestWordsToList
 /// выводит в объект ListBox интерфейса список слов с минимальным редакционным расстоянием
 /// по отношению к введенному слову
 /// </summary>
 /// <param name="closestWords">Список слов с минимальным редакционным расстоянием</param>
 private void AddClosestWordsToList(List<string> closestWords)
 {
     lbClosestWords.Items.Clear();
     for (int i = 0; i < closestWords.Count; i++)
     {
         lbClosestWords.Items.Add(closestWords[i]);
     }
 }
Example #4
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();
 }
Example #5
0
File: List.cs Project: tofka/Lab1
 public string ListUsers(List<User> list)
 {
     var query = list.Select(u => u.UserName).Take(10);
     string user = "******";
     foreach (string q in query) {
         user += q + "\n";
     }
     return string.Format("{0}", user);
 }
Example #6
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();//Очищаю для наступної пари рядків
                }
            }
        }
Example #7
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);
            }
        }
Example #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;
 }
Example #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);
 }
Example #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();
        }
Example #12
0
        private static List<string> GetWords(string filename)
        {
            filename = filename + ".txt";

            if (!File.Exists(filename))
                throw new FileNotFoundException(filename);

            var words = new List<string>();
            using (var sr = new StreamReader(filename))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    line = new string(line.Where(sym => char.IsLetter(sym) || char.IsWhiteSpace(sym)).ToArray()).ToLower();
                    var splitedLine = line.Split(new[] {' '},
                        StringSplitOptions.RemoveEmptyEntries);
                    words.AddRange(splitedLine);
                }
            }

            return words;
        }
Example #13
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();
 }
Example #14
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;
            }
        }
Example #15
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();
        }
Example #16
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;
 }
Example #17
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);//Перемальовую граф
        }
Example #18
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();
        }
Example #19
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);
                }
            }
        }
Example #20
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;
        }
Example #21
0
        ///////////////////////////////////////////////
        private void verificationRelations_Click(object sender, EventArgs e)
        {
            if (calc.modulsAfterVerification.Count != 0)
            {
                relationsWithM_Click(sender, e);

                List<List<string>> temp = new List<List<string>>();
                temp.AddRange(calc.modulsAfterVerification);
                //temp.Remove(findFirstAndLast()[0]);
                //temp.Remove(findFirstAndLast()[1]);

                //Всі перестановки
                var permutationsP = new Variations<List<string>>(temp, temp.Count);//Всі перестановки

                int feedback = 1000;
                List<List<string>> permutatiOptimal = new List<List<string>>();
                List<List<string>> permutation = new List<List<string>>();

                foreach (var p in permutationsP)
                {
                    //permutation.Add(findFirstAndLast()[0]);
                    permutation.AddRange(p);
                    //permutation.Add(findFirstAndLast()[1]);

                    if (createEdgesAndFindMinFeedBack(permutation) < feedback)
                    {
                        feedback = createEdgesAndFindMinFeedBack(permutation);
                        permutatiOptimal.Clear();
                        permutatiOptimal.AddRange(permutation);
                    }
                    permutation.Clear();
                }
                /////////////////////
                createEdgesAndFindMinFeedBack(permutatiOptimal);
                outVModulsFrom(permutatiOptimal);
                textBox2.Text += "\r\nКількість зворотніх зв'язків: " + feedback;
                _gArea.RelayoutGraph();
            }
        }
Example #22
0
        //Метод для злиття вершин(повертає true, якщо злиття відбулося)
        private bool mergeVertex(Graph graph, int indexOfGraph, params DataVertex[] list)
        {
            //Перевірка чи кількість елементів модуля <=5
            int count = 0;
            for (int n = 0; n < calc.moduls[indexOfGraph].Count; n++)
            {
                string namev = "";
                foreach (string s in calc.moduls[indexOfGraph].ElementAt(n))
                {
                    namev += s;
                }
                if (list.Any(x => x.Text == namev))
                {
                    count += calc.moduls[indexOfGraph].ElementAt(n).Count;
                }
            }
            if (count > 5 || list == null) return false;//Якщо модуль буде містити більше 5 елементів, то злиття не проводимо
            /////////////////////////////////////////////
            for (int i = 1; i < list.Length; i++)
            {
                //Видаляю спільні зв'язки
                _gArea.LogicCore.Graph.RemoveEdgeIf(x => x.Source == list[0] && x.Target == list[i]);
                graph.RemoveEdgeIf(x => x.Source == list[0] && x.Target == list[i]);
                _gArea.LogicCore.Graph.RemoveEdgeIf(x => x.Target == list[0] && x.Source == list[i]);
                graph.RemoveEdgeIf(x => x.Target == list[0] && x.Source == list[i]);
                //Зливаю елементи модулей та видаляю злиті
                for (int j = 0; j < calc.moduls[indexOfGraph].Count; j++)
                {
                    string str = "";
                    foreach (string s in calc.moduls[indexOfGraph].ElementAt(j))//Формую ім'я модуля
                    {
                        str += s;
                    }
                    if (str == list[0].Text)//Знаходжу відповідні вершині модулі
                    {
                        //calc.moduls[indexOfGraph].ElementAt(j).Add(list[i].Text);
                        calc.moduls[indexOfGraph].ElementAt(j).AddRange(nameVertexAndModuls[indexOfGraph][list[i].Text]);
                        //Міняю назву ключа(Створюю новий, а старий видаляю)
                        List<string> l = new List<string>();
                        l.AddRange(nameVertexAndModuls[indexOfGraph][list[i].Text]);

                        nameVertexAndModuls[indexOfGraph].Remove(str);
                        nameVertexAndModuls[indexOfGraph].Add(str + list[i].Text, l);
                        //////
                        nameVertexAndModuls[indexOfGraph][str + list[i]] = calc.moduls[indexOfGraph].ElementAt(j);
                    }
                    if (str == list[i].Text)//Видаляю злитий
                    {
                        calc.moduls[indexOfGraph].RemoveAt(j);
                        nameVertexAndModuls[indexOfGraph].Remove(str);
                        //nameVertexAndModuls[indexOfGraph][list[i].Text].Clear();
                        //nameVertexAndModuls[indexOfGraph][list[i].Text].AddRange(calc.moduls[indexOfGraph].ElementAt(j));
                    }
                }
                //Додаю назву вершини до загальної
                list[0].Text += list[i].Text;
                //Перенаправляю всі зв'язки
                var inE = new List<DataEdge>();
                inE.AddRange(graph.InEdges(list[i]));
                foreach (DataEdge e in inE)
                {
                    //e.Target = list[0];
                    //e.Text = string.Format("{0} -> {1}", e.Source, list[0]);

                    var Edge = new DataEdge(e.Source, list[0]) { Text = string.Format("{0} -> {1}", e.Source, list[0]) };
                    _gArea.LogicCore.Graph.AddEdge(Edge);
                    graph.AddEdge(Edge);
                }

                var outE = new List<DataEdge>();
                outE.AddRange(graph.OutEdges(list[i]));
                foreach (DataEdge e in outE)
                {
                    //e.Source = list[0];
                    //e.Text = string.Format("{0} -> {1}", list[0], e.Target);
                    var Edge = new DataEdge(list[0], e.Target) { Text = string.Format("{0} -> {1}", list[0], e.Target) };
                    _gArea.LogicCore.Graph.AddEdge(Edge);
                    graph.AddEdge(Edge);
                }

                //Видаляю вершини
                if (i == list.Count())
                {
                    _gArea.LogicCore.Graph.RemoveVertex(list[0]);
                    graph.RemoveVertex(list[0]);
                }
                _gArea.LogicCore.Graph.RemoveVertex(list[i]);
                graph.RemoveVertex(list[i]);

            }
            return true;
        }
Example #23
0
        private void outVModulsFrom(List<List<string>> source)
        {
            textBox2.Text = "Уточнені модулі:\n";
            int n = 1;
            textBox2.Text += "\r\n";

            foreach (List<string> list in source)
            {
                textBox2.Text += n + " модуль {  ";
                foreach (string j in list)
                {
                    textBox2.Text += j + "  ";
                }
                textBox2.Text += "}\r\n";
                n++;

            }
        }
Example #24
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;
                }
            }
        }
Example #25
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;
        }
Example #26
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;
        }
Example #27
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);
                }
            }
        }
Example #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));
            }
        }
Example #29
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;
        }
Example #30
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;
        }