Exemplo n.º 1
0
        private Bitmap GetMouseActivity(Rectangle r, Bitmap bo, int screenID, int[,] mouse, bool writeTestFile = false)
        {
            StringBuilder sb = new StringBuilder();
            Bitmap        b  = new Bitmap(r.Width, r.Height);

            int maxNum = mouse.Cast <int>().Max(),
                used   = mouse.Cast <int>().Count(x => x > 0);

            MessageBox.Show(r.Width + " " + r.Height + "; Max Num = " + maxNum + string.Format("; % ({0} used of {1}) = " + (used / (double)(r.Width * r.Height)).ToString("F10") + "%", used, r.Width * r.Height));

            for (int i = 0; i < r.Width; ++i)
            {
                for (int j = 0; j < r.Height; ++j)
                {
                    b.SetPixel(i, j, Interpolate(bo.GetPixel(i, j), Color.Red, Clamp(mouse[i, j] / (double)maxNum, 0, 1)));  //new Color(255, 0, 0, mouse[i, j] * 255 / maxNum)

                    if (writeTestFile)
                    {
                        sb.Append(string.Format("{0}x{1}: {2} ({3:F2})", i, j, mouse[i, j], mouse[i, j] / (double)maxNum) + Environment.NewLine);
                    }
                }
            }

            if (writeTestFile)
            {
                File.WriteAllText(testFile, sb.ToString());
            }

            b.Save(Path.Combine(appPath, string.Format("map{0}.png", screenID)));

            return(b);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 简洁的语义代码
        /// Simple semantic code
        /// </summary>
        public static Dictionary <string, double> damagedOrSunk(int[,] board, int[,] attacks)
        {
            var result = new Dictionary <string, double>();

            var boardBefore = board.Cast <int>().Where(x => x != 0)
                              .GroupBy(x => x)
                              .ToDictionary(gr => gr.Key, gr => gr.Count());

            // Apply attacks
            for (var i = 0; i < attacks.GetLength(0); i++)
            {
                board[board.GetLength(0) - attacks[i, 1], attacks[i, 0] - 1] = 0;
            }

            var boardAfter = board.Cast <int>().Where(x => x != 0)
                             .GroupBy(x => x)
                             .ToDictionary(gr => gr.Key, gr => gr.Count());

            result["sunk"]       = boardBefore.Keys.Count - boardAfter.Keys.Count;
            result["notTouched"] = boardAfter.Count(x => x.Value == boardBefore[x.Key]);

            result["damaged"] = boardBefore.Keys.Count - result["sunk"] - result["notTouched"];
            result["points"]  = result["sunk"] + 0.5 * result["damaged"] - 1 * result["notTouched"];

            return(result);
        }
 public void GetResult(ref int[,] mas)
 {
     story.Add(new Evristicknow {
         Cost  = EvristicFunction(mas.Cast <int>().ToArray()),
         steps = mas.Cast <int>().ToArray(), root = Copy(mas), visit = false
     });
     SeeTree(ref mas);
 }
Exemplo n.º 4
0
        public bool Solvability()//Checks if board is solveable
        {
            bool Solvable = false;

            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Determining solvability:                                                                                                                                                            //
            // If the grid width is odd, then the number of inversions in a solvable situation is even.                                                                                            //
            // If the grid width is even, and the blank is on an even row counting from the bottom (second-last, fourth-last etc), then the number of inversions in a solvable situation is odd.   //
            // If the grid width is even, and the blank is on an odd row counting from the bottom (last, third-last, fifth-last etc) then the number of inversions in a solvable situation is even.//
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            int[] TwoDtoArray = Board.Cast <int>().ToArray();//2D array to 1D array
            //Calculate number of inversions
            //An inversion is when a tile precedes another tile with a lower number on it.
            int Inversions = 0;

            for (int i = 0; i < TwoDtoArray.Length; i++)
            {
                for (int j = i; j < TwoDtoArray.Length; j++)
                {
                    if (TwoDtoArray[i] > TwoDtoArray[j] && TwoDtoArray[i] != 0 && TwoDtoArray[j] != 0)
                    {
                        Inversions++;
                    }
                }
            }
            int zeroPos = findZeroRow();

            if (size % 2 != 0)//odd width
            {
                if (Inversions % 2 == 0)
                {
                    Solvable = true;
                }
            }
            else if (size % 2 == 0)            //even width
            {
                if ((size - zeroPos) % 2 == 0) //even row counting from the button
                {
                    if (Inversions % 2 != 0)
                    {
                        Solvable = true;
                    }
                }
                else//odd row counting from the button
                {
                    if (Inversions % 2 == 0)
                    {
                        Solvable = true;
                    }
                }
            }

            return(Solvable);
        }
Exemplo n.º 5
0
        public void CreateRandomArray_CheckMinMaxRange()
        {
            // Arrange
            var array = getCreateRandomArray();
            int min = 5, max = 10;

            // Act
            int[,] result = array.CreateRandomArray(5, 5, min, max);
            // Assert
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Cast <int>().Max() <= max && result.Cast <int>().Min() >= min);
        }
        private void Recalculate()
        {
            for (int i = 0; i < BITS; i++)
            {
                bitTotals[i] = table.Sum(v => Bit(i, v));
            }
            for (int i = 0; i < BITS; i++)
            {
                for (int j = 0; j < BITS; j++)
                {
                    matrix[i, j] = 0;
                    for (int k = 0; k < LEN; k++)
                    {
                        matrix[i, j] += Bit(j, table[k]) & Bit(i, k);
                    }
                }
            }
            int mTotal = 0;

            for (int i = 0; i < BITS; i++)
            {
                matrixTotals[i] = 0;
                for (int j = 0; j < BITS; j++)
                {
                    matrixTotals[i] += matrix[j, i];
                }
                mTotal += matrixTotals[i];
            }
            int mAvg = mTotal / BITS;

            Variance = 0;
            for (int i = 0; i < BITS; i++)
            {
                matrixVariances[i]    = matrixTotals[i] - mAvg;
                matrixAbsVariances[i] = Math.Abs(matrixVariances[i]);
                Variance += matrixAbsVariances[i];
            }
            if (populated == LEN && Variance == 0)
            {
                Minimum            = matrix.Cast <int>().Min();
                Maximum            = matrix.Cast <int>().Max(m => m >= 31 ? int.MinValue : m);
                MatrixVariance     = matrix.Cast <int>().Sum(m => Math.Abs(m >= 31 ? 0 : (m - 16)));
                Improvement        = (Minimum > BestMinimum) || (Maximum < BestMaximum) || (MatrixVariance < BestMatrixVariance);
                BestMinimum        = BestMinimum > Minimum ? BestMinimum : Minimum;
                BestMaximum        = BestMaximum < Maximum ? BestMaximum : Maximum;
                BestMatrixVariance = BestMatrixVariance > MatrixVariance ? BestMatrixVariance : MatrixVariance;
            }
            else
            {
                Improvement = false;
            }
        }
Exemplo n.º 7
0
        private void PlainTextBox_TextChanged(object sender, EventArgs e)
        {
            EncryptionButton.Enabled = KeyTextBox.Text != string.Empty && PlainTextBox.Text != string.Empty;

            if (!radioButton2.Checked || PlainTextBox.Text == "")
            {
                return;
            }

            var count = _keyMatrix.Cast <int>().Count(digital => digital == 1);

            EncryptionButton.Enabled = count == 4;
        }
Exemplo n.º 8
0
 private static void Print()
 {
     Console.WriteLine($"Alive cells: {matrix.Cast<int>().Where(x => x > 0).Count()}");
     Console.WriteLine($"Sum: {matrix.Cast<int>().Where(x => x > 0).Sum()}");
     for (int row = 0; row < matrix.GetLength(0); row++)
     {
         for (int col = 0; col < matrix.GetLength(1); col++)
         {
             Console.Write(matrix[row, col] + " ");
         }
         Console.WriteLine();
     }
 }
Exemplo n.º 9
0
        private bool IsHorizontalyComplete(GameProgress progress)
        {
            var rows = progress.Current.GetLength(1);
            var horizontalyConsequitive = new List <int> [rows];

            for (var row = 0; row < rows; row++)
            {
                var rowElements          = progress.Current.GetRowElements(row);
                var consequitiveElements = _consequitiveElementsFinder.Find(rowElements);
                horizontalyConsequitive[row] = consequitiveElements;
            }

            return(horizontalyConsequitive.Cast <int>().SequenceEqual(_horizontalHints.Cast <int>()));
        }
Exemplo n.º 10
0
        public bool IsValid()
        {
            try
            {
                arr = To2D(board);

                int max = arr.Cast <int>().Max();
                int min = arr.Cast <int>().Min();

                double sqrt = Math.Sqrt(max);

                sqrtRegions = (int)sqrt;

                var list = new List <int>();

                for (int i = min; i < max + 1; i++)
                {
                    list.Add(i);
                }

                values = list.ToArray();

                if (min <= 0)
                {
                    throw new Exception();
                }
                if (sqrt != Math.Round(sqrt, 0))
                {
                    throw new Exception();
                }
                if (CheckColumns(arr) == false)
                {
                    throw new Exception();
                }
                if (CheckRows(arr) == false)
                {
                    throw new Exception();
                }
                if (CheckRegions(arr) == false)
                {
                    throw new Exception();
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 11
0
    // Start is called before the first frame update
    void Start()
    {
        Renderer grapthRender = gameObject.GetComponent(typeof(Renderer)) as Renderer;
        Vector3  graphSize    = grapthRender.bounds.size;
        float    maxElement   = cases.Cast <int>().Max();

        for (int z = 0; z < cases.Length / 10; z++)
        {
            for (int x = 0; x < 10; x++)
            {
                GameObject dataPoint       = Instantiate(DataPoint, new Vector3(0, 0, 0), Quaternion.identity);
                float      dataPointXscale = (float)(graphSize.x / ((cases.Length)));
                float      dataPointYscale = (float)(graphSize.y / maxElement) * cases[z, x];
                float      dataPointZscale = (float)(graphSize.z / ((cases.Length)));

                dataPoint.transform.localScale = new Vector3(dataPointXscale, dataPointYscale, dataPointZscale);
                dataPoint.transform.parent     = gameObject.transform;
                Vector3 dataPointSize = dataPoint.transform.localScale;
                float   dataPointXpos = (-1 / 2f) + (dataPointSize.x / 2f);
                float   dataPointYpos = (-1 / 2f) + (dataPointSize.y / 2f);
                float   dataPointZpos = (-1 / 2f) + (dataPointSize.z / 2f);
                dataPoint.transform.localPosition = new Vector3(dataPointXpos + ((dataPoint.transform.localScale.x * 2) * x), dataPointYpos, dataPointZpos + ((dataPoint.transform.localScale.z * 2) * z));
            }
        }
    }
Exemplo n.º 12
0
 static void PartA()
 {
     int[,] map = ReadInput();
     //PrintMap(map);
     map = RunAnimation(map, false);
     Console.WriteLine("Part A: Result is {0}.", map.Cast <int>().Sum());
 }
Exemplo n.º 13
0
        public void DrawGrid(int[,] board, bool done)
        {
            DisplayGrid.Children.Clear();

            int max = board.Cast <int>().Max();

            for (int i = 0; i < board.GetLength(0); i++)
            {
                for (int j = 0; j < board.GetLength(1); j++)
                {
                    TextBlock txtBlock1 = new TextBlock();
                    txtBlock1.Text          = board[i, j].ToString();
                    txtBlock1.FontSize      = 14;
                    txtBlock1.TextAlignment = TextAlignment.Center;
                    Grid.SetRow(txtBlock1, i);
                    Grid.SetColumn(txtBlock1, j);

                    if (board[i, j] == max)
                    {
                        txtBlock1.Background = new SolidColorBrush(Colors.Red);
                    }
                    else if (done)
                    {
                        txtBlock1.Background = new SolidColorBrush(Colors.Green);
                    }
                    if (board[i, j] == 0)
                    {
                        txtBlock1.Background = new SolidColorBrush(Colors.LightGray);
                    }
                    DisplayGrid.Children.Add(txtBlock1);
                }
            }
        }
Exemplo n.º 14
0
        private void CreateRandomTestMap_Click(object sender, EventArgs e)
        {
            if (this.Controls.Count == initialControlsCount + 1)
            {
                this.Controls.RemoveAt(initialControlsCount);
            }
            PictureBox pb1 = new PictureBox();

            Int32.TryParse(MapDimensionList.SelectedItem.ToString(), out dimensions);
            perlinMatrix = RasterFunctions.CreateTestArrayRandomPerlin(perlinFrequency, perlinMap);
            Console.Write("Minimum value of perlin Matrix : " + perlinMatrix.Cast <int>().Min() + ", maximum value : " + perlinMatrix.Cast <int>().Max() + "\n");
            // Initializing the nodes of the map
            perlinMap.ReinitializeMap();
            perlinMap.mapIsTestMap = true;
            perlinMap.InitializeNodes(perlinMatrix);
            perlinMap.InitializeLinks();
            // We transform the array to a bitmap
            pb1.Image = RasterFunctions.MapToBitmap(perlinMap, costMap);
            // We display everything nicely
            pb1.SizeMode = PictureBoxSizeMode.CenterImage;
            this.Size    = new System.Drawing.Size(1000, 1000);
            pb1.Size     = new System.Drawing.Size(1000, 1000);
            pb1.SizeMode = PictureBoxSizeMode.CenterImage;
            this.Controls.Add(pb1);

            // We also send the signal that pre-processing needs to be re-done but that the map
            // is now generated
            mapGenerated              = true;
            preProcessingDone         = false;
            departureArrivalGenerated = false;
        }
 public void Correct()
 {
     int[,] mat  = { { 1, 2 }, { 3, 4 } };
     int[,] test = { { 0, 1 }, { 1, 2 } };
     int[,] result;
     result = Matrix.Divide(mat, 2);
     Assert.IsTrue(Enumerable.SequenceEqual(result.Cast <int>(), test.Cast <int>()));
     test = new int[, ] {
         { 0, 0 }, { 0, 0 }
     };
     result = Matrix.Divide(mat, 10);
     Assert.IsTrue(Enumerable.SequenceEqual(result.Cast <int>(), test.Cast <int>()));
     mat = new int[, ] {
         { 10, 20 }, { 30, 40 }
     };
     test = new int[, ] {
         { 1, 2 }, { 3, 4 }
     };
     result = Matrix.Divide(mat, 10);
     Assert.IsTrue(Enumerable.SequenceEqual(result.Cast <int>(), test.Cast <int>()));
     test = new int[, ] {
         { -5, -10 }, { -15, -20 }
     };
     result = Matrix.Divide(mat, -2);
     Assert.IsTrue(Enumerable.SequenceEqual(result.Cast <int>(), test.Cast <int>()));
 }
Exemplo n.º 16
0
        //public static void ConvFilter(this PictureBox pctrBox, int[,] kernel)
        //{
        //    int R, G, B;
        //    R = G = B = 0;
        //    int avgR, avgG, avgB;



        //    int divisor = kernel.Cast<int>().Sum();
        //    if (divisor == 0)
        //        divisor = 1;
        //    Bitmap bm = new Bitmap(pctrBox.Image);

        //    int top = (kernel.GetLength(1) / 2) * bm.Width * 4;
        //    int bot = (bm.Height - (kernel.GetLength(1) / 2)) * bm.Width * 4;
        //    int left = (kernel.GetLength(0) / 2) * 4 - 4;
        //    int right = (bm.Width - (kernel.GetLength(0) / 2)) * 4;
        //    Point[] points =
        //    {
        //        new Point(0, 0),
        //        new Point(bm.Width, 0),
        //        new Point(0, bm.Height),
        //    };
        //    Rectangle rect = new Rectangle(0, 0, bm.Width, bm.Height);
        //    BitmapData bmData = bm.LockBits(rect, ImageLockMode.ReadWrite, bm.PixelFormat);
        //    IntPtr ptr = bmData.Scan0;
        //    int bitsPerPixel = Image.GetPixelFormatSize(bm.PixelFormat);
        //    int bytes = Math.Abs(bmData.Stride) * bm.Height;
        //    byte[] rgbValues = new byte[bytes];
        //    byte[] resultValues = rgbValues;
        //    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

        //    for (int counter = 0; counter < bytes; counter += bitsPerPixel / 8)
        //    {
        //        for(int y = -kernel.GetLength(1)/2; y <= kernel.GetLength(1)/2; y++)
        //        {
        //            for(int x = -kernel.GetLength(0)/2; x <= kernel.GetLength(0)/2; x++)
        //            {
        //                if((counter < top) & (counter % (4*bm.Width) <= left))
        //                {
        //                    if (x < 0 & y < 0)
        //                    {
        //                        R += rgbValues[counter    ];
        //                        G += rgbValues[counter + 1];
        //                        B += rgbValues[counter + 2];
        //                    }
        //                    else if (x >= 0 & y < 0)
        //                    {
        //                        R += rgbValues[counter     + (x) * 4];
        //                        G += rgbValues[counter + 1 + (x) * 4];
        //                        B += rgbValues[counter + 2 + (x) * 4];
        //                    }
        //                    else if (x < 0 & y >= 0)
        //                    {
        //                        R += rgbValues[counter     + (y * bm.Width) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width) * 4];
        //                    }
        //                    else if (x >= 0 & y >= 0)
        //                    {
        //                        R += rgbValues[counter     + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                }

        //                else if ((counter < top) & (counter % (4*bm.Width) >= right))
        //                {
        //                    if (x <= 0 & y >= 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                    else if (x > 0 & y >= 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width) * 4];
        //                    }
        //                    else if (x <= 0 & y < 0)
        //                    {

        //                        R += rgbValues[counter + (x) * 4];
        //                        G += rgbValues[counter + 1 + (x) * 4];
        //                        B += rgbValues[counter + 2 + (x) * 4];
        //                    }
        //                    else if (x > 0 & y < 0)
        //                    {

        //                        R += rgbValues[counter];
        //                        G += rgbValues[counter + 1];
        //                        B += rgbValues[counter + 2];
        //                    }
        //                }

        //                else if ((counter < top) & !(counter % (4*bm.Width) >= right) & !(counter % (4*bm.Width) <= left))
        //                {
        //                    if (y < 0)
        //                    {
        //                        R += rgbValues[counter + (x) * 4];
        //                        G += rgbValues[counter + 1 + (x) * 4];
        //                        B += rgbValues[counter + 2 + (x) * 4];
        //                    }
        //                    else
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                }
        //                else if ((counter % (4*bm.Width) <= left) & !(counter >= bot) & !(counter < top))
        //                {
        //                    if (x < 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width) * 4];
        //                    }
        //                    else
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                }
        //                else if ((counter % (4*bm.Width) >= left) & !(counter >= bot) & !(counter < top))
        //                {
        //                    if (x > 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width) * 4];
        //                    }
        //                    else
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                }

        //                else if ((counter >= bot) & (counter % (4*bm.Width) <= left))
        //                {
        //                    if (x >= 0 & y <= 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                    else if (x < 0 & y <= 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width) * 4];
        //                    }
        //                    else if (x >= 0 & y > 0)
        //                    {

        //                        R += rgbValues[counter + (x) * 4];
        //                        G += rgbValues[counter + 1 + (x) * 4];
        //                        B += rgbValues[counter + 2 + (x) * 4];
        //                    }
        //                    else if (x < 0 & y > 0)
        //                    {

        //                        R += rgbValues[counter];
        //                        G += rgbValues[counter + 1];
        //                        B += rgbValues[counter + 2];
        //                    }
        //                }

        //                else if ((counter >= bot) & (counter % (4*bm.Width) >= right))
        //                {
        //                    if (x <= 0 & y <= 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                    else if (x > 0 & y <= 0)
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width) * 4];
        //                    }
        //                    else if (x <= 0 & y > 0)
        //                    {

        //                        R += rgbValues[counter + (x) * 4];
        //                        G += rgbValues[counter + 1 + (x) * 4];
        //                        B += rgbValues[counter + 2 + (x) * 4];
        //                    }
        //                    else if (x > 0 & y > 0)
        //                    {

        //                        R += rgbValues[counter];
        //                        G += rgbValues[counter + 1];
        //                        B += rgbValues[counter + 2];
        //                    }
        //                }

        //                else if ((counter >= bot) & !(counter % (4*bm.Width) >= right) & !(counter % (4*bm.Width) <= left))
        //                {
        //                    if (y > 0)
        //                    {
        //                        R += rgbValues[counter + (x) * 4];
        //                        G += rgbValues[counter + 1 + (x) * 4];
        //                        B += rgbValues[counter + 2 + (x) * 4];
        //                    }
        //                    else
        //                    {
        //                        R += rgbValues[counter + (y * bm.Width + x) * 4];
        //                        G += rgbValues[counter + 1 + (y * bm.Width + x) * 4];
        //                        B += rgbValues[counter + 2 + (y * bm.Width + x) * 4];
        //                    }
        //                }


        //            }
        //        }
        //        avgR = R / divisor;
        //        avgG = G / divisor;
        //        avgB = B / divisor;
        //        resultValues[counter    ] = (byte)(avgR);
        //        resultValues[counter + 1] = (byte)(avgG);
        //        resultValues[counter + 2] = (byte)(avgB);

        //        R = G = B = 0;

        //    }
        //    System.Runtime.InteropServices.Marshal.Copy(resultValues, 0, ptr, bytes);
        //    bm.UnlockBits(bmData);
        //    pctrBox.Image = bm;
        //}

        public static void ApplyFilter(this PictureBox pctrBox, int[,] kernel, int offset)
        {
            int R, G, B;

            R = G = B = 0;
            int divisor = kernel.Cast <int>().Sum();

            if (divisor == 0)
            {
                divisor = 1;
            }
            Bitmap     bm           = new Bitmap(pctrBox.Image);
            Rectangle  rect         = new Rectangle(0, 0, bm.Width, bm.Height);
            BitmapData bmData       = bm.LockBits(rect, ImageLockMode.ReadWrite, bm.PixelFormat);
            IntPtr     ptr          = bmData.Scan0;
            int        bitsPerPixel = Image.GetPixelFormatSize(bm.PixelFormat);
            int        bytes        = Math.Abs(bmData.Stride) * bm.Height;

            byte[] rgbValues    = new byte[bytes];
            byte[] resultValues = new byte[bytes];;
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            for (int counter = 0; counter < bytes; counter += 4)
            {
                R = G = B = 0;
                for (int y = -kernel.GetLength(1) / 2; y <= kernel.GetLength(1) / 2; y++)
                {
                    for (int x = -kernel.GetLength(0) / 2; x <= kernel.GetLength(0) / 2; x++)
                    {
                        int sourceX = counter % (bm.Width * 4) + x * 4;
                        int sourceY = ((int)counter / ((int)bm.Width * 4)) * 4 + y * 4;
                        if (sourceX < 0)
                        {
                            sourceX = 0;
                        }
                        if (sourceX >= bm.Width * 4)
                        {
                            sourceX = (bm.Width - 1) * 4;
                        }
                        if (sourceY < 0)
                        {
                            sourceY = 0;
                        }
                        if (sourceY >= bm.Height * 4)
                        {
                            sourceY = (bm.Height - 1) * 4;
                        }
                        R += (rgbValues[sourceX + sourceY * bm.Width] * kernel[y + (kernel.GetLength(1) / 2), x + (kernel.GetLength(0) / 2)]);
                        G += (rgbValues[sourceX + sourceY * bm.Width + 1] * kernel[y + (kernel.GetLength(1) / 2), x + (kernel.GetLength(0) / 2)]);
                        B += (rgbValues[sourceX + sourceY * bm.Width + 2] * kernel[y + (kernel.GetLength(1) / 2), x + (kernel.GetLength(0) / 2)]);
                    }
                }
                resultValues[counter]     = Clamp(0, 255, (R / divisor) + offset);
                resultValues[counter + 1] = Clamp(0, 255, (G / divisor) + offset);
                resultValues[counter + 2] = Clamp(0, 255, (B / divisor) + offset);
                resultValues[counter + 3] = 255;
            }
            System.Runtime.InteropServices.Marshal.Copy(resultValues, 0, ptr, bytes);
            bm.UnlockBits(bmData);
            pctrBox.Image = bm;
        }
Exemplo n.º 17
0
 public static int IsSolved(int[,] board)
 {
     for (int i = 0; i < 3; i++)
     {
         if (board[i, 0] == board[i, 1] && board[i, 0] == board[i, 2] && board[i, 0] != 0)
         {
             return(board[i, 0] == 1 ? 1 : 2);
         }
         if (board[0, i] == board[1, i] && board[0, i] == board[2, i] && board[0, i] != 0)
         {
             return(board[0, i] == 1 ? 1 : 2);
         }
     }
     if (board[0, 0] == board[1, 1] && board[1, 1] == board[2, 2] && board[1, 1] != 0)
     {
         return(board[1, 1] == 1 ? 1 : 2);
     }
     if (board[0, 2] == board[1, 1] && board[1, 1] == board[2, 0] && board[1, 1] != 0)
     {
         return(board[1, 1] == 1 ? 1 : 2);
     }
     if (board.Cast <int>().ToArray().Contains(0))
     {
         return(-1);
     }
     return(0);
 }
Exemplo n.º 18
0
 protected bool AreTwoMultidimensionalArraysSame(int[,] matrix1, int[,] matrix2)
 {
     return(matrix1.Rank == matrix2.Rank &&
            Enumerable.Range(0, matrix1.Rank)
            .All(dimension => matrix1.GetLength(dimension) == matrix2.GetLength(dimension)) &&
            matrix1.Cast <int>().SequenceEqual(matrix2.Cast <int>()));
 }
Exemplo n.º 19
0
 /// <summary>
 /// Min value in the matrix check - Its reference value
 /// </summary>
 /// <param name="inputGraph">input data</param>
 /// <exception cref="InputValidatorException">Throws when input data validation fails</exception>
 private void MandatoryDataCheck(int[,] inputGraph)
 {
     if (inputGraph.Cast <int>().Count(x => (x > 0 && x < 10)) < 3)
     {
         throw new InputValidatorException("input data not having mandatory numbers in the matrix");
     }
 }
Exemplo n.º 20
0
        public override string GetResult(string[] input)
        {
            var data = input.Select(i => Regex.Split(i, @"\D+")
                                    .Where(x => !string.IsNullOrWhiteSpace(x))
                                    .Select(x => int.Parse(x)));

            var claims = data.Select(x => new Claim(x.ToArray()));

            foreach (var claim in claims)
            {
                for (int i = claim.Left; i < claim.Left + claim.Width; i++)
                {
                    for (int j = claim.Top; j < claim.Top + claim.Height; j++)
                    {
                        _fabric[i, j]++;
                    }
                }
            }

            var result = _fabric
                         .Cast <int>()
                         .Count(x => x > 1);

            return(result.ToString());
        }
Exemplo n.º 21
0
 /// <summary>
 /// Compare the values of two matrices. http://stackoverflow.com/a/12446807
 /// </summary>
 /// <returns>TRUE if all values are equal; otherwise return FALSE</returns>
 private bool CompareMatricesValues(int[,] m1, int[,] m2)
 {
     return(m1.Rank == m2.Rank &&
            Enumerable.Range(0, m1.Rank)
            .All(dimension => m1.GetLength(dimension) == m2.GetLength(dimension)) &&
            m1.Cast <int>().SequenceEqual(m2.Cast <int>()));
 }
Exemplo n.º 22
0
        static void ShowUp1(int[,] array)
        {
            Console.WriteLine();
            var list = array.Cast <int>().ToList();

            list.Reverse();
            int Part = 0;

            for (int y = 0; y < array.GetLength(0); y++)
            {
                for (int x = 0; x < array.GetLength(1); x++)
                {
                    array[y, x] = list[Part];
                    Part++;
                }
            }
            for (int y = 0; y < array.GetLength(0); y++)
            {
                for (int x = 0; x < array.GetLength(1); x++)
                {
                    Console.Write(array[y, x] + " ");
                }
                Console.WriteLine();
            }
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\n--------------------------------------------");
            Console.ResetColor();
        }
Exemplo n.º 23
0
    /*GameEnd(void):ゲームが終わった時の処理
     * 引数:board
     * 返り値:なし*/
    void GameEnd(int[,] boarddata)
    {
        //検索のため盤面データを1次元配列に変換
        int[] board_1dim = boarddata.Cast <int>().ToArray();
        //石の個数
        int black = 0;
        int white = 0;

        //石の数をカウント
        foreach (int disk in board_1dim)
        {
            switch (disk)
            {
            case  -1:
                black += 1;
                break;

            case 1:
                white += 1;
                break;
            }
        }
        //石の数を表示する
        canvas.enabled = true;
        text.text      = "黒: " + black + "白: " + white;
    }
Exemplo n.º 24
0
        public static void Print(int[,] m, int[] paintStart = null, int[] paintEnd = null)
        {
            int    rowLength       = m.GetLength(0);
            int    colLength       = m.GetLength(1);
            int    maxNumberLength = m.Cast <int> ().Max().ToString().Length;
            string elStr;

            bool paint = paintStart != null && paintEnd != null;

            for (int i = 0; i < rowLength; i++)
            {
                Console.Write("{");
                for (int j = 0; j < colLength; j++)
                {
                    elStr = m [i, j].ToString().PadRight(maxNumberLength, ' ');
                    if (paint && paintStart [0] <= i && paintEnd [1] >= j && paintStart [1] >= i && paintEnd [0] <= j)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                    }
                    Console.Write(elStr + (j != colLength - 1 ? "  " : ""));
                    Console.ResetColor();
                }
                Console.Write("}\n");
            }
        }
Exemplo n.º 25
0
 private static int CheckWinner()
 {
     for (int i = 0; i < 3; i++)
     {
         if (Playfield[i, 0] != 0 && Playfield[i, 0] == Playfield[i, 1] && Playfield[i, 0] == Playfield[i, 2])
         {
             return(Playfield[i, 0]);
         }
     }
     for (int i = 0; i < 3; i++)
     {
         if (Playfield[0, i] != 0 && Playfield[0, i] == Playfield[1, i] && Playfield[0, i] == Playfield[2, i])
         {
             return(Playfield[0, i]);
         }
     }
     if (Playfield[0, 0] == Playfield[1, 1] && Playfield[0, 0] == Playfield[2, 2])
     {
         return(Playfield[0, 0]);
     }
     if (Playfield[0, 2] == Playfield[1, 1] && Playfield[0, 2] == Playfield[2, 0])
     {
         return(Playfield[0, 2]);
     }
     if (Playfield.Cast <int>().Min() > 0)
     {
         return(3);
     }
     return(0);
 }
Exemplo n.º 26
0
        public static void TestGetClosestPointsToOrigin
        (
            int testIdentifier,
            int amountOfPointsClosestToOrigin,
            int[] origin,
            int[,] pointsToAnalyze,
            int[,] expectedOutput)
        {
            try
            {
                int[,] actualOutput = GetClosestPointsToOrigin(amountOfPointsClosestToOrigin, origin, pointsToAnalyze);

                bool isEqual =
                    actualOutput.Rank == expectedOutput.Rank &&
                    Enumerable.Range(0, actualOutput.Rank).All(dimension => actualOutput.GetLength(dimension) ==
                                                               expectedOutput.GetLength(dimension)) &&
                    actualOutput.Cast <int>().SequenceEqual(expectedOutput.Cast <int>());

                if (isEqual)
                {
                    return;
                }
            }
            catch
            {}

            Console.WriteLine(string.Format("Test case {0} failed.", testIdentifier));
        }
Exemplo n.º 27
0
 /// <summary>
 /// Invalid number check in the input data
 /// </summary>
 /// <param name="inputGraph">input data</param>
 /// <exception cref="InputValidatorException">Throws when input data validation fails</exception>
 private void InvalidNumberCheck(int[,] inputGraph)
 {
     if (inputGraph.Cast <int>().Count(x => (x < 0 || x >= 10)) > 0)
     {
         throw new InputValidatorException("Invalid data in the input data");
     }
 }
Exemplo n.º 28
0
        public void OutputArray(int[,] twoDimensionalArray, int rows, int columns, List <ISorter> sorters)
        {
            int a = 0;

            checkedSorters = sorters;
            this.rows      = rows;
            this.columns   = columns;
            arraysShowTabControl.TabPages.Clear();

            foreach (var sorter in checkedSorters)
            {
                TabPage page = new TabPage(sorter.methodName);
                arraysShowTabControl.TabPages.Add(page);
                a++;

                DataGridView newDataGridView = new DataGridView();
                newDataGridView.Dock = DockStyle.Fill;
                page.Controls.Add(newDataGridView);
                newDataGridView.ReadOnly             = true;
                newDataGridView.RowHeadersVisible    = false;
                newDataGridView.ColumnHeadersVisible = false;
                newDataGridView.RowCount             = rows;
                newDataGridView.ColumnCount          = columns;

                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < columns; j++)
                    {
                        newDataGridView.Rows[i].Cells[j].Value = twoDimensionalArray[i, j];
                    }
                }
                oneDimensionalArray = twoDimensionalArray.Cast <int>().ToArray();
            }
        }
Exemplo n.º 29
0
        //obtain histogram allocation of [0..255] in image array
        private static int[] ImHist(int[,] img)
        {
            int[] tempData     = img.Cast <int>().ToArray();
            int[] imHistResult = new int[256]; //uint8 size
            int   count        = 0;

            int[] temp = new int[256];
            for (int k = 0; k < temp.Length; k++)
            {
                temp[k] = k;
            }

            for (int i = 0; i < 256; i++)
            {
                count = 0;
                for (int j = 0; j < tempData.Length; j++)
                {
                    if (temp[i] == tempData[j])
                    {
                        count++;
                    }
                }
                imHistResult[i] = count;
            }
            return(imHistResult);
        }
Exemplo n.º 30
0
        public void GetCoordinates_Should_Return_Empty_Coordinates_When_Word_Is_Not_Found()
        {
            // Arrange
            int[,] expectedCoordinates = new int[0, 2] {
            };

            _mockService.Setup(s => s.GetCoordinates(It.IsAny <string[]>(), It.IsAny <string>())).Returns(expectedCoordinates);
            _mockService.Setup(s => s.CreateRecord(It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <DateTime>())).Returns(-1);

            _controller = new SearchController(_mockService.Object);

            string word = "PRUEBA";

            // Act
            IHttpActionResult httpActionResult = _controller.GetCoordinates(word);

            // Assert
            Assert.IsInstanceOfType(httpActionResult, typeof(JsonResult <int[, ]>));

            JsonResult <int[, ]> jsonResult = (JsonResult <int[, ]>)httpActionResult;

            int[,] coordinates = jsonResult.Content;

            Assert.IsTrue(expectedCoordinates.Cast <int>().SequenceEqual(coordinates.Cast <int>()));
        }