List Manipulation Advanced
Здравейте, имам 40/100.
1.List Manipulation Advanced
Next, we are going to implement more complicated list commands, extending the previous task. Again, read a list and keep reading commands until you receive "end":
Contains {number} – check if the list contains the number and if so - print "Yes", otherwise print "No such number".
PrintEven – print all the even numbers, separated by a space.
PrintOdd – print all the odd numbers, separated by a space.
GetSum – print the sum of all the numbers.
Filter {condition} {number} – print all the numbers that fulfill the given condition. The condition will be either '<', '>', ">=", "<=".
After the end command, print the list only if you have made some changes to the original list. Changes are made only from the commands from the previous task.
Example
Input |
Output |
2 13 43 876 342 23 543 Contains 100 Contains 543 PrintEven PrintOdd GetSum Filter >= 43 Filter < 100 end |
No such number Yes 2 876 342 13 43 23 543 1842 43 876 342 543 2 13 43 23 |
using System;
using System.Collections.Generic;
using System.Linq;
namespace List_Manipulation_Advanced
{
class Program
{
static void Main(string[] args)
{
List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList();
string command = Console.ReadLine();
int counter = 0;
while (command != "end")
{
string[] token = command.Split();
if (token[0] == "Contains")
{
int number = int.Parse(token[1]);
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] == number)
{
counter++;
}
}
if (counter > 0)
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No such number");
}
}
else if (token[0] == "PrintEven")
{
for (int i = 0; i < numbers.Count; i++)
{
int evenOrOdd = numbers[i];
if (evenOrOdd % 2 == 0)
{
Console.Write(evenOrOdd + " ");
}
}
Console.WriteLine();
}
else if (token[0] == "PrintOdd")
{
for (int i = 0; i < numbers.Count; i++)
{
int oddNumber = numbers[i];
if (oddNumber % 2 != 0)
{
Console.Write(oddNumber + " ");
}
}
Console.WriteLine();
}
else if (token[0] == "GetSum")
{
Console.WriteLine(numbers.Sum());
}
else if (token[0] == "Filter")
{
if (token[1] == "<")
{
int number = int.Parse(token[2]);
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] < number)
{
Console.Write(string.Join(" ", numbers[i]) + " ");
}
}
Console.WriteLine();
}
else if (token[1] == ">")
{
int number = int.Parse(token[2]);
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] > number)
{
Console.Write(string.Join(" ", numbers[i]) + " ");
}
}
Console.WriteLine();
}
else if (token[1] == ">=")
{
int number = int.Parse(token[2]);
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] >= number)
{
Console.Write(string.Join(" ", numbers[i]) + " ");
}
}
Console.WriteLine();
}
else
{
int number = int.Parse(token[2]);
for (int i = 0; i < numbers.Count; i++)
{
if (numbers[i] <= number)
{
Console.Write(string.Join(" ", numbers[i] + " "));
}
}
Console.WriteLine();
}
}
command = Console.ReadLine();
}
}
}
}
Благодаря ти !