Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

Elena123456 avatar Elena123456 235 Точки

Здравейте, тъй като вече има подобна тема ще пиша тук.

Прекарах сигурно един цял работен ден над тази задача, но получавам само 10/100. Може би не разбирам условието, което прочетох много на брой пъти. Въпреки всичко това с дадените инпути получавам посочените аутпути. Вече изчерпах всичките си идеи за тази задача и моля за помощ, тъй като не осъзнавам какво пропускам (освен, че не искам да имам в кода си допълнителни while цикли за валидирането на стартовете, а директно си ги задавам, тъй като while циклите може да се извъртят безброй много пъти до намирането на старта).

Ivo's galaxy is represented as a two-dimensional array. You will receive two integers, separated by a space, which represent the two dimensional array - the first being the rows and the second being the columns. Every cell in the matrix is a star that has a value. Ivo starts at the given row and col. He can move only on the diagonal from the lowest left to the upper right, and adds to his score all the stars (values) from the cells he passes through. Unfortunately, there is always an Evil power that tries to prevent his success.

Evil power starts at the given row and col and instantly destroys all stars on the opposite diagonal - from lowest right to the upper left. Ivo adds the values only of the stars that are not destroyed by the evil power.  

Then, you must fill the two dimensional array with increasing integers starting from 0, and continuing on every row, like this:

first row: 0, 1, 2… m

second row: n+1, n+2, n+3… n + n.

The input ends when you receive the command "Let the Force be with you". When that happens, you must print the value of all stars that Ivo has collected successfully.

Input

  • On the first line, you will receive the number N, M -> the dimensions of the matrix. You must then fill the matrix according to these dimensions.
  • On the next several lines you will begin receiving 2 integers separated by a single space, which represent Ivos row and col. On the next line you will receive the Evil Powers coordinates.
  • There will always be at least 2 lines of input to represent at least 1 path of Ivo and the Evil force.
  • When you receive the command, Let the Force be with youthe input ends.

Input:

5 5

5 -1

5 5

Let the Force be with you

Output:

48

 

Input:

5 5

4 -1

4 5

Let the Force be with you

 

Output:

29

 

https://pastebin.com/Hmw6060y

 

0
13/03/2021 23:54:00
Axiomatik avatar Axiomatik 2422 Точки

Hi Eli,

Two variants of Jedi-Galaxy.

:-)

using System;
using System.Linq;

namespace P03_JediGalaxy
{
    class Program
    {
        static void Main()
        {
            int[] dimestions = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
            int x = dimestions[0];
            int y = dimestions[1];

            int[,] matrix = new int[x, y];

            int value = 0;
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    matrix[i, j] = value++;
                }
            }

            string command = Console.ReadLine();
            long sum = 0;
            while (command != "Let the Force be with you")
            {
                int[] ivoS = command.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
                int[] evil = Console.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
                int xE = evil[0];
                int yE = evil[1];

                while (xE >= 0 && yE >= 0)
                {
                    if (xE >= 0 && xE < matrix.GetLength(0) && yE >= 0 && yE < matrix.GetLength(1))
                    {
                        matrix[xE, yE] = 0;
                    }
                    xE--;
                    yE--;
                }

                int xI = ivoS[0];
                int yI = ivoS[1];

                while (xI >= 0 && yI < matrix.GetLength(1))
                {
                    if (xI >= 0 && xI < matrix.GetLength(0) && yI >= 0 && yI < matrix.GetLength(1))
                    {
                        sum += matrix[xI, yI];
                    }

                    yI++;
                    xI--;
                }

                command = Console.ReadLine();
            }

            Console.WriteLine(sum);

        }
    }
}

 

using System;
using System.Linq;

namespace jediGalaxy
{
    public class StartUp
    {
        static void Main(string[] args)
        {
            int[] matrixDimensions = Console.ReadLine()
                .Split(" ", StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToArray();

            var matrix = new int[matrixDimensions[0], matrixDimensions[1]];

            MatrixCreate(matrix);

            int ivoStars = 0;

            string[] startIvo = Console.ReadLine()
                .Split(" ", StringSplitOptions.RemoveEmptyEntries);

            string[] startEvil = Console.ReadLine()
                .Split(" ", StringSplitOptions.RemoveEmptyEntries);


            matrix = EvilMove.EvilDestroyStars(matrix, startEvil);

            ivoStars = IvoMove.IvoCollectStars(matrix, startIvo, ivoStars);

            string command = Console.ReadLine();

            if (command == "Let the Force be with you")
            {
                Console.WriteLine(ivoStars);
            }
        }

        private static void MatrixCreate(int[,] matrix)
        {
            int counter = 0;

            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    matrix[row, col] = counter++;
                }
            }
        }
    }
}


using System;
namespace jediGalaxy
{
    public static class IvoMove
    {

        public static int IvoCollectStars(int[,] matrix, string[] startIvo, int ivoStars)
        {
            int startRow = int.Parse(startIvo[0]);
            int startCol = int.Parse(startIvo[1]);
            startRow--;
            startCol++;

            while (startRow >= 0 && startCol < matrix.GetLength(1))
            {
                ivoStars += matrix[startRow, startCol];
                startRow--;
                startCol++;
            }


            return ivoStars;
        }

    }
}


using System;
namespace jediGalaxy
{
    public static class EvilMove
    {

        public static int[,] EvilDestroyStars(int[,] matrix, string[] startEvil)
        {
            int startRow = int.Parse(startEvil[0]);
            int startCol = int.Parse(startEvil[1]);
            startRow--;
            startCol--;


            while (startRow >= 0 && startCol >= 0)
            {
                matrix[startRow, startCol] = 0;
                startRow--;
                startCol--;
            }

            return matrix;
        }

    }
}

 

1
Elena123456 avatar Elena123456 235 Точки

Hi, 

Thanks for both solutions.

I saw a lot of solutions about this exercise, but I can't see where is the problem in mine. Why I got only 10 points? Is my logic incorrect and I don't understand the exercise? I was debugging and your solutions and it seems  my solution should is working correctly, but is not. 

All the best!

0
Axiomatik avatar Axiomatik 2422 Точки

Heavy code.

Main problem came from index-validations executed at the following =>

 


new version:
                while (evilStartRow >= 0 && evilStartCol >= 0)
                {
                    EvilDestroysStars(matrix, ref sumOfStars);
                }

 

new version
                while (ivoStartRow >= 0 && ivoStartCol < matrixCols)
                {
                    //IvoCollectsStars(matrix, ref sumOfStars, ref ivoStartRow, ref ivoStartCol);
                    IvoCollectsStars(matrix, ref sumOfStars);
                }

Also, when modifying the matrix you need to validate the coordinates each time, which is why you received 10/100

        private static bool ValidateCoordinates(int row, int col, int[,] matrix)
        {
            return (row >= 0 && row < matrix.GetLength(0))
                && (col >= 0 && col < matrix.GetLength(1));
        }

 

 

1
14/03/2021 12:29:41
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.