示例#1
0
        public static void PartOne()
        {
            Console.WriteLine("Day Three - Part One");
            char[][] trees = PuzzleInputHelper.GetInputMatrix("DayThree.txt");

            int ouchies = Weeeeeeeeeeeee(trees, 3, 1);

            string displayRectangle = MatrixHelper <char> .GetDisplayRectangle(trees, new Rectangle(0, 0, 20, 20), MatrixWrap.WrapHorizontally | MatrixWrap.WrapVertically);

            Console.WriteLine(displayRectangle);

            Console.WriteLine($"You have {ouchies} ouchies. Oof!");

            Console.WriteLine("Day Three - End of Part One");
        }
        public void GivenA4x5Matrix_FlatMatrix_ShouldReturnProperString()
        {
            string[,] matrix =
            {
                { "D", "f", "e", "s", "T" },
                { "e", "f", " ", "o", "R" },
                { "v", " ", "p", " ", " " },
                { "o", "s", "u", "A", " " }
            };

            var result = MatrixHelper.FlatMatrix(matrix);

            Assert.IsNotNull(result);
            Assert.AreEqual("DfesTef oRv p  osuA ", result);
        }
示例#3
0
        public void Render(float partialTicks)
        {
            float partialRot = _lastTick + (_tick - _lastTick) * partialTicks;

            Matrix4 mat = MatrixHelper.CreateTransformationMatrix(SharpCraft.Instance.Camera.Pos, Vector3.UnitY * partialRot / 10, 1);

            _cube.Bind();
            _cube.Shader.SetMatrix4("transformationMatrix", mat);

            GL.BindTexture(TextureTarget.TextureCubeMap, _texture);

            _cube.RawModel.Render();

            _cube.Unbind();
        }
示例#4
0
        private void CollectSelectedBots()
        {
            if (!DesignMode)
            {
                MatrixHelper.ClearSelectedBots();

                foreach (ListViewItem item in lsvAllBots.CheckedItems)
                {
                    if (item.Group.Name.Equals("lvgWithAbilities"))
                    {
                        MatrixHelper.AddSelectedBot((IBot)item.Tag);
                    }
                }
            }
        }
        public void Returns_The_Lowest_Costs_With_Negative_Costs_Matrix2()
        {
            var costMatrix = new int[, ]
            {
                { 1, 0, 0 },
                { 0, 0, 0 },
                { 0, 1, 0 }
            };

            var maxCostMatrix = MatrixHelper.GetMaxMatrixForHungarianMatching(costMatrix, 1);

            var result = HungarianMatching.GetAssignmentsWithMinimunCost(maxCostMatrix);

            CollectionAssert.AreEqual(new int[] { 0, 2, 1 }, result);
        }
示例#6
0
 /// <summary>
 ///     Traditional matrix multiplication operator between to matrices A and B
 /// </summary>
 /// <param name="m1">the first matrix A to get the matrix AB </param>
 /// <param name="m2">the second matrix B to get the matrix AB </param>
 /// <returns>the matrix AB from matrices A and B</returns>
 public static T operator *(SquareMatrix <T> m1, SquareMatrix <T> m2)
 {
     double[,] result = MatrixHelper.Fill(m1.M, 0); //zeroes
     for (int m = 0; m < m1.M; m++)
     {
         for (int n = 0; n < m1.N; n++)
         {
             for (int k = 0; k < m1.N; k++)
             {
                 result[m, n] += m1[m, k] * m2[k, n];
             }
         }
     }
     return((T)Activator.CreateInstance(typeof(T), result));
 }
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;

        Vector3 pos = MatrixHelper.GetPosition(matrix);
        Vector3 vx  = MatrixHelper.GetXVector(matrix);
        Vector3 vy  = MatrixHelper.GetYVector(matrix);
        Vector3 vz  = MatrixHelper.GetZVector(matrix);

        Gizmos.color = Color.red;
        Gizmos.DrawLine(pos, pos + vx);

        Gizmos.color = Color.green;
        Gizmos.DrawLine(pos, pos + vy);

        Gizmos.color = Color.blue;
        Gizmos.DrawLine(pos, pos + vz);


        if (drawGrid)
        {
            Gizmos.color = Color.white;
            int count = Mathf.Min(drawGridCount, 25);
            for (int x = 0; x < count; x++)
            {
                for (int y = 0; y < count; y++)
                {
                    Vector3 p = MatrixHelper.MultiplyPoint(matrix, new Vector3(x * drawGridStepSize, y * drawGridStepSize, 0));

                    Gizmos.color = Color.blue;
                    Vector3 v = vz * drawGridCount * drawGridStepSize;
                    Gizmos.DrawLine(p, p + v);

                    p = MatrixHelper.MultiplyPoint(matrix, new Vector3(0, x * drawGridStepSize, y * drawGridStepSize));

                    Gizmos.color = Color.green;
                    v            = vx * drawGridCount * drawGridStepSize;
                    Gizmos.DrawLine(p, p + v);

                    p = MatrixHelper.MultiplyPoint(matrix, new Vector3(x * drawGridStepSize, 0, y * drawGridStepSize));

                    Gizmos.color = Color.red;
                    v            = vy * drawGridCount * drawGridStepSize;
                    Gizmos.DrawLine(p, p + v);
                }
            }
        }
    }
示例#8
0
        public void Update()
        {
            prevPos = pos;
            Vector3 prevVel = vel;

            vel = Vector3.Clamp(vel, -MaxSpeed, MaxSpeed);

            acl = Vector3.Clamp(acl, -MaxForce, MaxForce);

            this.pos += vel;
            this.vel += acl;

            this.rotation = MatrixHelper.RotateTowardMatrix(Vector3.Zero, vel);

            this.acl = Vector3.Zero;
        }
示例#9
0
        public void RowMultiplicationTestHelper()
        {
            Matrix <int> matrix   = new Matrix <int>(3, 3, 5);
            int          target   = 0;
            double       multiple = 4.0;
            Matrix <int> expected = new Matrix <int>(3, 3, 5);

            for (int c = 0; c < expected.Columns; c++)
            {
                expected[target, c] = 20;
            }
            Matrix <int> actual;

            actual = MatrixHelper.RowMultiplication(matrix, target, multiple);
            Assert.IsTrue(CompareMatrix(expected, actual));
        }
示例#10
0
        public override void Render(float partialTicks)
        {
            Vector3 partialPos   = Vector3.Lerp(LastPos, Pos, partialTicks);
            float   partialScale = lastParticleScale + (particleScale - lastParticleScale) * partialTicks;

            partialPos.Y += partialScale / 2;

            ModelBaked <Particle> model = ParticleRenderer.ParticleModel;

            model.Shader.UpdateGlobalUniforms();
            model.Shader.UpdateModelUniforms();
            model.Shader.UpdateInstanceUniforms(MatrixHelper.CreateTransformationMatrix(partialPos, Vector3.Zero, partialScale), this);

            GL.BindTexture(TextureTarget.Texture2D, textureID);
            model.RawModel.Render(PrimitiveType.Quads);
        }
示例#11
0
        public void Render(float partialTicks)
        {
            float partialRot = lastTick + (tick - lastTick) * partialTicks;

            Matrix4 mat = MatrixHelper.CreateTransformationMatrix(SharpCraft.Instance.Camera.pos, Vector3.UnitY * partialRot / 10, 1);

            cube.Bind();
            cube.Shader.UpdateGlobalUniforms();
            cube.Shader.UpdateModelUniforms(cube.RawModel);
            cube.Shader.UpdateInstanceUniforms(mat, null);

            GL.BindTexture(TextureTarget.TextureCubeMap, texture);
            cube.RawModel.Render(PrimitiveType.Triangles);

            cube.Unbind();
        }
示例#12
0
        public double Variance(double x, double y)
        {
            int n = T.Length;

            double[] k = new double[n];
            int      i;
            double   xi, yi;

            for (i = 0; i < n; i++)
            {
                xi   = x - X[i];
                yi   = y - Y[i];
                k[i] = Model(Math.Sqrt(xi * xi + yi * yi));
            }
            return(Model(0) + MatrixHelper.Multiply(MatrixHelper.Multiply(k, K, 1, n, n), k, 1, n, 1)[0]);
        }
示例#13
0
        protected internal override void DebugDraw(double deltaTime, Camera camera)
        {
            var world = MatrixHelper.CreateTransform(Position, Rotate, Scale) * GameObject.Transform.WorldTransform;
            var mvp   = world * camera.View * camera.Projection;
            var color = Color4.MidnightBlue;

            if (State == ActivationState.Active)
            {
                color = Color4.LightGreen;
            }
            else if (State == ActivationState.Inactive)
            {
                color = Color4.DarkSlateGray;
            }
            Drawer.DrawWireframeSphere(radius, mvp, color);
        }
        public void SortInputMatrixBySmallestElementAscending()
        {
            int[,] inputMatrix = { { 75, 19, 45 }, { 49, 52, 78 }, { 81, 6, 40 } };
            int[,] actual      = inputMatrix;
            int row        = 3;
            int column     = 3;
            var descending = false;

            int[] indexes = MatrixHelper.MatrixIndexes(inputMatrix, row, column);
            MatrixSortByMinElement sortBySumAsc = new MatrixSortByMinElement(inputMatrix, row, column, indexes);
            var chooseSortingStrategy           = new SortingStrategy(((IMatrixSort)sortBySumAsc).SortMatrix);

            actual          = chooseSortingStrategy.Invoke(descending);
            int[,] expected = { { 6, 40, 81 }, { 19, 45, 75 }, { 49, 52, 78 } };
            CollectionAssert.AreEqual(expected, actual, "{0} != {1}", expected, actual);
        }
示例#15
0
        public void Returns_The_Lowest_Costs_With_Negative_Costs_Matrix1()
        {
            var costMatrix = new int[, ]
            {
                { 5, 2, 3, 9 },
                { 6, 4, 5, 2 },
                { 3, 7, 2, 6 },
                { 10, 1, 4, 5 }
            };

            var maxCostMatrix = MatrixHelper.GetMaxMatrixForHungarianMatching(costMatrix, 10);

            var result = HungarianMatching.GetAssignmentsWithMinimunCost(maxCostMatrix);

            CollectionAssert.AreEqual(new int[] { 3, 2, 1, 0 }, result);
        }
        private void SquareMatrix_Transpose()
        {
            Console.Clear();

            ConsoleHelper.WriteSeparator("The read matrix is");

            MatrixHelper.PrintToConsole(this.squareMatrix);

            ConsoleHelper.WriteSeparator("The transpose of the read matrix is");

            int[,] transpose = MatrixHelper.Transpose(this.squareMatrix);

            MatrixHelper.PrintToConsole(transpose);

            this.ExerciseEnd_PromptGoBackToMenu("square matrix");
        }
        private void SquareMatrix_Adjunct()
        {
            Console.Clear();

            ConsoleHelper.WriteSeparator("The read matrix is");

            MatrixHelper.PrintToConsole(this.squareMatrix);

            ConsoleHelper.WriteSeparator("The adjunct of the read matrix is");

            int[,] adjunct = MatrixHelper.Adjunct(this.squareMatrix);

            MatrixHelper.PrintToConsole(adjunct);

            this.ExerciseEnd_PromptGoBackToMenu("square matrix");
        }
示例#18
0
        public void RowAdditionTest()
        {
            Matrix <int> matrix   = new Matrix <int>(4, 4, 3);
            int          additive = 1;
            int          target   = 2;
            Matrix <int> expected = new Matrix <int>(4, 4, 3);

            for (int c = 0; c < matrix.Columns; c++)
            {
                expected[target, c] = 6;
            }
            Matrix <int> actual;

            actual = MatrixHelper.RowAddition(matrix, additive, target);
            Assert.IsTrue(CompareMatrix(expected, actual));
        }
        private void SquareMatrix_Determinant()
        {
            Console.Clear();

            ConsoleHelper.WriteSeparator("The read matrix is");

            MatrixHelper.PrintToConsole(this.squareMatrix);

            ConsoleHelper.WriteSeparator("The determinant");

            int determinant = MatrixHelper.Determinant(this.squareMatrix);

            Console.WriteLine($"The determinant is: {determinant}");

            this.ExerciseEnd_PromptGoBackToMenu("square matrix");
        }
示例#20
0
        public static void PartOne()
        {
            char[][] seats = PuzzleInputHelper.GetInputMatrix("DayEleven.txt");

            string displayRect = MatrixHelper <char> .GetDisplayRectangle(seats, new System.Drawing.Rectangle(0, 0, 20, 20));

            Console.WriteLine(displayRect);

            OneRound(seats);

            Console.WriteLine();

            displayRect = MatrixHelper <char> .GetDisplayRectangle(seats, new System.Drawing.Rectangle(0, 0, 20, 20));

            Console.WriteLine(displayRect);
        }
        private void SquareMatrix_Invert()
        {
            Console.Clear();

            ConsoleHelper.WriteSeparator("The read matrix is");

            MatrixHelper.PrintToConsole(this.squareMatrix);

            ConsoleHelper.WriteSeparator("The inverse of the read matrix is");

            float[,] invert = MatrixHelper.Invert(this.squareMatrix);

            MatrixHelper.PrintToConsole(invert);

            this.ExerciseEnd_PromptGoBackToMenu("square matrix");
        }
示例#22
0
            // проверка совпадения матрицы и петтерна. В случае успеха в result лежит матрица с указанием отметок мин
            static bool cmpMatrixAndPattern(matrix m, matrix p, ref matrix result)
            {
                result = MatrixHelper.getNoInitMatrixFrom(m);
                MatrixHelper.initMatrixWithZeroes(ref result);

                if (!MatrixHelper.isEqualMatrix(sumMatrixAndPattern(m, p), MatrixHelper.getPatternMask(p)))
                {
                    return(false);
                }
                else
                {
                    matrix mines_m = getMines(m);
                    matrix mines_p = getMines(p);

                    for (int j = 0; j < mines_m.rows; j++)
                    {
                        for (int i = 0; i < mines_m.cols; i++)
                        {
                            int
                                v_mm = mines_m.cells[j, i],
                                v_mp = mines_p.cells[j, i];

                            if (v_mm == 0 && v_mp == 0)
                            {
                                continue;
                            }
                            if ((v_mm == -2 || v_mm == -3) && v_mp == -2)
                            {
                                continue;
                            }

                            if ((v_mm == -2 || v_mm == -3) && v_mp == 0)
                            {
                                return(false);
                            }

                            if (v_mm == 0 && v_mp == -2)
                            {
                                result.cells[j, i] = -3; continue;
                            }
                        }
                    }

                    // если результатом является нулевая матрица, то вернем ложь, чтобы не обновлять игровое поле
                    return(!MatrixHelper.isZeroMatrix(result));
                }
            }
示例#23
0
        static void Solve()
        {
            var queue = new Queue <Node>();

            var set    = new HashSet <string>();
            var srcStr = MatrixHelper.GetHashString(src);
            var desStr = MatrixHelper.GetHashString(des);

            set.Add(srcStr);

            queue.Enqueue(new Node(src, x, y, new List <string> {
                srcStr
            }));

            while (queue.Count() > 0)
            {
                var p = queue.Dequeue();

                for (int i = 0; i < 4; i++)
                {
                    int tx = dx[i] + p.X;
                    int ty = dy[i] + p.Y;

                    if (IsSafe(tx, ty))
                    {
                        var newMatrix = ArrayHelper.Clone(p.Matrix);
                        var newList   = new List <string>(p.Path);
                        var tmp       = newMatrix[tx, ty];
                        newMatrix[tx, ty]   = 0;
                        newMatrix[p.X, p.Y] = tmp;

                        var hashKey = MatrixHelper.GetHashString(newMatrix);
                        newList.Add(hashKey);
                        if (!set.Contains(hashKey))
                        {
                            queue.Enqueue(new Node(newMatrix, tx, ty, newList));
                        }

                        if (desStr == hashKey)
                        {
                            Print(newList);
                            return;
                        }
                    }
                }
            }
        }
示例#24
0
 private void ComputeFilterGradients(double[,,] gradients)
 {
     _weightOptimizers
     .AsParallel()
     .Select((q, i) => new { Kernel = q, Index = i })
     .ForAll(q =>
     {
         var dEdO = gradients.GetChannel(q.Index);
         for (int j = 0; j < _cache.GetLength(0); j++)
         {
             var dedf = MatrixHelper.Convolution(_cache.GetChannel(j), dEdO);
             q.Kernel
             .GetChannel(j)
             .ForEach((w, ii, jj) => w.SetGradient(dedf[ii, jj]));
         }
     });
 }
示例#25
0
    public override bool CalculateShadow()
    {
        if (base.CalculateShadow() == true)
        {
            if (RingComponent == null)
            {
                return(false);
            }

            if (Texture != null)
            {
                if (Helper.Enabled(RingComponent) == true)
                {
                    InnerRadius = RingComponent.InnerRadius;
                    OuterRadius = RingComponent.OuterRadius;
                }

                var direction = default(Vector3);
                var position  = default(Vector3);
                var color     = default(Color);

                Helper.CalculateLight(Light, transform.position, null, null, ref position, ref direction, ref color);

                var rotation = Quaternion.FromToRotation(direction, Vector3.back);
                var squash   = Vector3.Dot(direction, transform.up); // Find how squashed the ellipse is based on light direction
                var width    = transform.lossyScale.x * OuterRadius;
                var length   = transform.lossyScale.z * OuterRadius;
                var axis     = rotation * transform.up;                                                // Find the transformed up axis
                var spin     = Quaternion.LookRotation(Vector3.forward, new Vector2(-axis.x, axis.y)); // Orient the shadow ellipse
                var scale    = Helper.Reciprocal3(new Vector3(width, length * Mathf.Abs(squash), 1.0f));
                var skew     = Mathf.Tan(Helper.Acos(-squash));

                var shadowT = MatrixHelper.Translation(-transform.position);
                var shadowR = MatrixHelper.Rotation(spin * rotation);          // Spin the shadow so lines up with its tilt
                var shadowS = MatrixHelper.Scaling(scale);                     // Scale the ring into an oval
                var shadowK = MatrixHelper.ShearingZ(new Vector2(0.0f, skew)); // Skew the shadow so it aligns with the ring plane

                Matrix = shadowS * shadowK * shadowR * shadowT;
                Ratio  = Helper.Divide(OuterRadius, OuterRadius - InnerRadius);

                return(true);
            }
        }

        return(false);
    }
示例#26
0
            // добавляем все возможные варианты паттерна (повороты и зеркалирование) в кеш (библиотеку)
            static void addToPatternCache(matrix p, ref List <matrix> list_pattern)
            {
                matrix m_a = p;
                matrix m_b = MatrixHelper.mirrorMatrixHorizontal(p);
                matrix m_c = MatrixHelper.mirrorMatrixVertical(p);

                for (int n = 0; n < 4; n++)
                {
                    list_pattern.Add(m_a);
                    list_pattern.Add(m_b);
                    list_pattern.Add(m_c);

                    p = MatrixHelper.rotateMatrix(m_a);
                    p = MatrixHelper.rotateMatrix(m_b);
                    p = MatrixHelper.rotateMatrix(m_c);
                }
            }
示例#27
0
            // прогоняем по игровому полю паттерн, при совпадение применяем изменения
            static void findAndApplyPattern(ref matrix m, matrix p)
            {
                for (int j = -1; j <= m.rows - p.rows + 1; j++)
                {
                    for (int i = -1; i <= m.cols - p.cols + 1; i++)
                    {
                        matrix sub_matrix = MatrixHelper.getMatrixSlice(m, i, j, p.cols, p.rows);

                        matrix buffer = new matrix();

                        if (cmpMatrixAndPattern(sub_matrix, p, ref buffer))
                        {
                            applyResult(ref m, i, j, buffer);
                        }
                    }
                }
            }
        /// <summary>
        ///  Determines the correct offset for a render transform on an item with the given properties.
        /// </summary>
        private static Vector CalculateRenderOffset(Point center, double orientation, double width, double height,
                                                    Point renderTransformOrigin)
        {
            // Find the center point based on the orientation, the size of the item,
            // and the RenderTransformOrigin. This tells us exactly where the center
            // of the item is rendered with respect to the upper left corner of the
            // item's layout rect.
            var renderOrigin = new Point(width * renderTransformOrigin.X, height * renderTransformOrigin.Y);

            var matrix = Matrix.Identity;

            MatrixHelper.RotateAt(ref matrix, orientation, renderOrigin);
            var renderedCenter = matrix.Transform(new Point(width * 0.5, height * 0.5));

            // Use the rendered center to determine the desired offset for the transform.
            return(Vector.Subtruct(center, renderedCenter));
        }
        public void SortInputMatrixBySmallestElementAscending()
        {
            var sortingStrategy = new SortingStrategy();

            sortingStrategy.MatrixSortStrategy = new MatrixSortByMinElement();
            bool descending = false;

            int[,] inputMatrix = { { 75, 19, 45 }, { 49, 52, 78 }, { 81, 6, 40 } };
            int[,] actual      = inputMatrix;
            int row    = 3;
            int column = 3;

            int[] indexes = MatrixHelper.MatrixIndexes(inputMatrix, row, column);
            actual          = sortingStrategy.ExecuteSort(inputMatrix, row, column, indexes, descending);
            int[,] expected = { { 81, 6, 40 }, { 75, 19, 45 }, { 49, 52, 78 } };
            CollectionAssert.AreEqual(expected, actual, "{0} != {1}", expected, actual);
        }
示例#30
0
        void ca_OnCameraStatusChange(CameraAgent agent)
        {
            CmrPos = (vpMain.Camera as ProjectionCamera).Position;
            Point?p = MatrixHelper.From3Dto2D(AbsoluteVisual, vpMain, vpMain.Camera, new Point3D());

            if (p != null && !double.IsNaN(p.Value.X))
            {
                btnTest.Visibility = System.Windows.Visibility.Visible;
                btnTest.Content    = p.Value.X + "," + p.Value.Y;
                Canvas.SetLeft(btnTest, p.Value.X);
                Canvas.SetTop(btnTest, p.Value.Y);
            }
            else
            {
                btnTest.Visibility = System.Windows.Visibility.Hidden;
            }
        }