Лабораторная работа "Работа с данными типа: множество, дата, кортежи."
Задача №4
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
Dictionary<string, HashSet<string>> guests = new Dictionary<string, HashSet<string>>()
{
{ "Алексей", new HashSet<string> { "Мария", "Иван", "Ольга" } },
{ "Мария", new HashSet<string> { "Алексей", "Ольга" } },
{ "Иван", new HashSet<string> { "Алексей", "Мария" } },
{ "Ольга", new HashSet<string> { "Алексей", "Мария", "Иван" } }
};
HashSet<string> allStudents = new HashSet<string>(guests.Keys);
string host = null;
foreach (var student in guests)
{
if (student.Value.IsSupersetOf(allStudents.Except([student.Key ])))
{
host = student.Key;
break;
}
}
if (host != null)
{
Console.WriteLine($"Ученик который побывал у всех: {host}");
}
else
{
Console.WriteLine("нет такого");
}
}
}
Ученик который побывал у всех: Алексей
Даты:
Задание 1
using System;
class Program
{
static void Main()
{
Console.WriteLine("Введите дату: (ДД.ММ.ГГГГ)");
string inputDate = Console.ReadLine();
var parsedDate = DateTime.Parse(inputDate);
Console.WriteLine("Введенная дата является валидной");
}
}
Введите дату: (ДД.ММ.ГГГГ)
12.05.1999
Введенная дата является валидной
Задание 2
using System;
using System.Reflection;
class Program
{
static void Main()
{
Console.WriteLine("Введите первую дату: (ДД.ММ.ГГГГ)");
string inputFirstDate = Console.ReadLine();
var parsedFirstDate = DateTime.Parse(inputFirstDate);
Console.WriteLine("Введите вторую дату: (ДД.ММ.ГГГГ)");
string inputSecondDate = Console.ReadLine();
var parsedSecondDate = DateTime.Parse(inputSecondDate);
TimeSpan Days = parsedSecondDate - parsedFirstDate;
Console.WriteLine($"количество дней между двумя датами: {(int)Days.TotalDays}");
}
}
Введите первую дату: (ДД.ММ.ГГГГ)
12.04.1998
Введите вторую дату: (ДД.ММ.ГГГГ)
15.06.2000
количество дней между двумя датами: 795
Задание 3
using System;
using System.Reflection;
class Program
{
static void Main()
{
Console.WriteLine("Введите первую дату: (ДД.ММ.ГГГГ)");
string inputFirstDate = Console.ReadLine();
var parsedFirstDate = DateTime.Parse(inputFirstDate);
Console.WriteLine("Введите вторую дату: (ДД.ММ.ГГГГ)");
string inputSecondDate = Console.ReadLine();
var parsedSecondDate = DateTime.Parse(inputSecondDate);
TimeSpan Hours = parsedSecondDate - parsedFirstDate;
Console.WriteLine($"количество часов между двумя датами: {(int)Hours.TotalHours} ч.");
}
}
Введите первую дату: (ДД.ММ.ГГГГ)
12.04.2000
Введите вторую дату: (ДД.ММ.ГГГГ)
23.05.2006
количество часов между двумя датами: 53568 ч.
Задание 4
using System;
using System.Reflection;
class Program
{
static void Main()
{
Console.WriteLine("Введите первую дату: (ДД.ММ.ГГГГ)");
string inputFirstDate = Console.ReadLine();
var parsedFirstDate = DateTime.Parse(inputFirstDate);
Console.WriteLine("Введите вторую дату: (ДД.ММ.ГГГГ)");
string inputSecondDate = Console.ReadLine();
var parsedSecondDate = DateTime.Parse(inputSecondDate);
TimeSpan Minutes = parsedSecondDate - parsedFirstDate;
Console.WriteLine($"количество минут между двумя датами: {(int)Minutes.TotalMinutes} мин.");
}
}
Введите первую дату: (ДД.ММ.ГГГГ)
20.06.2001
Введите вторую дату: (ДД.ММ.ГГГГ)
22.07.2001
количество минут между двумя датами: 46080 мин.
Задание 5
using System;
class Program
{
static void Main()
{
Console.WriteLine("Введите год: ");
int inputYear = int.Parse(Console.ReadLine());
DateTime ITDay = new DateTime(inputYear, 1, 1).AddDays(255);
Console.WriteLine($"{ITDay.DayOfWeek}, {ITDay.ToString("d")}");
}
}
Введите год:
1999
Monday, 13.09.1999
Задание 6
using System;
class Program
{
static void Main()
{
Console.WriteLine("Введите номер дня года (1-365):");
int number;
while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 365)
{
Console.WriteLine("Некорректный ввод. Пожалуйста, введите число от 1 до 365:");
}
int year = DateTime.Now.Year;
DateTime date = new DateTime(year, 1, 1).AddDays(number - 1);
int dayOfWeekNumber = (int)date.DayOfWeek;
string dayOfWeekName = date.DayOfWeek.ToString();
Console.WriteLine($"День года: {number}");
Console.WriteLine($"Дата: {date.ToShortDateString()}");
Console.WriteLine($"Номер дня недели: {dayOfWeekNumber}");
Console.WriteLine($"Название дня недели: {dayOfWeekName}");
}
}
Введите номер дня года (1-365):
1
День года: 1
Дата: 01.01.2025
Номер дня недели: 3
Название дня недели: Wednesday
Задание 7
using System;
class Program
{
static void Main()
{
DateTime examDate = new DateTime(2025, 06, 25);
Console.WriteLine("Введите дату (ДД.ММ.ГГГГ):");
if (DateTime.TryParse(Console.ReadLine(), out DateTime inputDate))
{
int dayss = (inputDate - examDate).Days;
if (dayss < 0)
Console.WriteLine($"Осталось {-dayss} дней.");
else if (dayss > 0)
Console.WriteLine($"Прошло {dayss} дней.");
else
Console.WriteLine("Сегодня экзамен!");
}
else
{
Console.WriteLine("Некорректный ввод даты.");
}
}
}
Введите дату (ДД.ММ.ГГГГ):
03.02.2025
Осталось 142 дней.
Задание 8
using System;
class Program
{
static void Main()
{
DateTime today = DateTime.Today;
DateTime tomorrow = today.AddDays(1);
string formattedDate = tomorrow.ToString("dd.MM.yyyy");
Console.WriteLine($"Дата завтра: {formattedDate}");
}
}
Дата завтра: 04.02.2025
Задание 9
using System;
class Program
{
static void Main()
{
Console.Write("Введите день и месяц рождения в формате dd.mm: ");
string birthdayInput = Console.ReadLine();
string[] parts = birthdayInput.Split('.');
int day = int.Parse(parts[0]);
int month = int.Parse(parts[1]);
DateTime today = DateTime.Today;
DateTime birthdayThisYear = new DateTime(today.Year, month, day);
if (birthdayThisYear < today)
{
birthdayThisYear = birthdayThisYear.AddYears(1);
}
TimeSpan difference = birthdayThisYear - today;
int daysDifference = difference.Days;
if (daysDifference == 0)
{
Console.WriteLine("С днем рождения!");
}
else if (daysDifference > 0)
{
Console.WriteLine($"До дня рождения осталось {daysDifference} дней.");
}
else
{
Console.WriteLine($"После дня рождения прошло {-daysDifference} дней.");
}
}
}
Введите день и месяц рождения в формате dd.mm: 02.06
До дня рождения осталось 119 дней.
Задание 10
using System;
class Program
{
static void Main()
{
Console.Write("Введите время в формате hh:mm:ss: ");
string timeInput = Console.ReadLine();
string[] parts = timeInput.Split(':');
int hours = int.Parse(parts[0]);
int minutes = int.Parse(parts[1]);
int seconds = int.Parse(parts[2]);
int totalSeconds = hours * 3600 + minutes * 60 + seconds;
Console.WriteLine($"С начала суток прошло {totalSeconds} секунд.");
}
}
Введите время в формате hh:mm:ss: 22:34:20
С начала суток прошло 81260 секунд.
Задание 11
class Program
{
static void Main(string[] args)
{
List<DateTime> dates = new List<DateTime>()
{
new DateTime(2025, 1, 05),
new DateTime(2025, 2, 10),
new DateTime(2025, 3, 17),
new DateTime(2025, 4, 13),
new DateTime(2025, 5, 27)
};
DateTime daten = DateTime.MaxValue;
foreach (DateTime date in dates)
{
Console.WriteLine(date.ToShortDateString());
if (date >= DateTime.Today && date < daten)
{
daten = date;
}
}
Console.WriteLine("Самая ближайшая дата: " + daten.ToShortDateString());
}
}
05.01.2025
10.02.2025
17.03.2025
13.04.2025
27.05.2025
Самая ближайшая дата: 10.02.2025
Задание 12
class Program
{
static void Main()
{
List<string> birthdays = new List<string>
{
"10.05.1999", "05.02.1995", "20.06.1997", "18.07.1990", "09.01.1987", "30.08.1982"
};
var monthsCount = new int[12];
foreach (var birthday in birthdays)
{
var month = int.Parse(birthday.Split('.')[1]);
monthsCount[month - 1]++;
}
Console.WriteLine("Количество дней рождений в каждом месяце:");
for (int i = 0; i < monthsCount.Length; i++)
{
Console.WriteLine($"{i + 1}: {monthsCount[i]}");
}
}
}
Количество дней рождений в каждом месяце:
1: 1
2: 1
3: 0
4: 0
5: 1
6: 1
7: 1
8: 1
9: 0
10: 0
11: 0
12: 0
Задние 13
class Program
{
static void Main()
{
string[] dates = {
"01.01.2023",
"15.01.2023",
"20.02.2023",
"05.02.2023",
"10.03.2023",
"25.01.2023",
"30.03.2023",
"01.04.2023",
"15.04.2023",
"20.01.2023"
};
Dictionary<string, int> monthsCount = new Dictionary<string, int>();
foreach (var date in dates)
{
DateTime parsedDate = DateTime.ParseExact(date, "dd.MM.yyyy", null);
string monthName = parsedDate.ToString("MMMM");
if (monthsCount.ContainsKey(monthName))
{
monthsCount[monthName]++;
}
else
{
monthsCount[monthName] = 1;
}
}
string mostPopularMonth = null;
int maxCount = 0;
foreach (var month in monthsCount)
{
if (month.Value > maxCount)
{
maxCount = month.Value;
mostPopularMonth = month.Key;
}
}
Console.WriteLine($"Самый популярный месяц: {mostPopularMonth}");
}
}
Самый популярный месяц: январь
Задание 14
class Program
{
static void Main()
{
int[] dayCounts = new int[7];
int startYear = 1900;
int endYear = 2000;
for (int year = startYear; year <= endYear; year++)
{
for (int month = 1; month <= 12; month++)
{
DateTime date = new DateTime(year, month, 13);
int dayOfWeek = (int)date.DayOfWeek;
dayCounts[dayOfWeek]++;
}
}
Console.WriteLine("Количество 13-х чисел по дням недели:");
string[] daysOfWeek = { "Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота" };
for (int i = 0; i < dayCounts.Length; i++)
{
Console.WriteLine($"{daysOfWeek[i]}: {dayCounts[i]} раз");
}
}
}
Количество 13-х чисел по дням недели:
Воскресенье: 172 раз
Понедельник: 174 раз
Вторник: 172 раз
Среда: 174 раз
Четверг: 173 раз
Пятница: 173 раз
Суббота: 174 раз
Задание 15
class Program
{
static void Main()
{
string input = "00:00-01:00,00:30-02:30,01:00-03:00,01:30-02:00";
string[] intervals = input.Split(',');
int[] count = new int[24 * 60];
foreach (var interval in intervals)
{
string[] parts = interval.Split('-');
TimeSpan start = TimeSpan.Parse(parts[0]);
TimeSpan end = TimeSpan.Parse(parts[1]);
int startMinute = (int)start.TotalMinutes;
int endMinute = (int)end.TotalMinutes;
for (int i = startMinute; i < endMinute; i++)
{
count[i]++;
}
}
int maxCount = count.Max();
Console.WriteLine($"Максимальное количество касс: {maxCount}");
Console.WriteLine("Интервалы с максимальным количеством касс:");
for (int i = 0; i < count.Length; i++)
{
if (count[i] == maxCount)
{
TimeSpan start = TimeSpan.FromMinutes(i);
TimeSpan end = TimeSpan.FromMinutes(i + 1);
Console.WriteLine($"{start:hh\\:mm} - {end:hh\\:mm}");
}
}
}
}
Максимальное количество касс: 3
Интервалы с максимальным количеством касс:
01:30 - 01:31
01:31 - 01:32
...
02:00 - 02:01
Задание 16
class Program
{
static void Main()
{
Console.WriteLine("Введите год:");
if (int.TryParse(Console.ReadLine(), out int year))
{
int weekendCount = 0;
for (int month = 1; month <= 12; month++)
{
for (int day = 1; day <= DateTime.DaysInMonth(year, month); day++)
{
DateTime date = new DateTime(year, month, day);
if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
{
weekendCount++;
}
}
}
Console.WriteLine($"Количество выходных дней в {year} году: {weekendCount}");
}
else
{
Console.WriteLine("Некорректный ввод. Пожалуйста, введите год в числовом формате.");
}
}
}
Введите год:
2025
Количество выходных дней в 2025 году: 104