Loading...

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

VesselinTonchev avatar VesselinTonchev 5 Точки

Methods looping

Здравейте :),

Всичко се счупи, след като добавих метод, който да валидира, че индексите, с които ще се работи, не са out of range. Уж всичко точно, но като вкарам "End", за да изляза, ме прехвърля в IndexValidator и вътре директно отива в CommandChecker, а после в метода, който е в един от case -вете на switch - Remove???!?!?@?? Страшен мазаляк се получи и не разбирам защо. Ако го махна тоя метод за валидиране и си го хардкодна в двата случая, които ме интересуват, всичко си работи, но има повтаряем код. 

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

namespace List_Exercise___Vol_5
{
    class Program
    {        static void Main(string[] args)
        {
            List<string> numbers = Console.ReadLine().Split().ToList();
            CommandChecker(numbers);

            Console.WriteLine(string.Join(" ", numbers));
        }
        static void CommandChecker(List<string> numbers)
        {
            List<string> command = Console.ReadLine().Split().ToList();            
            while(command[0] != "End")
            {
                switch (command[0])
                {                    
                    case "Add":                        
                        Add(numbers, command);
                        break;
                    case "Insert":
                        int temp = Convert.ToInt32(command[2]);
                        IndexValidator(numbers, command, ref temp);
                        
                        Insert(numbers, command);
                        break;
                    case "Remove":
                        temp = Convert.ToInt32(command[1]);
                        IndexValidator(numbers, command, ref temp);

                        Remove(numbers, command);
                        break;
                    case "Shift":
                        if (command[1] == "left")
                        {
                            ShiftLeft(numbers, command);
                        }
                        else
                        {
                            ShiftRight(numbers, command);
                        }
                        break;
                }
                command = Console.ReadLine().Split().ToList();
            }            
        }
        static void IndexValidator(List<string> numbers, List<string> command, ref int temp)
        {
            if (temp > numbers.Count || temp < 0)
            {
                Console.WriteLine("Invalid index");
                CommandChecker(numbers);
            }
        }
        static void Add(List<string> numbers, List<string> command)
        {
            numbers.Add(command[1]);
        }
        static void Insert(List<string> numbers, List<string> command)
        {
            int temp = Convert.ToInt32(command[2]);
            numbers.Insert(temp, command[1]);
        }
        static void Remove(List<string> numbers, List<string> command)
        {
            int temp = Convert.ToInt32(command[1]);
            numbers.RemoveAt(temp);
        }
        static void ShiftLeft(List<string> numbers, List<string> command)
        {
            int count = Convert.ToInt32(command[2]);
            while (count > 0)
            {
                numbers.Add(numbers[0]);
                numbers.RemoveAt(0);
                count--;
            }            
        }
        static void ShiftRight(List<string> numbers, List<string> command)
        {
            int count = Convert.ToInt32(command[2]);

            while (count > 0)
            {
                numbers.Insert(0, numbers[numbers.Count - 1]);
                numbers.RemoveAt(numbers.Count - 1);
                count--;
            }
        }
    }
}

 

Тагове:
0
Module: C# Advanced
VesselinTonchev avatar VesselinTonchev 5 Точки

Като добавя това:

Console.WriteLine(string.Join(" ", numbers));
            System.Environment.Exit(1);

веднага след switch-а, всичко заспива и съм 100/100, ама не ме кефи изобщо и съм сигурен, че има адекватен и културен начин да изляза.

0
kkaraivanov avatar kkaraivanov 486 Точки

Здравей! Редактирах метода ти със суича, мисля че ще работи коректно....не съм тествал цялото решение защото не си посочил задачата коя е.

static void CommandChecker(List<string> numbers)
{
    string commands = null;
    while ((commands = Console.ReadLine()) != "End")
    {
        var command = commands.Split().ToList();
        switch (command[0])
        {
            case "Add":
                Add(numbers, command);
                break;
            case "Insert":
                int temp = Convert.ToInt32(command[2]);
                IndexValidator(numbers, command, ref temp);

                Insert(numbers, command);
                break;
            case "Remove":
                temp = Convert.ToInt32(command[1]);
                IndexValidator(numbers, command, ref temp);

                Remove(numbers, command);
                break;
            case "Shift":
                if (command[1] == "left")
                {
                    ShiftLeft(numbers, command);
                }
                else
                {
                    ShiftRight(numbers, command);
                }
                break;
        }
    }
}

 

0
06/03/2020 15:33:52
VesselinTonchev avatar VesselinTonchev 5 Точки

Ами, защото съм тъпак и забравих. И пак не би трябвало да се държи така. Свършва си switch-a и трябва да си приключи. То на същия принцип може да ми залупи и при другите методи

1.List Operations

You will be given a list of integer numbers on the first line of input. You will be receiving operations you have to apply on the list until you receive the "End" command. The possible commands are:

  • Add {number} add number at the end.
  • Insert {number} {index} insert number at given index.
  • Remove {index} remove at index.
  • Shift left {count} first number becomes last ‘count’ times.
  • Shift right {count} last number becomes first ‘count’ times.

Note: there is a possibility that the given index is outside of the bounds of the array. In that case print "Invalid index"

Examples

Input

Output

1 23 29 18 43 21 20

Add 5

Remove 5

Shift left 3

Shift left 1

End

43 20 5 1 23 29 18

5 12 42 95 32 1

Insert 3 0

Remove 10

Insert 8 6

Shift right 1

Shift left 2

End

Invalid index

5 12 42 95 32 8 1 3

0
06/03/2020 16:04:15
kkaraivanov avatar kkaraivanov 486 Точки

ПРобвай този код който направих по задачата

namespace Variables
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            var line = Console.ReadLine().Split().Select(int.Parse).ToList();
            string commands = null;

            while ((commands = Console.ReadLine()) != "End")
            {
                var command = commands.Split(" ", 2);
                var action = command[1];

                switch (command[0])
                {
                    // Add {number}
                    case "Add":
                        int.TryParse(action, out int addNumber);
                        line.Add(addNumber);
                        break;
                    // Insert {number} {index}
                    case "Insert":
                        int.TryParse(action.Split()[0], out int insertNumber);
                        int.TryParse(action.Split()[1], out int insertOnIndex);

                        if (IndexIsValid(line, insertOnIndex))
                            line.Insert(insertOnIndex, insertNumber);
                        else
                            Console.WriteLine("Invalid index");
                        break;
                    // Remove {index}
                    case "Remove":
                        int.TryParse(action, out int removeIndex);
                        if (IndexIsValid(line, removeIndex))
                            line.RemoveAt(removeIndex);
                        else
                            Console.WriteLine("Invalid index");
                        break;
                    // Shift left {count} | Shift right {count}
                    case "Shift":
                        int.TryParse(action.Split()[1], out int count);
                        var direction = action.Split()[0];
                        switch (direction)
                        {
                            case "left":
                                ShiftLeft(line, count);
                                break;
                                case "right":
                                ShiftRight(line, count);
                                break;
                        }
                        break;
                }
            }

            Console.WriteLine(string.Join(" ", line));
        }

        private static void ShiftLeft(List<int> arr, int count)
        {
            var ferst = arr[0];
            arr.RemoveAt(0);
            arr.Add(ferst);
            count--;

            if (count > 0)
                ShiftLeft(arr, count);
        }
        private static void ShiftRight(List<int> arr, int count)
        {
            var last = arr[arr.Count - 1];
            arr.RemoveAt(arr.Count - 1);
            arr.Insert(0, last);
            count--;

            if (count > 0)
                ShiftRight(arr, count);
        }
        private static bool IndexIsValid(List<int> arr, int index)
        {
            return index >= 0 && index < arr.Count;
        }
    }
}

 

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