Loading...

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

Elena123456 avatar Elena123456 235 Точки

Въпрос от Arrays-запис на точно определени елементи от един масив в друг с различна дължина от първоначалния

Изгледах няколко лекции от Programming Fundamental за масиви, търсех информация във форуми, но не успях да намеря отговора на въпроса ми. Възможно е и нещо да съм пропуснала от обучението. Зная как да записвам елементи от един масив в друг, но ако искам новия масив да е с различна дължина записа не се получава. Моля за малко разяснение за да мога да приключа с масивите и да продължа по-нататъка. Вече трета седмица стоя само на масиви.

Ето един пример за по-нагледно:

Input:               Output:

1 3 2 4 6            2 4

2 even

 

Input:               Output:

1 3 2 4 6            2 4 6 (искам да печата, колкото има, т.е в случая само 3)

4 even

 

Input:               Output:

2 2 4 6            "Invalid index"

3 odd

 

Input:                  Output:

1 4 6 8 3 5             1 3 5

3 odd

 

 

 

За съжаление успявам само да прочета масива и командата, но не и да запиша четните числа в нов масив:

using System;
using System.Linq;


namespace Arrays1
{
    class MainClas
    {
        public static void Main()
        {

            int[] array = Console.ReadLine().Split().Select(int.Parse).ToArray();
            string command = Console.ReadLine();
            string[] commandArr = command.Split();
            int index = int.Parse(commandArr[0]);
            string type = commandArr[1];


            if (type == "even")
            {
                int[] newArr = new int[index];
                if (index <= array.Length)
                {
                    for (int i = 0; i < array.Length - 1 && i < index; i++)
                    {
                        if (array[i] % 2 == 0)
                        {

                            newArr[index] = array[i];
                        }

                    }

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

                else
                {
                    Console.WriteLine("Invalid index");
                }

            }
        }
    }

}

 

Тагове:
0
Programming Fundamentals
Axiomatik avatar Axiomatik 2422 Точки

Don't know what the exercise is, but hope that this helps:

using System;
using System.Linq;

namespace Array
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = Console.ReadLine()
                .Split()
                .Select(int.Parse)
                .ToArray();

            string command = Console.ReadLine();

            string[] commandArguments = command
                .Split();

            int index = int.Parse(commandArguments[0]);

            string type = commandArguments[1];

            if (type == "even")
            {
                // LINQ variant which does not require for-loop
                // Array length will adapt to the given amount of numbers
                // int[] newArr = array
                //    .Where(num => num % 2 == 0)
                //    .ToArray();

                int[] newArr = new int[index];
                if (index <= array.Length)
                {
                    int counter = 0;
                    for (int i = 0; i < array.Length && counter < index; i++)
                    {
                        if (array[i] % 2 == 0)
                        {
                            newArr[counter] = array[i];
                            counter++;
                        }
                    }
                    if (newArr.Sum() > 0)
                    {
                        Console.WriteLine(string.Join(" ", newArr.Where(num => num != 0)));
                    }
                    else
                    {
                        Console.WriteLine("Invalid index");
                    }
                }
            }
            else
            {
                // LINQ variant which does not require for-loop
                // Array length will adapt to the given amount of numbers
                // int[] newArr = array
                //    .Where(num => num % 2 != 0)
                //    .ToArray();

                int[] newArr = new int[index];
                if (index <= array.Length)
                {
                    int counter = 0;
                    for (int i = 0; i < array.Length && counter < index; i++)
                    {
                        if (array[i] % 2 != 0)
                        {
                            newArr[counter] = array[i];
                            counter++;
                        }
                    }

                    if (newArr.Sum() > 0)
                    {
                        Console.WriteLine(string.Join(" ", newArr.Where(num => num != 0)));
                    }
                    else
                    {
                        Console.WriteLine("Invalid index");
                    }
                }
            }
        }
    }
}
 

1
Elena123456 avatar Elena123456 235 Точки

Thank you very much for your quick responce. There is no exercise, this is only my question. :)

Is very userfriendly and comfortable to use "counter" for create a numbers of elements in new array,

but I can't understand what this is doing:

  if (newArr.Sum() > 0)
  {
     Console.WriteLine(string.Join(" ", newArr.Where(num => num != 0)));
   }

Why are you usind "newArr.Where.."?  I'am not familiar with this syntax.

 

 

I tried to print a new array which contens only even number using counter, but unsuccessfully.

Print only "0".

 

using System;
using System.Linq;


namespace Arrays1
{
    class MainClas
    {
        public static void Main()
        {

            int[] array = Console.ReadLine().Split().Select(int.Parse).ToArray();

           
            string command = Console.ReadLine();
            string[] commandArr = command.Split();
            int index = int.Parse(commandArr[0]);
            string type = commandArr[1];


            if (type == "even")
            {
                int[] newArr = new int[index];
                if (index <= array.Length) 
                {
                    int counter=0;

                    for (int i = 0; i < array.Length - 1 && index < counter; i++)
                    {

                        if (array[i] % 2 == 0)
                        {
                           
                            newArr[counter] = array[i];

                        }

                    }

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

             
            }
        }
   }
}

0
20/07/2020 20:32:49
Axiomatik avatar Axiomatik 2422 Точки

The way you set up your exercise, if you have the following input : “1 3 2 4 6” + “4 even”, output will be “2 4 6 0”, but since you specified that you are looking for a filtered output that does not print empty elements of the array (in this case 0), you have to apply some sort of filter. In this case “newArr.Where(num => num != 0)” (filter any number that is not 0 in newArr and pass it on to string.Join).

1
krum_43 avatar krum_43 750 Точки

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

Ето ти един кратък код на C#:

 


        static void Main(string[] args)
        {
            int[] numbers = Console.ReadLine().Split().Select(int.Parse).ToArray();
            List<int> output = new List<int>();
            string command = Console.ReadLine();
            string[] commandSplit = command.Split();
            int currentCount = 0;
            int count = int.Parse(commandSplit[0]);
            string evenOrAdd = commandSplit[1];
            if (evenOrAdd == "even")
            {
                for (int i = 0; i <numbers.Length  ; i++)                              
                {
                    if (numbers[i] % 2 == 0)
                    {
                        currentCount++;
                        output.Add(numbers[i]);
                        if ((currentCount == count) || (i ==numbers.Length - 1))
                        {
                            if(output.Count==0)
                            {
                                Console.WriteLine("Invalid index");
                            }
                            Console.WriteLine(String.Join(" ", output));
                            return;
                        }
                    }
                }
            }
            if (evenOrAdd == "odd")
            {
                foreach (var number in numbers)
                {
                    if (number % 2 == 1)
                    {
                        currentCount++;
                        output.Add(number);
                        if ((currentCount == count) || (number == numbers[numbers.Length - 1]))
                        {
                            if (output.Count == 0)
                            {
                                Console.WriteLine("Invalid index");
                            }
                            Console.WriteLine(String.Join(" ", output));
                            return;
                        }
                    }
                }
            }
                                      
        }
    }
}
 

 

1
22/07/2020 09:03:41
Elena123456 avatar Elena123456 235 Точки

Благодаря! Тъкмо навлизам в списъците и ми трябва малко време да осъзная решението Ви, но със сигурност ще ми е от полза.

Поздрави!

 

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