Loading...

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

EvgeniVT avatar EvgeniVT 61 Точки
Best Answer

Ето тук съм ти преправил малко кода https://pastebin.com/fPfxqdYxСлучаите когато индекса е извън границите не е нужно да махаш и да слагаш елементи в списъка. Само записваш стойността на тази която остава в клетка на тази която се маха. Предполагам, че грешките идват от това че точно си указал с цифра елемента с кой индекс да се махне което в даден случай да не е коректно.

3
Ferhaps avatar Ferhaps 2 Точки

Благодаря !

1
Elena123456 avatar Elena123456 235 Точки

Здравейте, може ли малко помощ и на мен за тази задача? Два теста ми гръмят 80/100- Incorect Answer, тоест не  излизам от границите на масива. Дебъгвах няколко пъти, но не мога да открия нищо. С дадените инпути в условието получавам правилните аутпути.

https://pastebin.com/K2CBMfNk

0
Axiomatik avatar Axiomatik 2422 Точки

From what I can see the only problem was on lines 42 + 62, since you didn't change the values inside of the original collection, but overwrote an external int value with a new int value from the collection :

 

firstElement = listOfDistances[listOfDistances.Count – 1];

instead of :

listOfDistances[0] = listOfDistances[listOfDistances.Count – 1];

 

This would have otherwise worked with reference-type data (objects, collections, …), but unfortunately not with primitive-type data (double, int, string, ...).

I also removed string.join at line 80, you can directly print out the final sum. For additional, try to refactor the code by using one for-loop for all three if-else validations.

Can't test the solution in judge, but I think this should do it.

Best,

Code:

using System;
using System.Linq;
using System.Collections.Generic;


namespace PokemonDontGo
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            List<int> listOfDistances = Console.ReadLine().Split().Select(int.Parse).ToList();

            List<int> removedElements = new List<int>();

            while (listOfDistances.Count != 0)
            {
                int index = int.Parse(Console.ReadLine());

                if (index >= 0 && index < listOfDistances.Count)
                {
                    int distance = listOfDistances[index];
                    removedElements.Add(distance);
                    listOfDistances.RemoveAt(index);

                    for (int i = 0; i <= listOfDistances.Count - 1; i++)
                    {
                        if (listOfDistances[i] <= distance)
                        {
                            listOfDistances[i] = listOfDistances[i] + distance;
                        }
                        else if (listOfDistances[i] > distance)
                        {
                            listOfDistances[i] = listOfDistances[i] - distance;
                        }
                    }
                }
                else if (index < 0)
                {
                    int firstElement = listOfDistances[0];
                    removedElements.Add(firstElement);
                    //firstElement = listOfDistances[listOfDistances.Count - 1];
                    listOfDistances[0] = listOfDistances[listOfDistances.Count - 1];

                    for (int i = 0; i < listOfDistances.Count; i++)
                    {
                        if (listOfDistances[i] <= firstElement)
                        {
                            listOfDistances[i] = listOfDistances[i] + firstElement;
                        }
                        else if (listOfDistances[i] > firstElement)
                        {
                            listOfDistances[i] = listOfDistances[i] - firstElement;
                        }
                    }
                }
                else if (index >= listOfDistances.Count)
                {
                    int firstElement = listOfDistances[0];
                    int lastElement = listOfDistances[listOfDistances.Count - 1];
                    removedElements.Add(lastElement);
                    //lastElement = firstElement;
                    listOfDistances[listOfDistances.Count - 1] = firstElement;

                    for (int i = 0; i < listOfDistances.Count; i++)
                    {
                        if (listOfDistances[i] <= lastElement)
                        {
                            listOfDistances[i] = listOfDistances[i] + lastElement;
                        }
                        else if (listOfDistances[i] > lastElement)
                        {
                            listOfDistances[i] = listOfDistances[i] - lastElement;
                        }
                    }
                }
            }

            //Console.WriteLine(string.Join(" ", removedElements.Sum()));
            Console.WriteLine(removedElements.Sum());
        }
    }
}
 

 

 

1
Elena123456 avatar Elena123456 235 Точки

@Axiomatik ,

thanks again!

This is a very big mistake which I have made. I know differences betwen Reference and Value type. The first are stored in the heap, but the second are stored in the stack (faster memory). When int a=5 and int b=a we have made a copy of a in b and b also became 5, because they are Value type. When we have Reference type (lists, arrays) in upper case we copy not the value in the heap, but only their references in the stack. For arrays I know about .SequenceEqual Method to say that one array is equal to another. Maybe that works and for lists too.

In this exercise I see this theoretical knowledge in the practice. Thank you for that! I promise I will work with reference type with more attention. :)

I have already refactored my code and extracted all for loops in method  "IncreaseAndDecreaseAllElements ()": https://pastebin.com/ern1ntcW

Thank you for your time!

Elena

 

1
Axiomatik avatar Axiomatik 2422 Точки

Hi,

Seen the modifications and looks great now. By the way, check out the SoftUni-seminar with Jordan Georgiev from 17 September, has some useful tips on how to learn programming and also provides useful industry insights for the next years to come.

Best,

1
Elena123456 avatar Elena123456 235 Точки

Thanks for useful information!

I have found the webinar-  https://softuni.bg/trainings/resources/video/52993/video-17-september-2020-jordan-georgiev-how-to-learn-programming-better-and-faster/3143

Today I would be watching it.

Best regards!

Elena

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