public void FindIndexesOfGreatestElement(int a, int[] expected)
        {
            GetAMock(a);

            int[] actual = TwoDimensionalArray.FindIndexesOfGreatestElement(aMock);
            Assert.AreEqual(expected, actual);
        }
        public void FindSmallestElement(int a, int expected)
        {
            GetAMock(a);

            int actual = TwoDimensionalArray.FindSmallestElement(aMock);

            Assert.AreEqual(expected, actual);
        }
        public void CountElementsGreaterThenNeighbors(int a, int expected)
        {
            GetAMock(a);

            int actual = TwoDimensionalArray.CountElementsGreaterThenNeighbors(aMock);

            Assert.AreEqual(expected, actual);
        }
        public void TransposeArray(int a, int e)
        {
            GetAMock(a);
            GetExpectedMock(e);

            int[,] expected = expectedMock;
            int[,] actual   = TwoDimensionalArray.TransposeArray(aMock);
            Assert.AreEqual(expected, actual);
        }
Exemple #5
0
        public static Dictionary <string, T[, ]> ToTwoDimensionalArray <T, TBase>(
            this IList <TBase> items,
            Dictionary <string, Func <TBase, T[]> > selectors,
            TwoDimensionalArray dimensionality = TwoDimensionalArray.None)
        {
            // This code is covered by unit tests Acoustics.Test - change the unit tests before you change the class!
            Contract.Requires(items != null);
            Contract.Requires(selectors != null);

            var itemCount = items.Count;
            int keyCount  = selectors.Keys.Count;
            var result    = new Dictionary <string, T[, ]>(keyCount);

            foreach (var kvp in selectors)
            {
                var current = kvp.Value(items[0]);
                var value   = dimensionality == TwoDimensionalArray.None ? new T[itemCount, current.Length] : new T[current.Length, itemCount];
                result.Add(kvp.Key, value);
            }

            Parallel.ForEach(
                selectors,
                (kvp, state, index) =>
            {
                var key      = kvp.Key;
                var selector = kvp.Value;

                for (int i = 0; i < itemCount; i++)
                {
                    T[] line       = selector(items[i]);
                    var lineLength = line.Length;
                    for (int j = 0; j < lineLength; j++)
                    {
                        switch (dimensionality)
                        {
                        case TwoDimensionalArray.None:
                            result[key][i, j] = line[j];
                            break;

                        case TwoDimensionalArray.Transpose:
                            result[key][j, i] = line[j];
                            break;

                        case TwoDimensionalArray.Rotate90ClockWise:
                            result[key][lineLength - 1 - j, i] = line[j];
                            break;

                        default:
                            throw new NotImplementedException("Dimensionality not supported");
                        }
                    }
                }
            });

            return(result);
        }
        public TwoDimArrayMapper(TMatrix[,] matrix, TwoDimensionalArray dimensionality)
        {
            this.matrix         = matrix;
            this.dimensionality = dimensionality;

            this.Rows    = dimensionality == TwoDimensionalArray.None ? matrix.RowLength() : matrix.ColumnLength();
            this.Columns = dimensionality == TwoDimensionalArray.None
                               ? matrix.ColumnLength()
                               : matrix.RowLength();
        }
        public static T[,] ReadMatrixFromCsv <T>(FileEntry source, TwoDimensionalArray transform = TwoDimensionalArray.None)
        {
            Contract.Requires(source != null);

            using (var stream = source.OpenText())
            {
                var reader = new CsvReader(stream, DefaultConfiguration);

                return(reader.DecodeMatrix <T>(transform, true));
            }
        }
        public static void WriteMatrixToCsv <T>(FileInfo destination, T[,] matrix, TwoDimensionalArray dimensionality = TwoDimensionalArray.None)
        {
            Contract.Requires(destination != null);

            // not tested!
            using (var stream = destination.CreateText())
            {
                var writer = new CsvWriter(stream, DefaultConfiguration);

                var transformedMatrix = new TwoDimArrayMapper <T>(matrix, dimensionality);

                EncodeMatrixInner(writer, transformedMatrix, true);
            }
        }
        private static T[,] DecodeMatrix <T>(this CsvReader reader, TwoDimensionalArray dimensionality,
                                             bool includeRowIndex)
        {
            int rowCount;
            int columnCount;
            var csvRows = DecodeMatrix <T>(reader, includeRowIndex, out rowCount, out columnCount);

            var result = dimensionality == TwoDimensionalArray.None
                ? new T[rowCount, columnCount]
                : new T[columnCount, rowCount];

            for (int r = 0; r < csvRows.Count; r++)
            {
                var row = csvRows[r];
                for (int c = 0; c < row.Length; c++)
                {
                    switch (dimensionality)
                    {
                    case TwoDimensionalArray.None:
                        result[r, c] = row[c];
                        break;

                    case TwoDimensionalArray.Transpose:
                        result[c, r] = row[c];
                        break;

                    case TwoDimensionalArray.Rotate90ClockWise:
                        // note these operations are reversed and look wrong, but because they
                        // are being done on the LHS of assignment, the operations need to be inversed
                        result[c, rowCount - 1 - r] = row[c];
                        break;

                    case TwoDimensionalArray.Rotate90AntiClockWise:
                        // note these operations are reversed and look wrong, but because they
                        // are being done on the LHS of assignment, the operations need to be inversed
                        result[columnCount - 1 - c, r] = row[c];

                        break;

                    default:
                        throw new NotImplementedException("Other dimensionalities not implemented");
                    }
                }
            }

            return(result);
        }
Exemple #10
0
        public void RunParallelForTask()
        {
            try
            {
                TwoDimensionalArray array = new TwoDimensionalArray(10000, 10000, new ParallelForSumOfArray());
                var watch = Stopwatch.StartNew();
                int sum   = array.SumOfArrayElements();
                watch.Stop();
                this.writer.Write($"Parallel.For with local thread totals. Time Taken-->{watch.ElapsedMilliseconds}");
                array.Display(sum);
            }

            catch (OutOfMemoryException e)
            {
                logger.Error($"Out of Memory: {e.Message}");
            }
        }
Exemple #11
0
        public void RunSequentialSumOfArrayTask()
        {
            try
            {
                TwoDimensionalArray array = new TwoDimensionalArray(10000, 10000, new SequentialSumOfArray());
                var watch = Stopwatch.StartNew();
                int sum   = array.SumOfArrayElements();
                watch.Stop();
                this.writer.Write($"Regular Iteration. Time Taken-->{watch.ElapsedMilliseconds}");
                array.Display(sum);
            }

            catch (OutOfMemoryException e)
            {
                logger.Error($"Out of Memory: {e.Message}");
            }
        }
Exemple #12
0
 /// <summary>
 /// pomocná funkce pro GetPDF417Text
 /// </summary>
 /// <param name="indexListe"></param>
 /// <param name="liste"></param>
 /// <param name="i"></param>
 /// <param name="j"></param>
 private void Regroupe(ref int indexListe, ref TwoDimensionalArray liste, ref int i, ref int j)
 {
     if (indexListe > 1)
     {
         i = 1;
         while (i < indexListe)
         {
             if (liste.Get(1, i - 1) == liste.Get(1, i))
             {
                 liste.Set(0, i - 1, liste.Get(0, i - 1) + liste.Get(0, i));
                 j = i + 1;
                 while (j < indexListe)
                 {
                     liste.Set(0, j - 1, liste.Get(0, j));
                     liste.Set(1, j - 1, liste.Get(1, j));
                     j += 1;
                 }
                 indexListe -= 1;
                 i          -= 1;
             }
             i += 1;
         }
     }
 }
Exemple #13
0
        public bool IsPlanar(Graph graphArgument)
        {
            if (WorkerLog != null)
            {
                WorkerLog("Начало алгоритма Мак-Лейна");
            }
            var graph = new Graph(graphArgument);

            Debug.Assert(
                graph.Children.All(pair => pair.Value
                                   .All(value => graph.Children.ContainsKey(value) &&
                                        graph.Children[value].Contains(pair.Key))));

            if (WorkerBegin != null)
            {
                WorkerBegin();
            }
            // Шаг первый - удаляем все листья и узлы степени 2
            if (WorkerLog != null)
            {
                WorkerLog("Удаляем все листья и узлы степени 2");
            }

            // листья представляют собой дерево и нарисовать его плоскую укладку тривиально.
            graph.RemoveAllTrees();

            // Замечание. Если на ребра планарного графа нанести произвольное число вершин степени 2,
            // то он останется планарным; равным образом, если на ребра непланарного графа
            // нанести вершины степени 2, то он планарным не станет.
            graph.RemoveIntermedians();

            // Шаг второй - граф нужно укладывать отдельно по компонентам связности.
            var stackListQueue = new StackListQueue <Graph> {
                graph.GetAllSubGraphs()
            };

            if (WorkerLog != null)
            {
                WorkerLog("Находим ВСЕ пути в графе длины не более размера графа + 1");
            }
            // Глобальные кэшированные данные
            Dictionary <int, PathDictionary> cachedAllGraphPaths =
                graph.GetAllGraphPaths();

            foreach (Graph subGraph in stackListQueue)
            {
                if (WorkerLog != null)
                {
                    WorkerLog("Проверка связанной компоненты " + subGraph);
                }
                // листья представляют собой дерево и нарисовать его плоскую укладку тривиально.
                subGraph.RemoveAllTrees();
                if (subGraph.Vertices.Count() < 2)
                {
                    continue;
                }

                Dictionary <int, PathDictionary> cachedSubGraphPaths =
                    Graph.GetSubgraphPaths(subGraph.Vertices, cachedAllGraphPaths);

                if (WorkerLog != null)
                {
                    WorkerLog("Находим ВСЕ циклы в графе длины не менее 2 и не более размера графа");
                }
                var circles = new StackListQueue <Circle>(cachedSubGraphPaths.Where(pair => pair.Key > 2)
                                                          .SelectMany(pair => subGraph.Vertices
                                                                      .SelectMany(vertex => pair.Value.Where(pair2 => pair2.Key.Key.Equals(pair2.Key.Value))
                                                                                  .SelectMany(
                                                                                      pair2 => pair2.Value.Select(path => new Circle(path.GetRange(0, path.Count - 1)))))));
                if (WorkerLog != null)
                {
                    WorkerLog(string.Format("Количество циклов {0}", circles.Count()));
                }

                //if (WorkerLog != null) WorkerLog("Находим все циклы в графе");
                //IEnumerable<Circle> circles = subGraph.GetAllGraphCircles(cachedSubGraphPaths);

                if (!circles.Any())
                {
                    continue;                 // граф — дерево и нарисовать его плоскую укладку тривиально.
                }
                if (WorkerLog != null)
                {
                    WorkerLog("Удаляем дубликаты");
                }
                circles = new StackListQueue <Circle>(circles.Distinct(CircleComparer));
                if (WorkerLog != null)
                {
                    WorkerLog(string.Format("Количество циклов {0}", circles.Count()));
                }

                //Debug.Assert(subGraph.Vertices.Count() ==
                //             circles.SelectMany(circle => circle.ToList()).Distinct().Count());

                //     С технической точки зрения проверять, что цикл является простым и тау-циклом нет необходимости, поскольку не
                //     приведён алгорим позволяющий проверить , что цикл является тау-циклом за количество операций меньшее чем приведение
                //     матрицы к каноническому виду. Поэтому если действительно надо сделать хорошую реализацию, то либо надо закоментировать
                //     проверки циклов на простоту и что они являются тау-циклами с помощью приведения к каноническому виду , либо
                //     предложить алгоритм быстрой проверки, что цикл является тау-циклом

                if (WorkerLog != null)
                {
                    WorkerLog("Ограничиваем простыми циклами");
                }
                circles.RemoveAll(Circle.IsNotSimple);
                if (WorkerLog != null)
                {
                    WorkerLog(string.Format("Количество циклов {0}", circles.Count()));
                }

                if (WorkerLog != null)
                {
                    WorkerLog("Удаляем элементарные циклы и петли");
                }
                circles.RemoveAll(circle => circle.Count < 3);
                if (WorkerLog != null)
                {
                    WorkerLog(string.Format("Количество циклов {0}", circles.Count()));
                }

                //if (WorkerLog != null) WorkerLog("Ограничиваем тау-циклами");
                //circles.RemoveAll(circle => !circle.IsTau());
                //if (WorkerLog != null) WorkerLog(string.Format("Количество циклов {0}", circles.Count()));

                Debug.WriteLine(string.Join(Environment.NewLine, circles.Select(circle => circle.ToString())));

                if (WorkerLog != null)
                {
                    WorkerLog("Строим матрицу над GF2 из найденных циклов");
                }
                var booleanMatrix = new BooleanMatrix(circles.Select(subGraph.GetVector));
                if (WorkerLog != null)
                {
                    WorkerLog(string.Format("Размер матрицы {0}х{1}", booleanMatrix.Count(), booleanMatrix.Length));
                }

                foreach (var r in booleanMatrix)
                {
                    if (r.Count() < booleanMatrix.Length)
                    {
                        r.Add(Enumerable.Repeat(false, booleanMatrix.Length - r.Count()));
                    }
                }

                Debug.WriteLine("matrix:");
                Debug.WriteLine(booleanMatrix);

                // отыскание минимума некоторого функционала на множестве базисов подпространства квазициклов
                // Шаг 1. Приведение матрицы к каноническому виду
                if (WorkerLog != null)
                {
                    WorkerLog("Приводим матрицу к каноническому виду");
                }
                if (Settings.EnableCudafy)
                {
                    lock (CudafyMatrix.Semaphore)
                    {
                        try
                        {
                            /////////////////////////////////////////////////////
                            // Использование параллельных вычислений CUDA
                            // для приведения матрицы к каноническому виду
                            CudafyMatrix.SetMatrix(
                                new ArrayOfArray <int>(
                                    booleanMatrix.Select(vector => vector.Select(b => b ? 1 : 0).ToArray()).ToArray())
                                .ToTwoDimensional());

                            // Использование алгоритма Гаусса-Жордана
                            // Для приведения матрицы к каноническому виду
                            CudafyMatrix.ExecuteGaussJordan();

                            // Удаляем нулевые строки
                            int[][] arrayOfArray =
                                new TwoDimensionalArray <int>(CudafyMatrix.GetMatrix()).ToArrayOfArray();
                            booleanMatrix = new BooleanMatrix(CudafyMatrix.GetIndexes()
                                                              .Select((first, row) => new KeyValuePair <int, int>(row, first))
                                                              .Where(pair => pair.Value >= 0)
                                                              .Select(pair => arrayOfArray[pair.Key].Select(value => value != 0)));

                            CudafyMatrix.SetMatrix(
                                new ArrayOfArray <int>(
                                    booleanMatrix.Select(vector => vector.Select(b => b ? 1 : 0).ToArray()).ToArray())
                                .ToTwoDimensional());
                        }
                        catch (Exception ex)
                        {
                            if (WorkerLog != null)
                            {
                                WorkerLog(ex.ToString());
                            }
                            /////////////////////////////////////////////////////
                            // Приведение матрицы к каноническому виду обычным способом
                            booleanMatrix.GaussJordan();
                            booleanMatrix.RemoveAll(BooleanVector.IsZero);
                        }
                        if (WorkerLog != null)
                        {
                            WorkerLog(string.Format("Размер матрицы {0}х{1}", booleanMatrix.Count(),
                                                    booleanMatrix.Length));
                        }

                        // Матрица имеет канонический вид
                        Debug.WriteLine("matrix:");
                        Debug.WriteLine(booleanMatrix);
                        Debug.Assert(booleanMatrix.Select(vector => vector.IndexOf(true)).Distinct().Count() ==
                                     booleanMatrix.Count);
                        Debug.Assert(booleanMatrix.Select(vector => vector.IndexOf(true))
                                     .SelectMany(
                                         index => booleanMatrix.Where(vector => vector.Count > index && vector[index]))
                                     .Count() == booleanMatrix.Count);
                        // Поскольку в колонках содержится по одной единице, то к строке можно прибавить только одну другую строку
                        int n = booleanMatrix.Count;
                        int macLane;
                        try
                        {
                            /////////////////////////////////////////////////////
                            // Использование параллельных вычислений CUDA
                            // для расчёта целевой функции симплекс-метода
                            Debug.Assert(CudafyMatrix.GetMatrix() != null);
                            CudafyMatrix.SetIndexes(Enumerable.Range(0, n).ToArray());
                            CudafyMatrix.ExecuteMacLane();
                            macLane = CudafyMatrix.GetMacLane();
#if DEBUG
                            int[][] arrayOfArray = new TwoDimensionalArray <int>(CudafyMatrix.GetMatrix()).ToArrayOfArray();
                            Debug.WriteLine(string.Join(Environment.NewLine,
                                                        arrayOfArray.Select(v => string.Join(",", v.Select(i => i.ToString())))));
#endif
                        }
                        catch (Exception ex)
                        {
                            if (WorkerLog != null)
                            {
                                WorkerLog(ex.ToString());
                            }
                            ///////////////////////////////////////////////////
                            // Вычисление целевой функции обычным методом
                            macLane = booleanMatrix.MacLane;
                        }
                        Debug.WriteLine("macLane = " + macLane);
                        Debug.WriteLine("matrix:");
                        Debug.WriteLine(booleanMatrix);
                        int k = Math.Min(2, Math.Max(1, n));
                        k = Math.Min(n, k);
                        if (WorkerLog != null)
                        {
                            WorkerLog("Начало симплекс-метода");
                        }
                        if (WorkerLog != null)
                        {
                            WorkerLog("Текущий macLane = " + macLane);
                        }
                        for (bool updated = true; k <= n && updated && macLane > 0;)
                        {
                            Debug.Assert(booleanMatrix.Length == subGraph.Count());
                            List <int> values = Enumerable.Range(0, n).ToList();

                            updated = false;
                            List <int> indexOfIndex = Enumerable.Range(n - k, k).ToList();
                            while (macLane > 0)
                            {
                                if (WorkerLog != null)
                                {
                                    WorkerLog(string.Format("Перебираем индексы в позициях {0}",
                                                            string.Join(",",
                                                                        indexOfIndex.Select(index => index.ToString(CultureInfo.InvariantCulture)))));
                                }
                                CudafyMatrix.SetMatrix(
                                    new ArrayOfArray <int>(
                                        booleanMatrix.Select(vector => vector.Select(b => b ? 1 : 0).ToArray())
                                        .ToArray())
                                    .ToTwoDimensional());
                                List <int> indexes = values.ToList();
                                foreach (int index in indexOfIndex)
                                {
                                    indexes[index] = n - 1;
                                }
                                while (macLane > 0)
                                {
                                    Debug.Write(string.Format("Проверяем индексы {0} ... ",
                                                              string.Join(",",
                                                                          indexes.Select(index => index.ToString(CultureInfo.InvariantCulture)))));
                                    // Проверяем, что матрица образованная indexes является обратимой
                                    var detMatrix = new BooleanMatrix(indexes);
                                    if (detMatrix.Det())
                                    {
                                        BooleanMatrix matrix2;
                                        int           macLane2 = 0;
                                        try
                                        {
                                            /////////////////////////////////////////////////////
                                            // Использование параллельных вычислений CUDA
                                            // для расчёта целевой функции симплекс-метода
                                            Debug.Assert(CudafyMatrix.GetMatrix() != null);
                                            CudafyMatrix.SetIndexes(indexes.ToArray());
                                            CudafyMatrix.ExecuteMacLane();
                                            macLane2 = CudafyMatrix.GetMacLane();
#if DEBUG
                                            CudafyMatrix.ExecuteUpdate();
                                            int[][] arrayOfArray =
                                                new TwoDimensionalArray <int>(CudafyMatrix.GetMatrix()).ToArrayOfArray();
                                            matrix2 =
                                                new BooleanMatrix(
                                                    arrayOfArray.Select(r => new BooleanVector(r.Select(c => c != 0))));

                                            CudafyMatrix.SetMatrix(
                                                new ArrayOfArray <int>(
                                                    booleanMatrix.Select(v => v.Select(b => b ? 1 : 0).ToArray())
                                                    .ToArray())
                                                .ToTwoDimensional());
#endif
                                        }
                                        catch (Exception ex)
                                        {
                                            if (WorkerLog != null)
                                            {
                                                WorkerLog(ex.ToString());
                                            }
                                            ///////////////////////////////////////////////////
                                            // Вычисление целевой функции обычным методом
                                            Dictionary <int, int> dictionary =
                                                indexes.Select((item, value) => new KeyValuePair <int, int>(value, item))
                                                .ToDictionary(pair => pair.Key, pair => pair.Value);
                                            matrix2 = new BooleanMatrix(
                                                dictionary.Select(
                                                    pair1 =>
                                                    dictionary
                                                    .Where(
                                                        pair2 =>
                                                        pair2.Value == pair1.Key && pair2.Key != pair1.Key)
                                                    .Select(pair => booleanMatrix[pair.Key])
                                                    .Aggregate(booleanMatrix[pair1.Key], BooleanVector.Xor)));
                                            macLane2 = matrix2.MacLane;
                                        }
                                        finally
                                        {
                                            Debug.WriteLine("macLane = " + macLane2);
                                        }
                                        if (macLane > macLane2)
                                        {
                                            if (WorkerLog != null)
                                            {
                                                WorkerLog("Найденое решение улучшилось ( " + macLane + " -> " + macLane2 +
                                                          " )");
                                            }
                                            Debug.WriteLine("macLane: " + macLane + "->" + macLane2);
                                            values  = indexes.ToList();
                                            macLane = macLane2;
                                            updated = true;
                                            Debug.WriteLine(string.Join(",", values.Select(item => item.ToString())));
                                            Debug.WriteLine("matrix2:");
                                            Debug.WriteLine(matrix2);
                                        }
                                        if (macLane == 0)
                                        {
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        Debug.WriteLine("Матрица не обратима");
                                    }
                                    int i = k;
                                    while (i-- > 0)
                                    {
                                        if (indexes[indexOfIndex[i]]-- > 0)
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            indexes[indexOfIndex[i]] = n - 1;
                                        }
                                    }
                                    if (i < 0)
                                    {
                                        break;
                                    }
                                }
                                int count = k;
                                while (count-- > 0)
                                {
                                    if (indexOfIndex[count]-- > (count == 0 ? 0 : (indexOfIndex[count - 1] + 1)))
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        indexOfIndex[count] = (count == (k - 1)
                                            ? n - 1
                                            : (indexOfIndex[count + 1] - 1));
                                    }
                                }
                                if (count < 0)
                                {
                                    break;
                                }
                            }
                            if (WorkerLog != null)
                            {
                                WorkerLog("Смена начальной точки симплекс-метода");
                            }
                            try
                            {
                                /////////////////////////////////////////////////////
                                // Использование параллельных вычислений CUDA
                                // для смены базиса симплекс-метода
                                Debug.Assert(CudafyMatrix.GetMatrix() != null);
                                CudafyMatrix.SetIndexes(values.ToArray());
                                CudafyMatrix.ExecuteUpdate();
#if DEBUG
                                int[][] arrayOfArray =
                                    new TwoDimensionalArray <int>(CudafyMatrix.GetMatrix()).ToArrayOfArray();
                                booleanMatrix =
                                    new BooleanMatrix(arrayOfArray.Select(r => new BooleanVector(r.Select(c => c != 0))));
#endif
                            }
                            catch (Exception ex)
                            {
                                if (WorkerLog != null)
                                {
                                    WorkerLog(ex.ToString());
                                }
                                ///////////////////////////////////////////////////
                                // Cмена базиса симплекс-метода обычным методом
                                Dictionary <int, int> dictionary =
                                    values.Select((item, value) => new KeyValuePair <int, int>(value, item))
                                    .ToDictionary(pair => pair.Key, pair => pair.Value);
                                booleanMatrix = new BooleanMatrix(
                                    dictionary.Select(
                                        pair1 =>
                                        dictionary
                                        .Where(pair2 => pair2.Value == pair1.Key && pair2.Key != pair1.Key)
                                        .Select(pair => booleanMatrix[pair.Key])
                                        .Aggregate(booleanMatrix[pair1.Key], BooleanVector.Xor)));
                            }
                            Debug.WriteLine(string.Join(",", values.Select(item => item.ToString())));
                            Debug.WriteLine("matrix:");
                            Debug.WriteLine(booleanMatrix);
                        }
                        if (macLane > 0)
                        {
                            if (WorkerLog != null)
                            {
                                WorkerLog("Не найдено нулевое значение фунции Мак-Лейна");
                            }
                            if (WorkerLog != null)
                            {
                                WorkerLog("Граф не планарен");
                            }
                            bool result = false;
                            if (WorkerComplite != null)
                            {
                                WorkerComplite(result);
                            }
                            return(result);
                        }
                    }
                }
                else
                {
                    // Приведение матрицы к каноническому виду обычным способом
                    booleanMatrix.GaussJordan();
                    booleanMatrix.RemoveAll(BooleanVector.IsZero);
                    if (WorkerLog != null)
                    {
                        WorkerLog(string.Format("Размер матрицы {0}х{1}", booleanMatrix.Count(),
                                                booleanMatrix.Length));
                    }
                    int macLane = booleanMatrix.MacLane;
                    Debug.WriteLine("macLane = " + macLane);
                    Debug.WriteLine("matrix:");
                    Debug.WriteLine(booleanMatrix);
                    int n = booleanMatrix.Count;
                    int k = Math.Min(2, Math.Max(1, n));
                    k = Math.Min(n, k);
                    if (WorkerLog != null)
                    {
                        WorkerLog("Начало симплекс-метода");
                    }
                    if (WorkerLog != null)
                    {
                        WorkerLog("Текущий macLane = " + macLane);
                    }
                    for (bool updated = true; k <= n && updated && macLane > 0;)
                    {
                        Debug.Assert(booleanMatrix.Length == subGraph.Count());
                        List <int> values = Enumerable.Range(0, n).ToList();

                        updated = false;
                        List <int> indexOfIndex = Enumerable.Range(n - k, k).ToList();
                        while (macLane > 0)
                        {
                            if (WorkerLog != null)
                            {
                                WorkerLog(string.Format("Перебираем индексы в позициях {0}",
                                                        string.Join(",",
                                                                    indexOfIndex.Select(index => index.ToString(CultureInfo.InvariantCulture)))));
                            }
                            CudafyMatrix.SetMatrix(
                                new ArrayOfArray <int>(
                                    booleanMatrix.Select(vector => vector.Select(b => b ? 1 : 0).ToArray())
                                    .ToArray())
                                .ToTwoDimensional());
                            List <int> indexes = values.ToList();
                            foreach (int index in indexOfIndex)
                            {
                                indexes[index] = n - 1;
                            }
                            while (macLane > 0)
                            {
                                Debug.Write(string.Format("Проверяем индексы {0} ... ",
                                                          string.Join(",",
                                                                      indexes.Select(index => index.ToString(CultureInfo.InvariantCulture)))));
                                // Проверяем, что матрица образованная indexes является обратимой
                                var detMatrix = new BooleanMatrix(indexes);
                                if (detMatrix.Det())
                                {
                                    int macLane2 = 0;
                                    ///////////////////////////////////////////////////
                                    // Вычисление целевой функции обычным методом
                                    Dictionary <int, int> dictionary =
                                        indexes.Select((item, value) => new KeyValuePair <int, int>(value, item))
                                        .ToDictionary(pair => pair.Key, pair => pair.Value);
                                    var matrix2 = new BooleanMatrix(
                                        dictionary.Select(
                                            pair1 =>
                                            dictionary
                                            .Where(
                                                pair2 =>
                                                pair2.Value == pair1.Key && pair2.Key != pair1.Key)
                                            .Select(pair => booleanMatrix[pair.Key])
                                            .Aggregate(booleanMatrix[pair1.Key], BooleanVector.Xor)));
                                    macLane2 = matrix2.MacLane;
                                    Debug.WriteLine("macLane = " + macLane2);
                                    if (macLane > macLane2)
                                    {
                                        if (WorkerLog != null)
                                        {
                                            WorkerLog("Найденое решение улучшилось ( " + macLane + " -> " + macLane2 +
                                                      " )");
                                        }
                                        Debug.WriteLine("macLane: " + macLane + "->" + macLane2);
                                        values  = indexes.ToList();
                                        macLane = macLane2;
                                        updated = true;
                                        Debug.WriteLine(string.Join(",", values.Select(item => item.ToString())));
                                        Debug.WriteLine("matrix2:");
                                        Debug.WriteLine(matrix2);
                                    }
                                    if (macLane == 0)
                                    {
                                        break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine("Матрица не обратима");
                                }
                                int i = k;
                                while (i-- > 0)
                                {
                                    if (indexes[indexOfIndex[i]]-- > 0)
                                    {
                                        break;
                                    }
                                    else
                                    {
                                        indexes[indexOfIndex[i]] = n - 1;
                                    }
                                }
                                if (i < 0)
                                {
                                    break;
                                }
                            }
                            int count = k;
                            while (count-- > 0)
                            {
                                if (indexOfIndex[count]-- > (count == 0 ? 0 : (indexOfIndex[count - 1] + 1)))
                                {
                                    break;
                                }
                                else
                                {
                                    indexOfIndex[count] = (count == (k - 1)
                                        ? n - 1
                                        : (indexOfIndex[count + 1] - 1));
                                }
                            }
                            if (count < 0)
                            {
                                break;
                            }
                        }
                        if (WorkerLog != null)
                        {
                            WorkerLog("Смена начальной точки симплекс-метода");
                        }
                        ///////////////////////////////////////////////////
                        // Cмена базиса симплекс-метода обычным методом
                        Dictionary <int, int> dictionary2 =
                            values.Select((item, value) => new KeyValuePair <int, int>(value, item))
                            .ToDictionary(pair => pair.Key, pair => pair.Value);
                        booleanMatrix = new BooleanMatrix(
                            dictionary2.Select(
                                pair1 =>
                                dictionary2
                                .Where(pair2 => pair2.Value == pair1.Key && pair2.Key != pair1.Key)
                                .Select(pair => booleanMatrix[pair.Key])
                                .Aggregate(booleanMatrix[pair1.Key], BooleanVector.Xor)));
                        Debug.WriteLine(string.Join(",", values.Select(item => item.ToString())));
                        Debug.WriteLine("matrix:");
                        Debug.WriteLine(booleanMatrix);
                    }
                    if (macLane > 0)
                    {
                        if (WorkerLog != null)
                        {
                            WorkerLog("Не найдено нулевое значение фунции Мак-Лейна");
                        }
                        if (WorkerLog != null)
                        {
                            WorkerLog("Граф не планарен");
                        }
                        bool result = false;
                        if (WorkerComplite != null)
                        {
                            WorkerComplite(result);
                        }
                        return(result);
                    }
                }
                if (WorkerLog != null)
                {
                    WorkerLog("Конец проверки связанной компоненты");
                }
            }
            {
                if (WorkerLog != null)
                {
                    WorkerLog("Конец алгоритма Мак-Лейна");
                }
                if (WorkerLog != null)
                {
                    WorkerLog("Граф планарен");
                }
                bool result = true;
                if (WorkerComplite != null)
                {
                    WorkerComplite(result);
                }
                return(result);
            }
        }
Exemple #14
0
        /// <summary>
        /// převede zadaný text na řetězec, který se dál zpracuje na binární data
        /// </summary>
        /// <param name="BarcodeText">text</param>
        /// <param name="ErrorCorrectionLevel">úroveň odolnosti proti chybám, max. 9</param>
        /// <param name="Columns">počet sloupců výsledného BC</param>
        /// <param name="ErrorCode">návratová hodnota - případný chybový stav</param>
        /// <returns></returns>
        private string GetPDF417Text(string BarcodeText, int ErrorCorrectionLevel, int Columns, out int ErrorCode)
        {
            int                 I           = 0;
            int                 J           = 0;
            int                 K           = 0;
            int                 indexChaine = 0;
            string              dummy;
            Boolean             flag;
            TwoDimensionalArray liste      = new TwoDimensionalArray();
            int                 indexListe = 0;
            int                 longueur;
            string              chaineMC = "";
            Int64               total;
            TwoDimensionalArray listeT = new TwoDimensionalArray();
            int                 curTable;
            string              chaineT;
            int                 newTable;
            OneDimensionalArray MCcorrection = new OneDimensionalArray();
            int                 c1;
            int                 c2;
            int                 c3;
            int                 mode      = 0;
            int                 codeASCII = 0;
            string              chaineMod;
            int                 diviseur;
            string              chaineMult = "";
            int                 nombre     = 0;
            string              ASCII;
            string              pdf417 = "";

            ASCII = "07260810082004151218042104100828082308241222042012131216121712190400040104020403040404050406040704080409121408000801042308020825080301000101010201030104010501060107010801090110011101120113011401150116011701180119012001210122012301240125080408050806042408070808020002010202020302040205020602070208020902100211021202130214021502160217021802190220022102220223022402250826082108270809";
            string[] coefRS = new string[9];
            coefRS[0] = "027917";
            coefRS[1] = "522568723809";
            coefRS[2] = "237308436284646653428379";
            coefRS[3] = "274562232755599524801132295116442428295042176065";
            coefRS[4] = "361575922525176586640321536742677742687284193517273494263147593800571320803133231390685330063410";
            coefRS[5] = "539422006093862771453106610287107505733877381612723476462172430609858822543376511400672762283184440035519031460594225535517352605158651201488502648733717083404097280771840629004381843623264543";
            coefRS[6] = "521310864547858580296379053779897444400925749415822093217208928244583620246148447631292908490704516258457907594723674292272096684432686606860569193219129186236287192775278173040379712463646776171491297763156732095270447090507048228821808898784663627378382262380602754336089614087432670616157374242726600269375898845454354130814587804034211330539297827865037517834315550086801004108539";
            coefRS[7] = "524894075766882857074204082586708250905786138720858194311913275190375850438733194280201280828757710814919089068569011204796605540913801700799137439418592668353859370694325240216257284549209884315070329793490274877162749812684461334376849521307291803712019358399908103511051008517225289470637731066255917269463830730433848585136538906090002290743199655903329049802580355588188462010134628320479130739071263318374601192605142673687234722384177752607640455193689707805641048060732621895544261852655309697755756060231773434421726528503118049795032144500238836394280566319009647550073914342126032681331792620060609441180791893754605383228749760213054297134054834299922191910532609829189020167029872449083402041656505579481173404251688095497555642543307159924558648055497010";
            coefRS[8] = "352077373504035599428207409574118498285380350492197265920155914299229643294871306088087193352781846075327520435543203666249346781621640268794534539781408390644102476499290632545037858916552041542289122272383800485098752472761107784860658741290204681407855085099062482180020297451593913142808684287536561076653899729567744390513192516258240518794395768848051610384168190826328596786303570381415641156237151429531207676710089168304402040708575162864229065861841512164477221092358785288357850836827736707094008494114521002499851543152729771095248361578323856797289051684466533820669045902452167342244173035463651051699591452578037124298332552043427119662777475850764364578911283711472420245288594394511327589777699688043408842383721521560644714559062145873663713159672729";
            coefRS[8] = coefRS[8] + "624059193417158209563564343693109608563365181772677310248353708410579870617841632860289536035777618586424833077597346269757632695751331247184045787680018066407369054492228613830922437519644905789420305441207300892827141537381662513056252341242797838837720224307631061087560310756665397808851309473795378031647915459806590731425216548249321881699535673782210815905303843922281073469791660162498308155422907817187062016425535336286437375273610296183923116667751353062366691379687842037357720742330005039923311424242749321054669316342299534105667488640672576540316486721610046656447171616464190531297321762752533175134014381433717045111020596284736138646411877669141919045780407164332899165726600325498655357752768223849647063310863251366304282738675410389244031121303263";
            string[] codageMC = new string[3];
            codageMC[0] = "urAxfsypyunkxdwyozpDAulspBkeBApAseAkprAuvsxhypnkutwxgzfDAplsfBkfrApvsuxyfnkptwuwzflspsyfvspxyftwpwzfxyyrxufkxFwymzonAudsxEyolkucwdBAoksucidAkokgdAcovkuhwxazdnAotsugydlkoswugjdksosidvkoxwuizdtsowydswowjdxwoyzdwydwjofAuFsxCyodkuEwxCjclAocsuEickkocgckcckEcvAohsuayctkogwuajcssogicsgcsacxsoiycwwoijcwicyyoFkuCwxBjcdAoEsuCicckoEguCbcccoEaccEoEDchkoawuDjcgsoaicggoabcgacgDobjcibcFAoCsuBicEkoCguBbcEcoCacEEoCDcECcascagcaacCkuAroBaoBDcCBtfkwpwyezmnAtdswoymlktcwwojFBAmksFAkmvkthwwqzFnAmtstgyFlkmswFksFkgFvkmxwtizFtsmwyFswFsiFxwmyzFwyFyzvfAxpsyuyvdkxowyujqlAvcsxoiqkkvcgxobqkcvcamfAtFswmyqvAmdktEwwmjqtkvgwxqjhlAEkkmcgtEbhkkqsghkcEvAmhstayhvAEtkmgwtajhtkqwwvijhssEsghsgExsmiyhxsEwwmijhwwqyjhwiEyyhyyEyjhyjvFkxmwytjqdAvEsxmiqckvEgxmbqccvEaqcEqcCmFktCwwljqhkmEstCigtAEckvaitCbgskEccmEagscqgamEDEcCEhkmawtDjgxkEgsmaigwsqiimabgwgEgaEgDEiwmbjgywEiigyiEibgybgzjqFAvCsxliqEkvCgxlbqEcvCaqEEvCDqECqEBEFAmCstBighAEEkmCgtBbggkqagvDbggcEEEmCDggEqaDgg";
            codageMC[0] = codageMC[0] + "CEasmDigisEagmDbgigqbbgiaEaDgiDgjigjbqCkvBgxkrqCcvBaqCEvBDqCCqCBECkmBgtArgakECcmBagacqDamBDgaEECCgaCECBEDggbggbagbDvAqvAnqBBmAqEBEgDEgDCgDBlfAspsweyldksowClAlcssoiCkklcgCkcCkECvAlhssqyCtklgwsqjCsslgiCsgCsaCxsliyCwwlijCwiCyyCyjtpkwuwyhjndAtoswuincktogwubncctoancEtoDlFksmwwdjnhklEssmiatACcktqismbaskngglEaascCcEasEChklawsnjaxkCgstrjawsniilabawgCgaawaCiwlbjaywCiiayiCibCjjazjvpAxusyxivokxugyxbvocxuavoExuDvoCnFAtmswtirhAnEkxviwtbrgkvqgxvbrgcnEEtmDrgEvqDnEBCFAlCssliahACEklCgslbixAagknagtnbiwkrigvrblCDiwcagEnaDiwECEBCaslDiaisCaglDbiysaignbbiygrjbCaDaiDCbiajiCbbiziajbvmkxtgywrvmcxtavmExtDvmCvmBnCktlgwsrraknCcxtrracvnatlDraEnCCraCnCBraBCCklBgskraakCCclBaiikaacnDalBDiicrbaCCCiiEaaCCCBaaBCDglBrabgCDaijgabaCDDijaabDCDrijrvlcxsqvlExsnvlCvlBnBctkqrDcnBEtknrDEvlnrDCnBBrDBCBclAqaDcCBElAnibcaDEnBnibErDnCBBibCaDBibBaDqibqibnxsfvkltkfnAmnAlCAoaBoiDoCAlaBlkpkBdAkosBckkogsebBcckoaBcEkoDBhkkqwsfjBgskqiBggkqbBgaBgDBiwkrjBiiBibBjjlpAsuswhil";
            codageMC[0] = codageMC[0] + "oksuglocsualoEsuDloCBFAkmssdiDhABEksvisdbDgklqgsvbDgcBEEkmDDgElqDBEBBaskniDisBagknbDiglrbDiaBaDBbiDjiBbbDjbtukwxgyirtucwxatuEwxDtuCtuBlmkstgnqklmcstanqctvastDnqElmCnqClmBnqBBCkklgDakBCcstrbikDaclnaklDbicnraBCCbiEDaCBCBDaBBDgklrDbgBDabjgDbaBDDbjaDbDBDrDbrbjrxxcyyqxxEyynxxCxxBttcwwqvvcxxqwwnvvExxnvvCttBvvBllcssqnncllEssnrrcnnEttnrrEvvnllBrrCnnBrrBBBckkqDDcBBEkknbbcDDEllnjjcbbEnnnBBBjjErrnDDBjjCBBqDDqBBnbbqDDnjjqbbnjjnxwoyyfxwmxwltsowwfvtoxwvvtmtslvtllkossfnlolkmrnonlmlklrnmnllrnlBAokkfDBolkvbDoDBmBAljbobDmDBljbmbDljblDBvjbvxwdvsuvstnkurlurltDAubBujDujDtApAAokkegAocAoEAoCAqsAqgAqaAqDAriArbkukkucshakuEshDkuCkuBAmkkdgBqkkvgkdaBqckvaBqEkvDBqCAmBBqBAngkdrBrgkvrBraAnDBrDAnrBrrsxcsxEsxCsxBktclvcsxqsgnlvEsxnlvCktBlvBAlcBncAlEkcnDrcBnEAlCDrEBnCAlBDrCBnBAlqBnqAlnDrqBnnDrnwyowymwylswotxowyvtxmswltxlksosgfltoswvnvoltmkslnvmltlnvlAkokcfBloksvDnoBlmAklbroDnmBllbrmDnlAkvBlvDnvbrvyzeyzdwyexyuwydxytswetwuswdvxutwtvxtkselsuksdntulstrvu";
            codageMC[1] = "ypkzewxdAyoszeixckyogzebxccyoaxcEyoDxcCxhkyqwzfjutAxgsyqiuskxggyqbuscxgausExgDusCuxkxiwyrjptAuwsxiipskuwgxibpscuwapsEuwDpsCpxkuywxjjftApwsuyifskpwguybfscpwafsEpwDfxkpywuzjfwspyifwgpybfwafywpzjfyifybxFAymszdixEkymgzdbxEcymaxEEymDxECxEBuhAxasyniugkxagynbugcxaaugExaDugCugBoxAuisxbiowkuigxbbowcuiaowEuiDowCowBdxAoysujidwkoygujbdwcoyadwEoyDdwCdysozidygozbdyadyDdzidzbxCkylgzcrxCcylaxCEylDxCCxCBuakxDgylruacxDauaExDDuaCuaBoikubgxDroicubaoiEubDoiCoiBcykojgubrcycojacyEojDcyCcyBczgojrczaczDczrxBcykqxBEyknxBCxBBuDcxBquDExBnuDCuDBobcuDqobEuDnobCobBcjcobqcjEobncjCcjBcjqcjnxAoykfxAmxAluBoxAvuBmuBloDouBvoDmoDlcbooDvcbmcblxAexAduAuuAtoBuoBtwpAyeszFiwokyegzFbwocyeawoEyeDwoCwoBthAwqsyfitgkwqgyfbtgcwqatgEwqDtgCtgBmxAtiswrimwktigwrbmwctiamwEtiDmwCmwBFxAmystjiFwkmygtjbFwcmyaFwEmyDFwCFysmziFygmzbFyaFyDFziFzbyukzhghjsyuczhahbwyuEzhDhDyyuCyuBwmkydgzErxqkwmczhrxqcyvaydDxqEwmCxqCwmBxqBtakwngydrviktacwnavicxrawnDviEtaCviCtaBviBmiktbgwnrqykmictb";
            codageMC[1] = codageMC[1] + "aqycvjatbDqyEmiCqyCmiBqyBEykmjgtbrhykEycmjahycqzamjDhyEEyChyCEyBEzgmjrhzgEzahzaEzDhzDEzrytczgqgrwytEzgngnyytCglzytBwlcycqxncwlEycnxnEytnxnCwlBxnBtDcwlqvbctDEwlnvbExnnvbCtDBvbBmbctDqqjcmbEtDnqjEvbnqjCmbBqjBEjcmbqgzcEjEmbngzEqjngzCEjBgzBEjqgzqEjngznysozgfgfyysmgdzyslwkoycfxloysvxlmwklxlltBowkvvDotBmvDmtBlvDlmDotBvqbovDvqbmmDlqblEbomDvgjoEbmgjmEblgjlEbvgjvysegFzysdwkexkuwkdxkttAuvButAtvBtmBuqDumBtqDtEDugbuEDtgbtysFwkFxkhtAhvAxmAxqBxwekyFgzCrwecyFaweEyFDweCweBsqkwfgyFrsqcwfasqEwfDsqCsqBliksrgwfrlicsraliEsrDliCliBCykljgsrrCycljaCyEljDCyCCyBCzgljrCzaCzDCzryhczaqarwyhEzananyyhCalzyhBwdcyEqwvcwdEyEnwvEyhnwvCwdBwvBsncwdqtrcsnEwdntrEwvntrCsnBtrBlbcsnqnjclbEsnnnjEtrnnjClbBnjBCjclbqazcCjElbnazEnjnazCCjBazBCjqazqCjnaznzioirsrfyziminwrdzzililyikzygozafafyyxozivivyadzyxmyglitzyxlwcoyEfwtowcmxvoyxvwclxvmwtlxvlslowcvtnoslmvrotnmsllvrmtnlvrllDoslvnbolDmrjonbmlDlrjmnblrjlCbolDvajoCbmizoajmCblizmajlizlCbvajvzieifwrFzzididyiczygeaFzywuy";
            codageMC[1] = codageMC[1] + "gdihzywtwcewsuwcdxtuwstxttskutlusktvnutltvntlBunDulBtrbunDtrbtCDuabuCDtijuabtijtziFiFyiEzygFywhwcFwshxsxskhtkxvlxlAxnBxrDxCBxaDxibxiCzwFcyCqwFEyCnwFCwFBsfcwFqsfEwFnsfCsfBkrcsfqkrEsfnkrCkrBBjckrqBjEkrnBjCBjBBjqBjnyaozDfDfyyamDdzyalwEoyCfwhowEmwhmwElwhlsdowEvsvosdmsvmsdlsvlknosdvlroknmlrmknllrlBboknvDjoBbmDjmBblDjlBbvDjvzbebfwnpzzbdbdybczyaeDFzyiuyadbhzyitwEewguwEdwxuwgtwxtscustuscttvustttvtklulnukltnrulntnrtBDuDbuBDtbjuDbtbjtjfsrpyjdwrozjcyjcjzbFbFyzjhjhybEzjgzyaFyihyyxwEFwghwwxxxxschssxttxvvxkkxllxnnxrrxBBxDDxbbxjFwrmzjEyjEjbCzjazjCyjCjjBjwCowCmwClsFowCvsFmsFlkfosFvkfmkflArokfvArmArlArvyDeBpzyDdwCewauwCdwatsEushusEtshtkdukvukdtkvtAnuBruAntBrtzDpDpyDozyDFybhwCFwahwixsEhsgxsxxkcxktxlvxAlxBnxDrxbpwnuzboybojDmzbqzjpsruyjowrujjoijobbmyjqybmjjqjjmwrtjjmijmbbljjnjjlijlbjkrsCusCtkFukFtAfuAftwDhsChsaxkExkhxAdxAvxBuzDuyDujbuwnxjbuibubDtjbvjjusrxijugrxbjuajuDbtijvibtbjvbjtgrwrjtajtDbsrjtrjsqjsnBxjDxiDxbbxgnyrbxabxDDwrbxrbwqbwn";
            codageMC[2] = "pjkurwejApbsunyebkpDwulzeDspByeBwzfcfjkprwzfEfbspnyzfCfDwplzzfBfByyrczfqfrwyrEzfnfnyyrCflzyrBxjcyrqxjEyrnxjCxjBuzcxjquzExjnuzCuzBpzcuzqpzEuznpzCdjAorsufydbkonwudzdDsolydBwokzdAyzdodrsovyzdmdnwotzzdldlydkzynozdvdvyynmdtzynlxboynvxbmxblujoxbvujmujlozoujvozmozlcrkofwuFzcnsodyclwoczckyckjzcucvwohzzctctycszylucxzyltxDuxDtubuubtojuojtcfsoFycdwoEzccyccjzchchycgzykxxBxuDxcFwoCzcEycEjcazcCycCjFjAmrstfyFbkmnwtdzFDsmlyFBwmkzFAyzFoFrsmvyzFmFnwmtzzFlFlyFkzyfozFvFvyyfmFtzyflwroyfvwrmwrltjowrvtjmtjlmzotjvmzmmzlqrkvfwxpzhbAqnsvdyhDkqlwvczhBsqkyhAwqkjhAiErkmfwtFzhrkEnsmdyhnsqtymczhlwEkyhkyEkjhkjzEuEvwmhzzhuzEthvwEtyzhthtyEszhszyduExzyvuydthxzyvtwnuxruwntxrttbuvjutbtvjtmjumjtgrAqfsvFygnkqdwvEzglsqcygkwqcjgkigkbEfsmFygvsEdwmEzgtwqgzgsyEcjgsjzEhEhyzgxgxyEgzgwzycxytxwlxxnxtDxvbxmbxgfkqFwvCzgdsqEygcwqEjgcigcbEFwmCzghwEEyggyEEjggjEazgizgFsqCygEwqCjgEigEbECygayECjgajgCwqBjgCigCbEBjgDjgBigBbCrklfwspzCnsldyClwlczCkyCkjzCuCvwlhzzCtCtyCszyFuCx";
            codageMC[2] = codageMC[2] + "zyFtwfuwftsrusrtljuljtarAnfstpyankndwtozalsncyakwncjakiakbCfslFyavsCdwlEzatwngzasyCcjasjzChChyzaxaxyCgzawzyExyhxwdxwvxsnxtrxlbxrfkvpwxuzinArdsvoyilkrcwvojiksrciikgrcbikaafknFwtmzivkadsnEyitsrgynEjiswaciisiacbisbCFwlCzahwCEyixwagyCEjiwyagjiwjCazaiziyzifArFsvmyidkrEwvmjicsrEiicgrEbicaicDaFsnCyihsaEwnCjigwrajigiaEbigbCCyaayCCjiiyaajiijiFkrCwvljiEsrCiiEgrCbiEaiEDaCwnBjiawaCiiaiaCbiabCBjaDjibjiCsrBiiCgrBbiCaiCDaBiiDiaBbiDbiBgrAriBaiBDaAriBriAqiAnBfskpyBdwkozBcyBcjBhyBgzyCxwFxsfxkrxDfklpwsuzDdsloyDcwlojDciDcbBFwkmzDhwBEyDgyBEjDgjBazDizbfAnpstuybdknowtujbcsnoibcgnobbcabcDDFslmybhsDEwlmjbgwDEibgiDEbbgbBCyDayBCjbiyDajbijrpkvuwxxjjdArosvuijckrogvubjccroajcEroDjcCbFknmwttjjhkbEsnmijgsrqinmbjggbEajgabEDjgDDCwlljbawDCijiwbaiDCbjiibabjibBBjDDjbbjjjjjFArmsvtijEkrmgvtbjEcrmajEErmDjECjEBbCsnlijasbCgnlbjagrnbjaabCDjaDDBibDiDBbjbibDbjbbjCkrlgvsrjCcrlajCErlDjCCjCBbBgnkrjDgbBajDabBDjDDDArbBrjDrjBcrkqjBErknjBCjBBbAqjBqbAnjBnjAorkfjAmjAlb";
            codageMC[2] = codageMC[2] + "AfjAvApwkezAoyAojAqzBpskuyBowkujBoiBobAmyBqyAmjBqjDpkluwsxjDosluiDoglubDoaDoDBmwktjDqwBmiDqiBmbDqbAljBnjDrjbpAnustxiboknugtxbbocnuaboEnuDboCboBDmsltibqsDmgltbbqgnvbbqaDmDbqDBliDniBlbbriDnbbrbrukvxgxyrrucvxaruEvxDruCruBbmkntgtwrjqkbmcntajqcrvantDjqEbmCjqCbmBjqBDlglsrbngDlajrgbnaDlDjrabnDjrDBkrDlrbnrjrrrtcvwqrtEvwnrtCrtBblcnsqjncblEnsnjnErtnjnCblBjnBDkqblqDknjnqblnjnnrsovwfrsmrslbkonsfjlobkmjlmbkljllDkfbkvjlvrsersdbkejkubkdjktAeyAejAuwkhjAuiAubAdjAvjBuskxiBugkxbBuaBuDAtiBviAtbBvbDuklxgsyrDuclxaDuElxDDuCDuBBtgkwrDvglxrDvaBtDDvDAsrBtrDvrnxctyqnxEtynnxCnxBDtclwqbvcnxqlwnbvEDtCbvCDtBbvBBsqDtqBsnbvqDtnbvnvyoxzfvymvylnwotyfrxonwmrxmnwlrxlDsolwfbtoDsmjvobtmDsljvmbtljvlBsfDsvbtvjvvvyevydnwerwunwdrwtDsebsuDsdjtubstjttvyFnwFrwhDsFbshjsxAhiAhbAxgkirAxaAxDAgrAxrBxckyqBxEkynBxCBxBAwqBxqAwnBxnlyoszflymlylBwokyfDxolyvDxmBwlDxlAwfBwvDxvtzetzdlyenyulydnytBweDwuBwdbxuDwtbxttzFlyFnyhBwFDwhbwxAiqAinAyokjfAymAylAifAyvkzekzdAyeByuAydBytszp";
            ErrorCode   = 0;
            if (BarcodeText == "")
            {
                ErrorCode = 1; return("");
            }
            indexChaine = 1;
            QuelMode(ref codeASCII, BarcodeText, indexChaine, ref mode);
            do
            {
                liste.Set(1, indexListe, mode);
                while (liste.Get(1, indexListe) == mode)
                {
                    liste.Set(0, indexListe, liste.Get(0, indexListe) + 1);
                    indexChaine = indexChaine + 1;
                    if (indexChaine > BarcodeText.Length)
                    {
                        break;
                    }
                    QuelMode(ref codeASCII, BarcodeText, indexChaine, ref mode);
                }
                indexListe = indexListe + 1;
            }while (indexChaine <= BarcodeText.Length);
            for (int i = 0; i <= indexListe - 1; i++)
            {
                if (liste.Get(1, i) == 902)
                {
                    if (i == 0)
                    {
                        if (indexListe > 1)
                        {
                            if (liste.Get(1, i + 1) == 900)
                            {
                                if (liste.Get(0, i) < 8)
                                {
                                    liste.Set(1, i, 900);
                                }
                            }
                            else if (liste.Get(1, i + 1) == 901)
                            {
                                if (liste.Get(0, i) == 1)
                                {
                                    liste.Set(1, i, 901);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (i == indexListe - 1)
                        {
                            if (liste.Get(1, i - 1) == 900)
                            {
                                if (liste.Get(0, i) < 7)
                                {
                                    liste.Set(1, i, 900);
                                }
                            }
                            else if (liste.Get(1, i - 1) == 901)
                            {
                                if (liste.Get(0, i) == 1)
                                {
                                    liste.Set(1, i, 901);
                                }
                            }
                        }
                        else
                        {
                            if (liste.Get(1, i - 1) == 901 && liste.Get(1, i + 1) == 901)
                            {
                                if (liste.Get(0, i) < 4)
                                {
                                    liste.Set(1, i, 901);
                                }
                            }
                            else if (liste.Get(1, i - 1) == 900 && liste.Get(1, i + 1) == 901)
                            {
                                if (liste.Get(0, i) < 5)
                                {
                                    liste.Set(1, i, 900);
                                }
                            }
                            else if (liste.Get(1, i - 1) == 900 && liste.Get(1, i + 1) == 900)
                            {
                                if (liste.Get(0, i) < 8)
                                {
                                    liste.Set(1, i, 900);
                                }
                            }
                        }
                    }
                }
            }

            Regroupe(ref indexListe, ref liste, ref I, ref J);
            for (int i = 0; i <= indexListe - 1; i++)
            {
                if (liste.Get(1, i) == 900 && i > 0)
                {
                    if (i == indexListe - 1)
                    {
                        if (liste.Get(1, i - 1) == 901)
                        {
                            if (liste.Get(0, i) == 1)
                            {
                                liste.Set(1, i, 901);
                            }
                        }
                        else
                        {
                            if (liste.Get(1, i - 1) == 901 && liste.Get(1, i + 1) == 901)
                            {
                                if (liste.Get(0, i) < 5)
                                {
                                    liste.Set(1, i, 901);
                                }
                                else if ((liste.Get(1, i - 1) == 901 && liste.Get(1, i + 1) != 901) || (liste.Get(1, i - 1) != 901 && liste.Get(1, i + 1) == 901))
                                {
                                    if (liste.Get(0, i) < 3)
                                    {
                                        liste.Set(1, i, 901);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Regroupe(ref indexListe, ref liste, ref I, ref J);
            indexChaine = 1;
            for (int ii = 0; ii <= indexListe - 1; ii++)
            {
                switch (liste.Get(1, ii))
                {
                case 900:
                    listeT = new TwoDimensionalArray();
                    for (int indexListeT = 0; indexListeT <= liste.Get(0, ii) - 1; indexListeT++)
                    {
                        codeASCII = Encoding.GetEncoding(1250).GetBytes(BarcodeText.Substring(indexChaine + indexListeT - 1, 1))[0];
                        switch (codeASCII)
                        {
                        case 9:
                        {
                            listeT.Set(0, indexListeT, 12);
                            listeT.Set(1, indexListeT, 12);
                            break;
                        }

                        case 10:
                        {
                            listeT.Set(0, indexListeT, 8);
                            listeT.Set(1, indexListeT, 15);
                            break;
                        }

                        case 13:
                        {
                            listeT.Set(0, indexListeT, 12);
                            listeT.Set(1, indexListeT, 11);
                            break;
                        }

                        default:
                        {
                            listeT.Set(0, indexListeT, int.Parse(ASCII.Substring(codeASCII * 4 - 127 - 1, 2)));
                            listeT.Set(1, indexListeT, int.Parse(ASCII.Substring(codeASCII * 4 - 125 - 1, 2)));
                        }
                        break;
                        }
                    }
                    curTable = 1;
                    chaineT  = "";
                    for (int j = 0; j <= liste.Get(0, ii) - 1; j++)
                    {
                        if ((listeT.Get(0, j) & curTable) > 0)
                        {
                            chaineT = chaineT + listeT.Get(1, j).ToString("00");
                        }
                        else
                        {
                            flag = false;
                            if (j == liste.Get(0, ii) - 1)
                            {
                                flag = true;
                            }
                            else
                            {
                                if ((listeT.Get(0, j) & listeT.Get(0, j + 1)) == 0)
                                {
                                    flag = true;
                                }
                            }
                            if (flag)
                            {
                                if ((listeT.Get(0, j) & 1) > 0 && curTable == 2)
                                {
                                    chaineT = chaineT + "27" + listeT.Get(1, j).ToString("00");
                                }
                                else if ((listeT.Get(0, j) & 8) > 0)
                                {
                                    chaineT = chaineT + "29" + listeT.Get(1, j).ToString("00");
                                }
                                else
                                {
                                    flag = false;
                                }
                            }

                            if (!flag)
                            {
                                if (j == liste.Get(0, ii) - 1)
                                {
                                    newTable = listeT.Get(0, j);
                                }
                                else
                                {
                                    newTable = ((listeT.Get(0, j) & listeT.Get(0, j + 1)) == 0) ? listeT.Get(0, j) : listeT.Get(0, j) & listeT.Get(0, j + 1);
                                }

                                if (newTable == 3 || newTable == 5 || newTable == 7 || newTable == 9 || newTable == 11 || newTable == 13 || newTable == 15)
                                {
                                    newTable = 1;
                                }
                                if (newTable == 6 || newTable == 10 || newTable == 14)
                                {
                                    newTable = 2;
                                }
                                if (newTable == 12)
                                {
                                    newTable = 4;
                                }

                                switch (curTable)
                                {
                                case 1:
                                    switch (newTable)
                                    {
                                    case 2:
                                        chaineT = chaineT + "27";
                                        break;

                                    case 4:
                                        chaineT = chaineT + "28";
                                        break;

                                    case 8:
                                        chaineT = chaineT + "2825";
                                        break;
                                    }
                                    break;

                                case 2:
                                    switch (newTable)
                                    {
                                    case 1:
                                        chaineT = chaineT + "2828";
                                        break;

                                    case 4:
                                        chaineT = chaineT + "28";
                                        break;

                                    case 8:
                                        chaineT = chaineT + "2825";
                                        break;
                                    }
                                    break;

                                case 4:
                                    switch (newTable)
                                    {
                                    case 1:
                                        chaineT = chaineT + "28";
                                        break;

                                    case 2:
                                        chaineT = chaineT + "27";
                                        break;

                                    case 8:
                                        chaineT = chaineT + "25";
                                        break;
                                    }
                                    break;

                                case 8:
                                    switch (newTable)
                                    {
                                    case 1:
                                        chaineT = chaineT + "29";
                                        break;

                                    case 2:
                                        chaineT = chaineT + "2927";
                                        break;

                                    case 4:
                                        chaineT = chaineT + "2928";
                                        break;
                                    }
                                    break;
                                }
                                curTable = newTable;
                                chaineT  = chaineT + listeT.Get(1, j).ToString("00");
                            }
                        }
                    }
                    if (chaineT.Length % 4 > 0)
                    {
                        chaineT = chaineT + "29";
                    }
                    if (ii > 0)
                    {
                        chaineMC = chaineMC + "900";
                    }
                    for (int j = 1; j <= chaineT.Length; j += 4)
                    {
                        chaineMC = chaineMC + (int.Parse(chaineT.Substring(j - 1, 2)) * 30 + int.Parse(chaineT.Substring(j + 2 - 1, 2))).ToString("000");
                    }
                    break;

                case 901:
                    if (liste.Get(0, ii) == 1)
                    {
                        chaineMC = chaineMC + "913" + (Encoding.GetEncoding(1250).GetBytes(BarcodeText.Substring(indexChaine - 1, 1))[0]).ToString("000");
                    }
                    else
                    {
                        if (liste.Get(0, ii) % 6 == 0)
                        {
                            chaineMC = chaineMC + "924";
                        }
                        else
                        {
                            chaineMC = chaineMC + "901";
                        }
                        J = 0;
                        while (J < liste.Get(0, ii))
                        {
                            longueur = liste.Get(0, ii) - J;
                            if (longueur >= 6)
                            {
                                longueur = 6;
                                total    = 0;
                                for (int k = 0; k <= longueur - 1; k++)
                                {
                                    total = total + (Encoding.GetEncoding(1250).GetBytes(BarcodeText.Substring(indexChaine + J + k - 1, 1))[0] * (Int64)Math.Pow(256, (longueur - 1 - k)));
                                }
                                chaineMod = String.Format(total.ToString(), "general number");
                                dummy     = "";
                                do
                                {
                                    diviseur = 900;
                                    Modulo(ref chaineMult, ref nombre, ref chaineMod, ref diviseur);
                                    dummy     = diviseur.ToString("000") + dummy;
                                    chaineMod = chaineMult;
                                }while (chaineMult != "");
                                chaineMC = chaineMC + dummy;
                            }
                            else
                            {
                                for (int k = 0; k <= longueur - 1; k++)
                                {
                                    chaineMC = chaineMC + (Encoding.GetEncoding(1250).GetBytes(BarcodeText.Substring(indexChaine + J + k - 1, 1))[0]).ToString("000");
                                }
                            }
                            J = J + longueur;
                        }
                    }
                    break;

                case 902:
                    chaineMC = chaineMC + "902";
                    J        = 0;
                    while (J < liste.Get(0, ii))
                    {
                        longueur = liste.Get(0, ii) - J;
                        if (longueur > 44)
                        {
                            longueur = 44;
                        }
                        chaineMod = "1" + BarcodeText.Substring(indexChaine + J - 1, longueur);
                        dummy     = "";
                        do
                        {
                            diviseur = 900;
                            Modulo(ref chaineMult, ref nombre, ref chaineMod, ref diviseur);
                            dummy     = diviseur.ToString("000") + dummy;
                            chaineMod = chaineMult;
                        }while (chaineMult != "");
                        chaineMC = chaineMC + dummy;
                        J        = J + longueur;
                    }
                    break;
                }
                indexChaine = indexChaine + liste.Get(0, ii);
            }
            longueur = chaineMC.Length / 3;
            if (ErrorCorrectionLevel < 0)
            {
                if (longueur < 41)
                {
                    ErrorCorrectionLevel = 2;
                }
                else if (longueur < 161)
                {
                    ErrorCorrectionLevel = 3;
                }
                else if (longueur < 321)
                {
                    ErrorCorrectionLevel = 4;
                }
                else
                {
                    ErrorCorrectionLevel = 5;
                }
            }
            longueur = longueur + 1 + (int)Math.Pow(2, (ErrorCorrectionLevel + 1));
            if (Columns > 30)
            {
                Columns = 30;
            }
            if (Columns < 1)
            {
                Columns = (int)((Math.Sqrt(204 * longueur + 4761) - 69) / (34 / 1.3));
                if (Columns == 0)
                {
                    Columns = 1;
                }
            }
            while (ErrorCorrectionLevel > 0)
            {
                longueur = chaineMC.Length / 3 + 1 + (int)Math.Pow(2, (ErrorCorrectionLevel + 1));
                longueur = ((int)(longueur / Columns) + (longueur % Columns > 0 ? 1 : 0)) * Columns;
                if (longueur < 929)
                {
                    break;
                }
                ErrorCorrectionLevel = ErrorCorrectionLevel - 1;
                ErrorCode            = 10;
            }
            if (longueur > 928)
            {
                ErrorCode = 2;
                return("");
            }
            if (longueur / Columns > 90)
            {
                ErrorCode = 3;
                return("");
            }
            longueur = chaineMC.Length / 3 + 1 + (int)Math.Pow(2, (ErrorCorrectionLevel + 1));
            I        = 0;
            if ((int)(longueur / Columns) < 3)
            {
                I = Columns * 3 - longueur;
            }
            else
            {
                if (longueur % Columns > 0)
                {
                    I = Columns - (longueur % Columns);
                }
            }
            while (I > 0)
            {
                chaineMC = chaineMC + "900";
                I        = I - 1;
            }
            chaineMC     = (chaineMC.Length / 3 + 1).ToString("000") + chaineMC;
            longueur     = chaineMC.Length / 3;
            K            = (int)Math.Pow(2, (ErrorCorrectionLevel + 1));
            MCcorrection = new OneDimensionalArray();
            total        = 0;
            for (int iii = 0; iii <= longueur - 1; iii++)
            {
                total = (int.Parse(chaineMC.Substring(iii * 3 + 1 - 1, 3)) + MCcorrection.Get(K - 1)) % 929;
                for (int j = K - 1; j >= 0; j--)
                {
                    if (j == 0)
                    {
                        MCcorrection.Set(j, (929 - (total * Int64.Parse(coefRS[ErrorCorrectionLevel].Substring(j * 3 + 1 - 1, 3))) % 929) % 929);
                    }
                    else
                    {
                        MCcorrection.Set(j, (MCcorrection.Get(j - 1) + 929 - (total * int.Parse(coefRS[ErrorCorrectionLevel].Substring(j * 3 + 1 - 1, 3))) % 929) % 929);
                    }
                }
            }
            for (int j = 0; j <= K - 1; j++)
            {
                if (MCcorrection.Get(j) != 0)
                {
                    MCcorrection.Set(j, 929 - MCcorrection.Get(j));
                }
            }

            for (int ii = K - 1; ii >= 0; ii--)
            {
                chaineMC = chaineMC + MCcorrection.Get(ii).ToString("000");
            }
            c1 = (int)((chaineMC.Length / 3 / Columns - 1) / 3);
            c2 = ErrorCorrectionLevel * 3 + (chaineMC.Length / 3 / Columns - 1) % 3;
            c3 = Columns - 1;
            for (int ii = 0; ii <= chaineMC.Length / 3 / Columns - 1; ii++)
            {
                dummy = chaineMC.Substring(ii * Columns * 3 + 1 - 1, Columns * 3);
                K     = (int)(ii / 3) * 30;
                switch (ii % 3)
                {
                case 0:
                    dummy = (K + c1).ToString("000") + dummy + (K + c3).ToString("000");
                    break;

                case 1:
                    dummy = (K + c2).ToString("000") + dummy + (K + c1).ToString("000");
                    break;

                case 2:
                    dummy = (K + c3).ToString("000") + dummy + (K + c2).ToString("000");
                    break;
                }
                pdf417 = pdf417 + "+*";
                for (int j = 0; j <= dummy.Length / 3 - 1; j++)
                {
                    pdf417 = pdf417 + codageMC[ii % 3].Substring(int.Parse(dummy.Substring(j * 3 + 1 - 1, 3)) * 3 + 1 - 1, 3) + "*";
                }
                pdf417 = pdf417 + "-" + "|";
            }
            return(pdf417);
        }
Exemple #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Algorithms!");
            #region Merge Sorting
            int[] array = { 11, 13, 7, 12, 16, 9, 24, 5, 10, 3 };
            MergeSort.MergeSortWithTwoArray();
            MergeSort.RecursiveMergeSort(array, 0, array.Length - 1);
            Console.WriteLine($"Recursive Merge Sort : [{string.Join(",", array)}]");
            #endregion

            #region Binary Search
            Console.WriteLine();
            Console.WriteLine("Binary Search");
            int[] binarySearchArray = new int[] { 2, 8, 12, 22, 35, 88, 100 };
            Console.WriteLine($"The index of given element in a Binary Search is : {BinarySearch.BinarySearch.BinarySearchAlgorithm(binarySearchArray, binarySearchArray.Length, 88)}");
            #endregion

            #region Bubble Sort
            Console.WriteLine();
            Console.WriteLine("Bubble Sort!");
            int[] bubbleSortArray = new int[] { 10, 8, 12, 22, 100, 88, 101, 4 };
            BubbleSort.BubbleSort.BubbleSortAlgorithm(bubbleSortArray, bubbleSortArray.Length);
            #endregion

            #region Count Sort
            Console.WriteLine();
            Console.WriteLine("Count Sort!");
            CountSort.CountSort.CountSortAlgoritm();
            #endregion

            #region Fibonacci Series
            Console.WriteLine();
            Console.WriteLine("Fibonacci Series!");
            FibonacciSeries.FibonacciSeries.FibonacciSeriesAlgorithm();
            #endregion

            #region Factorial
            Console.WriteLine();
            Console.WriteLine("Factorial !!");
            Factorial.Factorial.FactorialMethod(5);
            #endregion

            #region Recursion
            Console.WriteLine("Recursion Ascending & Descending Sorting");
            Recursion.Recursion.RecursionSort(3);
            #endregion

            #region Reverse a String
            Console.WriteLine();
            Console.WriteLine("Reverse a String !!");
            Basics.ReverseAString.ReverseString("rajeesh");
            #endregion

            #region Missing number problem in an array
            MissingNumberProblem.FindMissingNumberInAnArray();
            #endregion


            #region MinAndMax Array Problems
            Console.WriteLine("Minimum and Maximum Problems in an Arrays!");
            int[] arrayElement = { 10, 88, 1, 55, 48 };
            MinAndMax.MinAndMaxSumInAnArray(arrayElement);
            int[] arrMinAndMax = { 3, 10, 2, 5, 7, 10 };
            MinAndMax.FindMaxValueCountInAnArray(arrMinAndMax);
            #endregion

            Console.WriteLine();
            Console.WriteLine("Multidimensional Arrays!");
            #region Multidimensional Array
            TwoDimensionalArray.ReplaceDiagonalWithStar();
            Console.WriteLine("Matrix Rotation");
            TwoDimensionalArray.NinetyDegreeMatrixRotation();
            #endregion



            Console.ReadLine();
        }
Exemple #16
0
        public static TBase[] FromTwoDimensionalArray <TBase, T>(
            this Dictionary <string, T[, ]> items,
            Dictionary <string, Action <TBase, T[]> > setters,
            TwoDimensionalArray dimensionality = TwoDimensionalArray.None)
            where TBase : new()
        {
            // This code is covered by unit tests Acoustics.Test - change the unit tests before you change the class!
            Contract.Requires(items != null);
            Contract.Requires(setters != null);

            // assume all matrices contain the same number of elements
            int major     = dimensionality == TwoDimensionalArray.None ? 0 : 1;
            int minor     = major == 1 ? 0 : 1;
            var itemCount = items.First().Value.GetLength(major);

            int keyCount = setters.Keys.Count;
            var results  = new TBase[itemCount];

            // initialize all values
            for (int index = 0; index < results.Length; index++)
            {
                results[index] = new TBase();
            }

            Parallel.ForEach(
                setters,
                (kvp, state, index) =>
            {
                var key    = kvp.Key;
                var setter = kvp.Value;

                var matrix = items[key];
                for (int i = 0; i < itemCount; i++)
                {
                    var lineLength = matrix.GetLength(minor);
                    T[] line       = new T[lineLength];

                    for (int j = 0; j < lineLength; j++)
                    {
                        switch (dimensionality)
                        {
                        case TwoDimensionalArray.None:
                            line[j] = matrix[i, j];
                            break;

                        case TwoDimensionalArray.Transpose:
                            line[j] = matrix[j, i];
                            break;

                        case TwoDimensionalArray.Rotate90ClockWise:
                            line[j] = matrix[lineLength - 1 - j, i];
                            break;

                        default:
                            throw new NotImplementedException("Dimensionality not supported");
                        }
                    }

                    // set the line (row or column) to the instance
                    setter(results[i], line);
                }
            });

            return(results);
        }
 public static T[,] ReadMatrixFromCsv <T>(FileInfo source, TwoDimensionalArray transform = TwoDimensionalArray.None)
 {
     return(ReadMatrixFromCsv <T>(source.ToFileEntry(), transform));
 }