Example #1
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(h, w) = inputStream.ReadValue <int, int>();
            var panels = InitializeMap(inputStream, h, w);
            var start  = panels[0][0];
            var goal   = panels[10][0];

            const int Inf    = 1 << 28;
            var       counts = new int[h, w, 11].SetAll((i, j, k) => Inf);

            counts[start.row, start.column, 0] = 0;

            if (panels.Any(l => l.Count == 0))
            {
                yield return(-1);

                yield break;
            }

            for (int current = 0; current < 10; current++)
            {
                foreach (var begin in panels[current])
                {
                    foreach (var end in panels[current + 1])
                    {
                        var distance = Math.Abs(begin.row - end.row) + Math.Abs(begin.column - end.column);
                        AlgorithmHelpers.UpdateWhenSmall(ref counts[end.row, end.column, current + 1], counts[begin.row, begin.column, current] + distance);
                    }
                }
            }

            yield return(counts[goal.row, goal.column, 10]);
        }
Example #2
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(_, maxX) = inputStream.ReadValue <int, long>();
            var a = inputStream.ReadLongArray();

            var       fMax        = new long[41, 2].SetAll((_, __) => long.MinValue);
            const int EqualOrOver = 0;
            const int Under       = 1;

            fMax[40, 0] = 0;
            for (int digit = 39; digit >= 0; digit--)
            {
                long mask = 1L << digit;
                var  ones = a.Count(ai => (ai & mask) > 0);

                if ((maxX & mask) > 0)
                {
                    // Eq -> Eq (di == 1)
                    AlgorithmHelpers.UpdateWhenLarge(ref fMax[digit, EqualOrOver], fMax[digit + 1, EqualOrOver] + mask * (a.Length - ones));
                    // Eq -> Under (di == 0)
                    AlgorithmHelpers.UpdateWhenLarge(ref fMax[digit, Under], fMax[digit + 1, EqualOrOver] + mask * ones);
                }
                else
                {
                    // Eq -> Eq (di == 0)
                    AlgorithmHelpers.UpdateWhenLarge(ref fMax[digit, EqualOrOver], fMax[digit + 1, EqualOrOver] + mask * ones);
                }

                // Under -> Under
                AlgorithmHelpers.UpdateWhenLarge(ref fMax[digit, Under], fMax[digit + 1, Under] + mask * ones);
                AlgorithmHelpers.UpdateWhenLarge(ref fMax[digit, Under], fMax[digit + 1, Under] + mask * (a.Length - ones));
            }

            yield return(Math.Max(fMax[0, EqualOrOver], fMax[0, Under]));
        }
Example #3
0
        public int CalculateClasses()
        {
            List <int> nClasses = new List <int>();

            for (double i = thetavalues.Item1; i < thetavalues.Item2; i += thetaStepNum)
            {
                for (int z = 0; z < s; z++)
                {
                    double[][] rndata  = AlgorithmHelpers.RandomizeArray(data);
                    int        Classes = 0;
                    for (int j = 0; j < rndata.Length - 1; ++j)
                    {
                        double dist = Distance.Euclidean(rndata[j], rndata[j + 1]);
                        if (dist > i)
                        {
                            Classes += 1;
                        }
                    }
                    nClasses.Add(Classes);
                }
            }

            var most = nClasses
                       .GroupBy(x => x)
                       .OrderByDescending(grp => grp.Count())
                       .Select(grp => grp.Key)
                       .First();

            return(most);
        }
Example #4
0
        //Method that updates the chart with the data vectors
        public void ShowTrainingData(Double[][] classA, Double[][] classB)
        {
            //create data series from the vectors
            var class1 = AlgorithmHelpers.JaggedToMD(classA);
            var class2 = AlgorithmHelpers.JaggedToMD(classB);

            //Compute the minimum and maximum numbers for the X axis
            var maxX = classA.Max(0)[0] > classB.Max(0)[0] ? classA.Max(0)[0] : classB.Max(0)[0];
            var minX = classA.Min(0)[0] < classB.Min(0)[0] ? classA.Min(0)[0] : classB.Min(0)[0];

            //Update the range of the X axis with the max and the min
            perceChart.RangeX = new Range((float)minX, (float)maxX);
            nnChart.RangeX    = new Range((float)minX, (float)maxX);
            lsChart.RangeX    = new Range((float)minX, (float)maxX);

            //Update the Perceptron chart with the loaded data
            perceChart.UpdateDataSeries("class1", class1);
            perceChart.UpdateDataSeries("class2", class2);
            //Update the BackPropagation chart with the loaded data
            nnChart.UpdateDataSeries("class1", class1);
            nnChart.UpdateDataSeries("class2", class2);
            //Update the LS chart
            lsChart.UpdateDataSeries("class1", class1);
            lsChart.UpdateDataSeries("class2", class2);
        }
Example #5
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(height, width, itemCount) = inputStream.ReadValue <int, int, int>();
            var       items   = new long[height, width];
            const int MaxPick = 3;

            for (int i = 0; i < itemCount; i++)
            {
                var(r, c, v) = inputStream.ReadValue <int, int, int>();
                r--;
                c--;
                items[r, c] = v;
            }

            var dp = new long[height, width, 4];

            dp[0, 0, 1] = items[0, 0];

            for (int row = 0; row < height; row++)
            {
                for (int column = 0; column < width; column++)
                {
                    if (row + 1 < height)
                    {
                        for (int currentPicked = 0; currentPicked <= MaxPick; currentPicked++)
                        {
                            for (int nextPicked = 0; nextPicked <= 1; nextPicked++)
                            {
                                AlgorithmHelpers.UpdateWhenLarge(ref dp[row + 1, column, nextPicked], dp[row, column, currentPicked] + items[row + 1, column] * nextPicked);
                            }
                        }
                    }

                    if (column + 1 < width)
                    {
                        for (int currentPicked = 0; currentPicked <= MaxPick; currentPicked++)
                        {
                            AlgorithmHelpers.UpdateWhenLarge(ref dp[row, column + 1, currentPicked], dp[row, column, currentPicked]);

                            if (currentPicked < MaxPick)
                            {
                                AlgorithmHelpers.UpdateWhenLarge(ref dp[row, column + 1, currentPicked + 1], dp[row, column, currentPicked] + items[row, column + 1]);
                            }
                        }
                    }
                }
            }

            long max = 0;

            for (int picked = 0; picked <= MaxPick; picked++)
            {
                AlgorithmHelpers.UpdateWhenLarge(ref max, dp[height - 1, width - 1, picked]);
            }

            yield return(max);
        }
Example #6
0
 void Update(int[][] distances, int from, int to, int d)
 {
     for (int i = 0; i < distances.Length; i++)
     {
         for (int j = 0; j < distances[i].Length; j++)
         {
             AlgorithmHelpers.UpdateWhenSmall(ref distances[i][j], distances[i][from] + d + distances[to][j]);
             AlgorithmHelpers.UpdateWhenSmall(ref distances[i][j], distances[i][to] + d + distances[from][j]);
         }
     }
 }
Example #7
0
 void WarshallFloyd(int[][] distances)
 {
     for (int k = 0; k < distances.Length; k++)
     {
         for (int i = 0; i < distances.Length; i++)
         {
             for (int j = 0; j < distances[i].Length; j++)
             {
                 AlgorithmHelpers.UpdateWhenSmall(ref distances[i][j], distances[i][k] + distances[k][j]);
             }
         }
     }
 }
Example #8
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(n, capacity) = inputStream.ReadValue <int, int>();
            var items = new Item[n];

            for (int i = 0; i < items.Length; i++)
            {
                var(w, v) = inputStream.ReadValue <int, int>();
                items[i]  = new Item(w, v);
            }
            var baseW = items[0].Weight;

            for (int i = 0; i < items.Length; i++)
            {
                items[i] = new Item(items[i].Weight - baseW, items[i].Value);
            }

            const int maxCapacity = 300;
            var       maxValues   = new int[n + 1, n + 1, maxCapacity];

            for (int i = 0; i < n; i++)
            {
                for (int selected = 0; selected <= i; selected++)
                {
                    for (int w = 0; w < maxCapacity; w++)
                    {
                        AlgorithmHelpers.UpdateWhenLarge(ref maxValues[i + 1, selected, w], maxValues[i, selected, w]);

                        if (w + items[i].Weight < maxCapacity)
                        {
                            AlgorithmHelpers.UpdateWhenLarge(ref maxValues[i + 1, selected + 1, w + items[i].Weight], maxValues[i, selected, w] + items[i].Value);
                        }
                    }
                }
            }

            var max = int.MinValue;

            for (int selected = 0; selected <= n; selected++)
            {
                for (int w = 0; w < maxCapacity; w++)
                {
                    if ((long)baseW * selected + w <= capacity)
                    {
                        max = Math.Max(max, maxValues[n, selected, w]);
                    }
                }
            }

            yield return(max);
        }
Example #9
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var maxWidth = inputStream.ReadInt();

            var(screenShotCount, maxScreenShotCount) = inputStream.ReadValue <int, int>();

            var screenShots = new ScreenShot[screenShotCount];

            for (int i = 0; i < screenShotCount; i++)
            {
                var(a, b)      = inputStream.ReadValue <int, int>();
                screenShots[i] = new ScreenShot(a, b);
            }

            var importantness = new int[screenShotCount + 1, maxScreenShotCount + 1, maxWidth + 1];

            for (int ss = 0; ss < screenShotCount; ss++)
            {
                for (int taken = 0; taken <= maxScreenShotCount; taken++)
                {
                    for (int w = 0; w <= maxWidth; w++)
                    {
                        AlgorithmHelpers.UpdateWhenLarge(ref importantness[ss + 1, taken, w], importantness[ss, taken, w]);

                        var nextWidth = w + screenShots[ss].Width;
                        if (nextWidth <= maxWidth && taken < maxScreenShotCount)
                        {
                            AlgorithmHelpers.UpdateWhenLarge(ref importantness[ss + 1, taken + 1, nextWidth], importantness[ss, taken, w] + screenShots[ss].Importantness);
                        }
                    }
                }
            }

            var maxImportantness = 0;

            for (int ss = 0; ss <= maxScreenShotCount; ss++)
            {
                for (int w = 0; w <= maxWidth; w++)
                {
                    AlgorithmHelpers.UpdateWhenLarge(ref maxImportantness, importantness[screenShotCount, ss, w]);
                }
            }

            yield return(maxImportantness);
        }
Example #10
0
        void Initialize(int halfN)
        {
            _values = new int[halfN, maxCapacity + 1];

            for (int i = 1; i < halfN; i++)
            {
                for (int w = 0; w <= maxCapacity; w++)
                {
                    AlgorithmHelpers.UpdateWhenLarge(ref _values[i, w], _values[i >> 1, w]);

                    var nextWeight = w + _goods[i].Weight;
                    if (nextWeight <= maxCapacity)
                    {
                        AlgorithmHelpers.UpdateWhenLarge(ref _values[i, nextWeight], _values[i >> 1, w] + _goods[i].Value);
                    }
                }
            }
        }
Example #11
0
        public override ConfusionMatrix Execute()
        {
            //Create an network with one layer and one neuron in that layer
            var network = new ActivationNetwork(new ThresholdFunction(), 3, 1);

            //Bind the reference of the neuron
            var neuron = network.Layers[0].Neurons[0] as ActivationNeuron;

            //Create the Perceptron learning algorithm
            //Library perceptron implements a single layer linear classifier
            var teacher = new PerceptronLearning(network);

            teacher.LearningRate = 0.1;

            //Enrich the dimensions of the vectors, padding 1 to the end
            var richTraining = AlgorithmHelpers.PaddDimension(trainingSet);
            var richTesting  = AlgorithmHelpers.PaddDimension(testSet);

            //Training the network until the error is small enough
            //or 500 hundred iterations have been computed
            int epochs = 0;

            while (true)
            {
                double error = teacher.RunEpoch(richTraining, trainingOutput);/// trainingSet.Length;
                ++epochs;
                if (error < 0.025 * trainingSet.Length || epochs == 500)
                {
                    break;
                }
            }

            var predicted = richTesting
                            .Select(x => neuron.Compute(x))
                            .Select(x => Convert.ToInt32(x))
                            .ToArray();


            //Create a confusion matrix with the calculated parameters
            ConfusionMatrix cmatrix = new ConfusionMatrix(predicted, expected, POSITIVE, NEGATIVE);

            OnAlgorithmEnded(Enumerable.Repeat(neuron, 1), cmatrix);
            return(cmatrix);
        }
Example #12
0
 int GetValueAt(int index, int capacity)
 {
     if (index < _values.GetLength(0))
     {
         return(_values[index, capacity]);
     }
     else
     {
         var nextIndex = index >> 1;
         var value     = 0;
         AlgorithmHelpers.UpdateWhenLarge(ref value, GetValueAt(nextIndex, capacity));
         var nextCapacity = capacity - _goods[index].Weight;
         if (nextCapacity >= 0)
         {
             AlgorithmHelpers.UpdateWhenLarge(ref value, GetValueAt(nextIndex, nextCapacity) + _goods[index].Value);
         }
         return(value);
     }
 }
Example #13
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(hurdlesCount, length) = inputStream.ReadValue <int, int>();
            var hardles = inputStream.ReadIntArray();

            var(t1, t2, t3) = inputStream.ReadValue <int, int, int>();

            var fastestTime = Enumerable.Repeat(1L << 50, length + 1).ToArray();

            fastestTime[0] = 0;

            for (int i = 0; i < length; i++)
            {
                var loss = Array.BinarySearch(hardles, i) >= 0 ? t3 : 0;

                // 走る
                AlgorithmHelpers.UpdateWhenSmall(ref fastestTime[i + 1], fastestTime[i] + t1 + loss);

                // 1飛ぶ
                if (i + 2 <= length)
                {
                    AlgorithmHelpers.UpdateWhenSmall(ref fastestTime[i + 2], fastestTime[i] + t1 + t2 + loss);
                }
                else
                {
                    AlgorithmHelpers.UpdateWhenSmall(ref fastestTime[i + 1], fastestTime[i] + (t1 + t2) / 2 + loss);
                }

                // 3飛ぶ
                if (i + 4 <= length)
                {
                    AlgorithmHelpers.UpdateWhenSmall(ref fastestTime[i + 4], fastestTime[i] + t1 + t2 * 3 + loss);
                }
                else
                {
                    var toJumpDoubled = length * 2 - i * 2 - 1;
                    AlgorithmHelpers.UpdateWhenSmall(ref fastestTime[length], fastestTime[i] + (t1 + toJumpDoubled * t2) / 2 + loss);
                }
            }

            yield return(fastestTime[length]);
        }
Example #14
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(jankenCount, restriction) = inputStream.ReadValue <int, int>();
            var winPoints = inputStream.ReadIntArray();
            var pattern   = inputStream.ReadLine().Select(c => ToHand(c)).ToArray();

            var totalPoints = 0;

            for (int mod = 0; mod < restriction; mod++)
            {
                var subJankens = (jankenCount - mod + restriction - 1) / restriction;
                var points     = new int[subJankens + 1, 3];

                for (int round = 0; round < subJankens; round++)
                {
                    var index = round * restriction + mod;
                    for (int before = Rock; before <= Paper; before++)
                    {
                        for (int current = Rock; current <= Paper; current++)
                        {
                            if (before != current)
                            {
                                AlgorithmHelpers.UpdateWhenLarge(ref points[round + 1, current],
                                                                 points[round, before] + (Wins(current, pattern[index]) ? winPoints[current] : 0));
                            }
                        }
                    }
                }

                var total = 0;

                for (int hand = Rock; hand <= Paper; hand++)
                {
                    total = Math.Max(total, points[subJankens, hand]);
                }

                totalPoints += total;
            }

            yield return(totalPoints);
        }
Example #15
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var n       = inputStream.ReadInt();
            var infants = inputStream.ReadIntArray().Select((a, index) => new Infant(a, index)).ToArray();

            Array.Sort(infants);
            Array.Reverse(infants);

            var happiness = new long[n + 1, n + 1];     // [left人数, right人数]

            for (int i = 1; i <= n; i++)
            {
                var infant = infants[i - 1];

                for (int leftCount = 0; leftCount <= i; leftCount++)    // left 0人~i人
                {
                    var rightCount = i - leftCount;

                    // 左に配置
                    if (leftCount > 0)
                    {
                        AlgorithmHelpers.UpdateWhenLarge(ref happiness[leftCount, rightCount], happiness[leftCount - 1, rightCount] + infant.GetHappiness(leftCount - 1));  // leftCount=1のとき座標は0
                    }
                    // 右に配置
                    if (rightCount > 0)
                    {
                        AlgorithmHelpers.UpdateWhenLarge(ref happiness[leftCount, rightCount], happiness[leftCount, rightCount - 1] + infant.GetHappiness(infants.Length - rightCount));    // rightCount=1のとき座標はn-1
                    }
                }
            }

            long max = 0;

            for (int leftCount = 0; leftCount <= n; leftCount++)
            {
                var rightCount = n - leftCount;
                AlgorithmHelpers.UpdateWhenLarge(ref max, happiness[leftCount, rightCount]);
            }

            yield return(max);
        }
Example #16
0
        public override ConfusionMatrix Execute()
        {
            //Create a knn classifer with 2 classes
            var knn = new KNearestNeighbors(k: k,
                                            classes: 2,
                                            inputs: trainingSet,
                                            outputs: trainingOutput);

            //Map the classifier over the test set
            //This wil return an array where index i is the classificatioon of the i-th vector
            //of the testSet
            var predicted = AlgorithmHelpers
                            .MergeArrays(trainingSet, testSet)
                            .Select(x => knn.Compute(x))
                            .ToArray();

            //Create a new confusion matrix with the calculated parameters
            var cmatrix = new ConfusionMatrix(predicted, AlgorithmHelpers.MergeArrays(trainingOutput, expected), POSITIVE, NEGATIVE);

            return(cmatrix);
        }
Example #17
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            _ = inputStream.ReadInt();
            var        s            = inputStream.ReadLine();
            var        reverseCosts = inputStream.ReadLongArray();
            var        eraseCosts   = inputStream.ReadLongArray();
            const long Inf          = 1L << 60;

            var costs = new long[s.Length + 1, s.Length + 1].SetAll((i, j) => Inf);

            costs[0, 0] = 0;

            for (int cursor = 0; cursor < s.Length; cursor++)
            {
                for (int height = 0; height < s.Length; height++)
                {
                    var bracket = s[cursor] == '(' ? 1 : -1;

                    // do nothing
                    if (height + bracket >= 0)
                    {
                        AlgorithmHelpers.UpdateWhenSmall(ref costs[cursor + 1, height + bracket], costs[cursor, height]);
                    }

                    // reverse
                    if (height - bracket >= 0)
                    {
                        AlgorithmHelpers.UpdateWhenSmall(ref costs[cursor + 1, height - bracket], costs[cursor, height] + reverseCosts[cursor]);
                    }

                    // erase
                    AlgorithmHelpers.UpdateWhenSmall(ref costs[cursor + 1, height], costs[cursor, height] + eraseCosts[cursor]);
                }
            }

            yield return(costs[s.Length, 0]);
        }
Example #18
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var(dishKinds, lastOrder) = inputStream.ReadValue <int, int>();
            var dishes = new Dish[dishKinds];

            for (int i = 0; i < dishKinds; i++)
            {
                var(a, b) = inputStream.ReadValue <int, int>();
                dishes[i] = new Dish(a, b);
            }

            Array.Sort(dishes);
            var maxMinutes = lastOrder + 3000;

            var happinesses = new int[dishKinds + 1, maxMinutes + 1];

            for (int i = 0; i < dishes.Length; i++)
            {
                for (int minutes = 0; minutes <= maxMinutes; minutes++)
                {
                    AlgorithmHelpers.UpdateWhenLarge(ref happinesses[i + 1, minutes], happinesses[i, minutes]);

                    if (minutes < lastOrder)
                    {
                        AlgorithmHelpers.UpdateWhenLarge(ref happinesses[i + 1, minutes + dishes[i].NeedToEat], happinesses[i, minutes] + dishes[i].Deliciousness);
                    }
                }
            }

            var max = 0;

            for (int minutes = 0; minutes <= maxMinutes; minutes++)
            {
                AlgorithmHelpers.UpdateWhenLarge(ref max, happinesses[dishKinds, minutes]);
            }
            yield return(max);
        }
Example #19
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var n       = inputStream.ReadInt();
            var infants = inputStream.ReadIntArray().Select((a, index) => new Infant(a, index)).ToArray();

            Array.Sort(infants);
            Array.Reverse(infants);

            var dpStatus = new DPStatus[n + 1, 2];     // left of right

            dpStatus[0, 0] = new DPStatus(0, 0, infants.Length - 1);
            dpStatus[0, 1] = new DPStatus(0, 0, infants.Length - 1);


            for (int i = 0; i < n; i++)
            {
                var infant = infants[i];

                var beforeLeft  = dpStatus[i, 0];
                var beforeRight = dpStatus[i, 1];

                // 左に並べるとき
                AlgorithmHelpers.UpdateWhenLarge(ref dpStatus[i + 1, 0],
                                                 new DPStatus(beforeLeft.Happiness + infant.Briskness * Math.Abs(infant.Position - beforeLeft.LeftIndex), beforeLeft.LeftIndex + 1, beforeLeft.RightIndex));
                AlgorithmHelpers.UpdateWhenLarge(ref dpStatus[i + 1, 0],
                                                 new DPStatus(beforeRight.Happiness + infant.Briskness * Math.Abs(infant.Position - beforeRight.LeftIndex), beforeRight.LeftIndex + 1, beforeRight.RightIndex));


                // 右に並べるとき
                AlgorithmHelpers.UpdateWhenLarge(ref dpStatus[i + 1, 1],
                                                 new DPStatus(beforeLeft.Happiness + infant.Briskness * Math.Abs(infant.Position - beforeLeft.RightIndex), beforeLeft.LeftIndex, beforeLeft.RightIndex - 1));
                AlgorithmHelpers.UpdateWhenLarge(ref dpStatus[i + 1, 1],
                                                 new DPStatus(beforeRight.Happiness + infant.Briskness * Math.Abs(infant.Position - beforeRight.RightIndex), beforeRight.LeftIndex, beforeRight.RightIndex - 1));
            }

            yield return(Math.Max(dpStatus[n, 0].Happiness, dpStatus[n, 1].Happiness));
        }
Example #20
0
        long GetMinCost(long n)
        {
            if (memo.ContainsKey(n))
            {
                return(memo[n]);
            }
            else if (n == 0)
            {
                return(0);
            }
            else if (n == 1)
            {
                return(d);
            }
            else
            {
                var min = long.MaxValue;
                if (new BigInteger(n) * d < long.MaxValue)
                {
                    min = n * d;
                }

                var mod2 = n % 2;
                var mod3 = n % 3;
                var mod5 = n % 5;

                AlgorithmHelpers.UpdateWhenSmall(ref min, GetMinCost((n + 1) / 2) + a + (2 - mod2) * d);
                AlgorithmHelpers.UpdateWhenSmall(ref min, GetMinCost(n / 2) + a + mod2 * d);
                AlgorithmHelpers.UpdateWhenSmall(ref min, GetMinCost((n + 2) / 3) + b + (3 - mod3) * d);
                AlgorithmHelpers.UpdateWhenSmall(ref min, GetMinCost(n / 3) + b + mod3 * d);
                AlgorithmHelpers.UpdateWhenSmall(ref min, GetMinCost((n + 4) / 5) + c + (5 - mod5) * d);
                AlgorithmHelpers.UpdateWhenSmall(ref min, GetMinCost(n / 5) + c + mod5 * d);

                return(memo[n] = min);
            }
        }
 public void UpdateWhenSmallTest(int first, int second, int expected)
 {
     AlgorithmHelpers.UpdateWhenSmall(ref first, second);
     Assert.Equal(expected, first);
 }
        public static async Task Main(string[] args)
        {
            var allFilesLines = FileHelpers.GetFilesLines();

            var wholeFileWatch             = Stopwatch.StartNew();
            var fileLines                  = allFilesLines[FileIndex];
            var assumption                 = AssumptionsHelpers.ExtractStatementAssumptions(fileLines);
            var photos                     = AssumptionsHelpers.ExtractPhotos(fileLines);
            var slidesWithHorizontalPhotos = photos.Where(photo => photo.Orientation == "H").Select(photo => new Slide(photo)).ToList();
            var slidesWithVerticalPhotos   = AlgorithmHelpers.CreateSlidesFromVerticalPhotos(photos.Where(photo => photo.Orientation == "V").ToList());
            var sortedSlides               = slidesWithHorizontalPhotos.Concat(slidesWithVerticalPhotos).OrderByDescending(slide => slide.TagsCount).ToList();
            //var sortedSlides = slidesWithHorizontalPhotos.Concat(slidesWithVerticalPhotos).ToList();
            var slideShow = new List <Slide>()
            {
                sortedSlides[0]
            };

            sortedSlides.RemoveAt(0);
            var iterationWatch = Stopwatch.StartNew();

            while (true)
            {
                var   sortedSlidesLen = sortedSlides.Count;
                var   baseSlide       = slideShow.Last();
                Slide bestSlide       = null;
                if (sortedSlidesLen == 0)
                {
                    break;
                }
                if (UseMultipleThreads && sortedSlidesLen > SlidesPerTask)
                {
                    var chunks        = AlgorithmHelpers.SplitList(sortedSlides, SlidesPerTask).ToList();
                    var chunksToCount = chunks.Take(chunks.Count > MaxTasks ? MaxTasks : chunks.Count).ToList();
                    if (sortedSlidesLen % 1000 == 0)
                    {
                        Console.WriteLine($"Chunks: {chunks.Count}");
                    }
                    var tasks = new List <Task <Tuple <int, Slide> > >();
                    chunksToCount.ForEach(chunk => tasks.Add(AlgorithmHelpers.FindBestSildeInChunk(baseSlide, chunk, MinSlideScore)));
                    var tupleList = await Task.WhenAll(tasks.ToArray());

                    bestSlide = tupleList.OrderByDescending(slideTuple => slideTuple.Item1).FirstOrDefault().Item2;
                }
                else
                {
                    //bestSlide = (await AlgorithmHelpers.FindBestSildeInChunk(baseSlide, sortedSlides, MinSlideScore)).Item2;
                    bestSlide = (await AlgorithmHelpers.FindBestSildeInChunk(baseSlide, sortedSlides.Take(sortedSlidesLen > SlidesPerTask * MaxTasks ? SlidesPerTask * MaxTasks : sortedSlidesLen).ToList(), MinSlideScore)).Item2;
                }
                slideShow.Add(bestSlide);
                sortedSlides.Remove(bestSlide);
                if (sortedSlidesLen % 100 == 0)
                {
                    Console.WriteLine($"Slides left: {sortedSlidesLen} elapsed seconds: {(float)iterationWatch.ElapsedMilliseconds / 1000}");
                    iterationWatch.Restart();
                }
            }
            FileHelpers.PrepareResults(slideShow, FileIndex);
            Console.WriteLine($"Finished file {FileIndex} in seconds: {(float)wholeFileWatch.ElapsedMilliseconds / 1000}");
            Console.WriteLine($"Finished file {FileIndex} in minutes: {(float)wholeFileWatch.ElapsedMilliseconds / 60000}");
            Console.ReadLine();
        }
Example #23
0
        public void Start()
        {
            //Read the data from the files
            var file1DataRaw = AlgorithmHelpers.ReadMatrixFromFile(@"class_1.dat");
            var file2DataRaw = AlgorithmHelpers.ReadMatrixFromFile(@"class_2.dat");

            ClassA = AlgorithmHelpers.ScaleDown(AlgorithmHelpers.ChooseFeatures(file1DataRaw));
            ClassB = AlgorithmHelpers.ScaleDown(AlgorithmHelpers.ChooseFeatures(file2DataRaw));

            m_maxX = ClassA.Max(0)[0] > ClassB.Max(0)[0] ? ClassA.Max(0)[0] : ClassB.Max(0)[0];
            m_minX = ClassA.Min(0)[0] < ClassB.Min(0)[0] ? ClassA.Min(0)[0] : ClassB.Min(0)[0];

            //Fill the charts with the data
            m_view.ShowTrainingData(ClassA, ClassB);
            //Clear the list view
            m_view.ClearListView();
            //Fill it with the confusion matrix for each algorithm per iteration
            var statistics = new ConfusionMatrix[4, 5];


            //Merge the two data sets
            //and run kmeans
            var kmeans = new KMeansClustering(AlgorithmHelpers.MergeArrays(file1DataRaw, file2DataRaw),
                                              m_view.Iterations,
                                              m_view.ThetaStep);

            var idx = kmeans.Classify();

            m_view.ClustersTextUpdate(idx.Distinct().Length.ToString());

            m_view.ZeroProgressBar();
            m_view.StepProgressBar();

            //Partition m_iterations times and run the algorithms
            for (int i = 0; i < m_iterations; ++i)
            {
                m_view.PerformStep();
                //Partition its class to training and testing set
                var partitions = new DataPartition[] { AlgorithmHelpers.Partition(ClassA), AlgorithmHelpers.Partition(ClassB) };

                //Create the training data
                var trainingPair   = AlgorithmHelpers.CreateDataPair(partitions[0].Item1, partitions[1].Item1);
                var trainingSet    = trainingPair.Item1;
                var trainingOutput = trainingPair.Item2;

                //Create the testing data
                var testingPair   = AlgorithmHelpers.CreateDataPair(partitions[0].Item2, partitions[1].Item2);
                var testingSet    = testingPair.Item1;
                var testingOutput = testingPair.Item2;

                //Some functions need the training output to be a vector of doubles
                var doubleTO = trainingOutput
                               .Select(x => new[] { Convert.ToDouble(x) })
                               .ToArray();

                for (int k = 1; k < 3; ++k)
                {
                    var nn = new KNearestNeighboursRuntime(k, trainingSet, trainingOutput, testingSet, testingOutput);

                    if (BestKNN == null)
                    {
                        BestKNN = nn.Execute();
                    }
                    else
                    {
                        var iter = nn.Execute();
                        if (iter.Accuracy > BestKNN.Accuracy)
                        {
                            BestKNN = iter;
                        }
                    }
                }

                var perceptron = new PerceptronRuntime(trainingSet, doubleTO, testingSet, testingOutput);
                perceptron.Finished += perceptron_Finished;

                var leastSquare   = new LeastSquaresRuntime(AlgorithmHelpers.JaggedToMD(trainingSet), AlgorithmHelpers.JaggedToMD(doubleTO), AlgorithmHelpers.JaggedToMD(testingSet), testingOutput);
                var neuralNetwork = new ParallelNeuralNetworkRuntime(trainingSet, doubleTO, testingSet, testingOutput);

                neuralNetwork.Finished += neuralNetwork_Finished;
                //Compute the confusion matrices for the four classifiers
                statistics[0, i] = perceptron.Execute();
                statistics[1, i] = leastSquare.Execute();
                //Use the most accurate K of KNN
                statistics[2, i] = BestKNN;
                statistics[3, i] = neuralNetwork.Execute();
            }

            //Update the classifier lines in the charts
            //with the most accurate of the 5 iterations
            m_view.ChartUpdate("", "classifier", MostAccuratePerceptron.Item1);
            m_view.ChartUpdate("", "classifier1", MostAccurateNN.Item1);

            //Process the array with the Confusion Matrices
            //and update the list view
            var processed = AlgorithmHelpers.ProcessStatistics(statistics);

            m_view.UpdateStatisticsListView(processed);
        }