Loading...

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

PoliDobreva avatar PoliDobreva 1 Точки

ArrayManipulatorProblem Lists ProgrammingFundamentals

Здравейте, някой може ли да помогне с кода:https://pastebin.com/smH5tWnt

Дава ми 83/100 и out of memory... малко дървено е решението >>>

Ето и условието: 

Write a program that reads an array of integers from the console and set of commands and executes them over the array. The commands are as follows:

  • add <index> <element> – adds element at the specified index (elements right from this position inclusively are shifted to the right).
  • addMany <index> <element 1> <element 2> … <element n> – adds a set of elements at the specified index.
  • contains <element> – prints the index of the first occurrence of the specified element (if exists) in the array or -1 if the element is not found.
  • remove <index> – removes the element at the specified index.
  • shift <positions>shifts every element of the array the number of positions to the left (with rotation).
    • For example, [1, 2, 3, 4, 5] -> shift 2 -> [3, 4, 5, 1, 2]
  • sumPairs – sums the elements in the array by pairs (first + second, third + fourth, …).
    • For example, [1, 2, 4, 5, 6, 7, 8] -> [3, 9, 13, 8].
  • print – stop receiving more commands and print the last state of the array.

Input

Output

1 2 4 5 6 7

add 1 8

contains 1

contains -3

print

0

-1

[1, 8, 2, 4, 5, 6, 7]

1 2 3 4 5

addMany 5 9 8 7 6 5

contains 15

remove 3

shift 1

print

-1

[2, 3, 5, 9, 8, 7, 6, 5, 1]

2 2 4 2 4

add 1 4

sumPairs

print

[6, 6, 6]

1 2 1 2 1 2 1 2 1 2 1 2

sumPairs

sumPairs

addMany 0 -1 -2 -3

print

[-1, -2, -3, 6, 6, 6]

Тагове:
0
Programming Fundamentals
NikolayNeykov92 avatar NikolayNeykov92 617 Точки

Здравей, 

3-ти тест дава грешен резултат заради изчисляването на contains случая, а последния тест дава memory limit заради пазенето на входните данни в списък, вместо в масив. Ето фикснатият ти код:

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

namespace ArrayManipulator
{
    class Program
    {
        static void Main(string[] args)
        {
            List<long> input = Console.ReadLine().Split(' ').Select(long.Parse).ToList();


            while (true)
            {
                string[] command = Console.ReadLine().Split(' ');

                if (command[0] == "add")
                {
                    input.Insert(int.Parse(command[1]), int.Parse(command[2]));
                }

                else if (command[0] == "addMany")
                {
                    int position = int.Parse(command[1]);
                    for (int i = command.Length - 1; i >= 2; i--)
                    {
                        input.Insert(position, int.Parse(command[i]));
                    }
                }

                else if (command[0] == "contains")
                {
                    Console.WriteLine(input.IndexOf(long.Parse(command[1])));
                    //bool IsFound = false;
                    //for (int i = 0; i < input.Count; i++)
                    //{
                    //    if (input[i] == int.Parse(command[1]))
                    //    {
                    //        Console.WriteLine(i);
                    //        IsFound = true;
                    //    }
                    //}
                    //if (!IsFound)
                    //{
                    //    Console.WriteLine("-1");
                    //}

                }

                else if (command[0] == "remove")
                {
                    input.RemoveAt(int.Parse(command[1]));

                }

                else if (command[0] == "shift")
                {
                    int pos = int.Parse(command[1]);
                    for (int i = 0; i < pos; i++)
                    {
                        input.Add(input[i]);
                    }

                    while (pos != 0)
                    {
                        input.RemoveAt(0);
                        pos--;
                    }

                }

                else if (command[0] == "sumPairs")
                {
                    int count = input.Count / 2;
                    for (int i = 0; i < count; i++)
                    {
                        long sum = input[i] + input[i + 1];
                        input.RemoveAt(i);
                        input.RemoveAt(i);
                        input.Insert(i, sum);
                    }
                }

                else if (command[0] == "print")
                {
                    break;
                }
            }

            Console.WriteLine($"[{string.Join(", ", input)}]");
        }
    }
}

 

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