Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

ЛР3 / Лаб. 3 C# (Вариант 1)

.docx
Скачиваний:
6
Добавлен:
31.08.2024
Размер:
26.88 Кб
Скачать

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

delegate KeyValuePair<TKey, TValue> GenerateElement<TKey, TValue>(int j);

delegate TKey KeySelector<TKey>(Student st);

interface IDateAndCopy

{

object DeepCopy();

DateTime Date { get; set; }

}

class Person : IDateAndCopy

{

protected string name;

protected string surname;

protected DateTime dateOfBirth;

public Person(string name, string surname, DateTime dateOfBirth)

{

this.name = name;

this.surname = surname;

this.dateOfBirth = dateOfBirth;

}

public Person()

{

name = "Name";

surname = "Surname";

dateOfBirth = DateTime.Today;

}

public string Name

{

get

{

return name;

}

set

{

name = value;

}

}

public string Surname

{

get

{

return surname;

}

set

{

surname = value;

}

}

public DateTime Date

{

get

{

return dateOfBirth;

}

set

{

dateOfBirth = value;

}

}

public int YearOfBirth

{

get

{

return dateOfBirth.Year;

}

set

{

dateOfBirth = new DateTime(value, dateOfBirth.Month, dateOfBirth.Day);

}

}

public override string ToString()

{

return $"Фамилия, имя: {surname} {name}\nДата рождения: {dateOfBirth.ToShortDateString()}";

}

public virtual object DeepCopy()

{

Person human = new Person();

human.name = name;

human.surname = surname;

human.dateOfBirth = dateOfBirth;

return human;

}

}

enum Education

{

Specialist,

Bachelor,

SecondEducation

}

class Exam : IComparable, IComparer<Exam>

{

public string subject { get; set; }

public int grade { get; set; }

public DateTime examDate { get; set; }

public Exam(string subject, int grade, DateTime examDate)

{

this.subject = subject;

this.grade = grade;

this.examDate = examDate;

}

public Exam()

{

subject = "Subject";

grade = 0;

examDate = DateTime.Today;

}

public override string ToString()

{

return $"Предмет: {subject}, Оценка: {grade}, Дата экзамена: {examDate.ToShortDateString()}";

}

// сравнивает текущий экземпляр класса Exam с переданным объектом

public int CompareTo(object obj)

{

Exam anotherSubject = obj as Exam;

return subject.CompareTo(anotherSubject.subject);

}

// сравнивает два экземпляра класса Exam на основе их оценки

public int Compare(Exam gradeOne, Exam gradeTwo)

{

if (gradeOne.grade > gradeTwo.grade)

return 1;

if (gradeOne.grade < gradeTwo.grade)

return -1;

else

return 0;

}

}

// сравнивает два экземпляра класса Exam на основе их даты экзамена

class ExamDateCompare : IComparer<Exam>

{

public int Compare(Exam dateOne, Exam dateTwo)

{

if (dateOne.examDate > dateTwo.examDate)

return 1;

if (dateOne.examDate < dateTwo.examDate)

return -1;

else

return 0;

}

}

class Student : Person, IDateAndCopy, IEnumerable

{

Education formOfEducation;

int groupNumber;

List<Test> tests;

List<Exam> exams;

public Student(Person human, Education formOfEducation, int groupNumber)

{

this.Name = human.Name;

this.Surname = human.Surname;

this.Date = human.Date;

this.formOfEducation = formOfEducation;

this.groupNumber = groupNumber;

tests = new List<Test>();

exams = new List<Exam>();

}

public Student()

{

//Person human = new Person();

formOfEducation = Education.Bachelor;

groupNumber = 0;

tests = new List<Test>();

exams = new List<Exam>();

}

public Person StudentData

{

get

{

return new Person(this.Name, this.Surname, this.Date);

}

set

{

this.Name = value.Name; this.Surname = value.Surname; this.Date = value.Date;

}

}

public double AverageGrade

{

get

{

if (exams.Count == 0)

{

return 0;

}

double sum = 0;

foreach (Exam exam in exams)

{

sum += exam.grade;

}

return sum / exams.Count;

}

}

public Education FormOfEducation

{

get

{

return formOfEducation;

}

set

{

formOfEducation = value;

}

}

public int GroupNumber

{

get

{

return groupNumber;

}

set

{

if (value <= 100 || value > 599)

{

throw new ArgumentOutOfRangeException("Номер группы должен быть в диапазоне от 101 до 599");

}

else

{

groupNumber = value;

}

}

}

public List<Exam> Exams

{

get

{

return exams;

}

set

{

exams.AddRange(value);

}

}

public List<Test> Tests

{

get

{

return tests;

}

set

{

tests.AddRange(value);

}

}

public void AddExams(params Exam[] newExams)

{

foreach (Exam exam in newExams)

{

exams.Add(exam);

}

}

public void AddTests(params Test[] newTests)

{

foreach (Test test in newTests)

{

tests.Add(test);

}

}

public override string ToString()

{

Console.WriteLine($"Студент:\n{name} {surname} {dateOfBirth},\nОбразование: {formOfEducation},\nНомер группы: {groupNumber},\nЭкзамены: ");

for (int i = 0; i < exams.Count; i++)

{

Console.WriteLine(exams[i]);

}

Console.WriteLine("Зачёты: ");

for (int i = 0; i < tests.Count; i++)

{

Console.WriteLine(tests[i]);

}

return " ";

}

public virtual string ToShortString()

{

return $"Студент:\n{name} {surname} {dateOfBirth},\nОбразование: {formOfEducation},\nНомер группы: {groupNumber},\nСредний балл: {AverageGrade}\n";

}

public override object DeepCopy()

{

Student human = new Student();

human.name = name;

human.surname = surname;

human.dateOfBirth = dateOfBirth;

human.formOfEducation = formOfEducation;

human.groupNumber = groupNumber;

foreach (Exam exam in this.exams)

{

human.Exams.Add(exam);

}

foreach (Test test in this.tests)

{

human.Tests.Add(test);

}

return human;

}

// перебор всех зачётов и экзаменов

public IEnumerable TestExam()

{

foreach (Test test in this.tests)

{

yield return test;

}

foreach (Exam exam in this.exams)

{

yield return exam;

}

}

public IEnumerable GetExams(int grade)

{

foreach (Exam exam in exams)

{

if (exam.grade > grade)

{

yield return exam;

}

}

}

public IEnumerator GetEnumerator()

{

return new StudentEnumerator(exams, tests);

}

public IEnumerable ExamTestDone()

{

foreach (Exam exam in this.GetExams(2))

{

yield return exam;

}

foreach (Test test in this.tests)

{

if (test.status == true)

{

yield return test;

}

}

}

public IEnumerable TestWithExamDone()

{

foreach (Test test in this.tests)

{

if (test.status == true)

{

foreach (Exam exam in this.GetExams(2))

{

if (test.subject == exam.subject)

{

yield return test;

}

}

}

}

}

public void sortingSubject()

{

exams.Sort();

}

public void sortingGrade()

{

IComparer<Exam> grade = new Exam();

exams.Sort(grade);

}

public void sortingDate()

{

IComparer<Exam> date = new ExamDateCompare();

exams.Sort(date);

}

}

class StudentEnumerator : IEnumerator

{

List<Exam> exams;

List<Test> tests;

int index;

public StudentEnumerator(List<Exam> exams, List<Test> tests)

{

this.exams = exams;

this.tests = tests;

index = -1;

}

public object Current

{

get

{

return exams[index];

}

}

public bool MoveNext()

{

for (int i = index + 1; i < exams.Count; i++)

{

foreach (var test in tests)

{

if (((Test)test).subject == ((Exam)exams[i]).subject)

{

index = i;

return true;

}

}

}

return false;

}

public void Reset()

{

index = -1;

}

}

// коллекция студентов

class StudentCollection<TKey>

{

private Dictionary<TKey, Student> studentDict;

private KeySelector<TKey> tKey; // выбор ключа

public StudentCollection(KeySelector<TKey> tKey)

{

studentDict = new Dictionary<TKey, Student>();

this.tKey = tKey;

}

public void AddDefaults()

{

Student student = new Student();

TKey key = tKey(student);

studentDict.Add(key, student);

}

//добавление одного или несколько студентов в словаь

public void AddStudents(params Student[] students)

{

foreach (Student student in students)

{

TKey key = tKey(student);

studentDict.Add(key, student);

}

}

public override string ToString()

{

foreach (var student in studentDict)

{

Console.WriteLine("Key: " + student.Key.ToString());

Console.WriteLine(student.Value.ToString());

}

return " ";

}

public string ToShortString()

{

foreach (var student in studentDict)

{

Console.WriteLine("Key: " + student.Key.ToString());

Console.WriteLine(student.Value.ToShortString());

}

return " ";

}

// максимальный средний балл среди всех студентов

public double MaxAverage

{

get

{

if (studentDict.Count > 0)

{

return studentDict.Values.Max(max => max.AverageGrade);

}

return 0;

}

}

// возвращает элементы, содержащие переданную форму образования

public IEnumerable<KeyValuePair<TKey, Student>> EducationForm(Education value)

{

return studentDict.Where(form => form.Value.FormOfEducation == value);

}

// группировка элементов по форме обучения

public IEnumerable<IGrouping<Education, KeyValuePair<TKey, Student>>> GroupEducation

{

get

{

return studentDict.GroupBy(form => form.Value.FormOfEducation);

}

}

}

class Test

{

public string subject { get; set; }

public bool status { get; set; }

public Test(string subject, bool status)

{

this.subject = subject;

this.status = status;

}

public Test()

{

subject = "Subject";

status = true;

}

public override string ToString()

{

return $"Предмет: {subject}, Зачёт: {status}";

}

}

class TestCollections<TKey, TValue>

{

private List<TKey> tKeyList = new List<TKey>();

private List<string> stringList = new List<string>();

private Dictionary<TKey, TValue> tKeyDict = new Dictionary<TKey, TValue>();

private Dictionary<string, TValue> stringDict = new Dictionary<string, TValue>();

private GenerateElement<TKey, TValue> generateElement;

/*

public TestCollections()

{

tKeyList = new List<TKey>();

stringList = new List<string>();

tKeyDict = new Dictionary<TKey, TValue>();

stringDict = new Dictionary<string, TValue>();

}

*/

public TestCollections(int number, GenerateElement<TKey, TValue> method)

{

generateElement = method;

for (int i = 0; i < number; i++)

{

var element = generateElement(i); //Для каждого индекса вызывается делегат generateElement, который генерирует ключ и значение элемента

tKeyList.Add(element.Key);

stringList.Add(element.Key.ToString());

tKeyDict.Add(element.Key, element.Value);

stringDict.Add(element.Key.ToString(), element.Value);

}

}

public void searchTimeTKeyList()

{

var first = tKeyList[0];

var centeral = tKeyList[tKeyList.Count / 2];

var last = tKeyList[tKeyList.Count - 1];

var notBelonging = generateElement(tKeyList.Count * 2).Key;

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

Console.WriteLine("---Время для List<TKey >---");

watch.Start();

tKeyList.Contains(first);

watch.Stop();

Console.WriteLine("Время для первого элемента: " + watch.Elapsed);

watch.Restart();

tKeyList.Contains(centeral);

watch.Stop();

Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);

watch.Restart();

tKeyList.Contains(last);

watch.Stop();

Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);

watch.Restart();

tKeyList.Contains(notBelonging);

watch.Stop();

Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");

}

public void searchTimeStringList()

{

var first = stringList[0];

var centeral = stringList[stringList.Count / 2];

var last = stringList[stringList.Count - 1];

var notBelonging = generateElement(stringList.Count * 2).Key.ToString();

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

Console.WriteLine("---Время для List<string >---");

watch.Start();

stringList.Contains(first);

watch.Stop();

Console.WriteLine("Время для первого элемента: " + watch.Elapsed);

watch.Restart();

stringList.Contains(centeral);

watch.Stop();

Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);

watch.Restart();

stringList.Contains(last);

watch.Stop();

Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);

watch.Restart();

stringList.Contains(notBelonging);

watch.Stop();

Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");

}

public void searchTimeTKeyDictKey()

{

var first = tKeyDict.ElementAt(0).Key;

var centeral = tKeyDict.ElementAt(tKeyDict.Count / 2).Key;

var last = tKeyDict.ElementAt(tKeyDict.Count - 1).Key;

var notBelonging = generateElement(tKeyDict.Count * 2).Key;

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

Console.WriteLine("---Время по ключу для Dictionary< TKey, TValue >---");

watch.Start();

tKeyDict.ContainsKey(first);

watch.Stop();

Console.WriteLine("Время для первого элемента: " + watch.Elapsed);

watch.Restart();

tKeyDict.ContainsKey(centeral);

watch.Stop();

Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);

watch.Restart();

tKeyDict.ContainsKey(last);

watch.Stop();

Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);

watch.Restart();

tKeyDict.ContainsKey(notBelonging);

watch.Stop();

Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");

}

public void searchTimeStringDictKey()

{

var first = stringDict.ElementAt(0).Key;

var centeral = stringDict.ElementAt(stringDict.Count / 2).Key;

var last = stringDict.ElementAt(stringDict.Count - 1).Key;

var notBelonging = generateElement(stringDict.Count * 2).Key.ToString();

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

Console.WriteLine("---Время по ключу для Dictionary< string, TValue >---");

watch.Start();

stringDict.ContainsKey(first);

watch.Stop();

Console.WriteLine("Время для первого элемента: " + watch.Elapsed);

watch.Restart();

stringDict.ContainsKey(centeral);

watch.Stop();

Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);

watch.Restart();

stringDict.ContainsKey(last);

watch.Stop();

Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);

watch.Restart();

stringDict.ContainsKey(notBelonging);

watch.Stop();

Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");

}

public void searchTimeTKeyDictValue()

{

var first = tKeyDict.ElementAt(0).Value;

var centeral = tKeyDict.ElementAt(tKeyDict.Count / 2).Value;

var last = tKeyDict.ElementAt(tKeyDict.Count - 1).Value;

var notBelonging = generateElement(tKeyDict.Count * 2).Value;

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

Console.WriteLine("---Время по значению для Dictionary< TKey, TValue >---");

watch.Start();

tKeyDict.ContainsValue(first);

watch.Stop();

Console.WriteLine("Время для первого элемента: " + watch.Elapsed);

watch.Restart();

tKeyDict.ContainsValue(centeral);

watch.Stop();

Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);

watch.Restart();

tKeyDict.ContainsValue(last);

watch.Stop();

Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);

watch.Restart();

tKeyDict.ContainsValue(notBelonging);

watch.Stop();

Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");

}

public void searchTimeStringDictValue()

{

var first = stringDict.ElementAt(0).Value;

var centeral = stringDict.ElementAt(stringDict.Count / 2).Value;

var last = stringDict.ElementAt(stringDict.Count - 1).Value;

var notBelonging = generateElement(stringDict.Count * 2).Value;

System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

Console.WriteLine("---Время по значению для Dictionary< string, TValue >---");

watch.Start();

stringDict.ContainsValue(first);

watch.Stop();

Console.WriteLine("Время для первого элемента: " + watch.Elapsed);

watch.Restart();

stringDict.ContainsValue(centeral);

watch.Stop();

Console.WriteLine("Время для центрального элемента: " + watch.Elapsed);

watch.Restart();

stringDict.ContainsValue(last);

watch.Stop();

Console.WriteLine("Время для последнего элемента: " + watch.Elapsed);

watch.Restart();

stringDict.ContainsValue(notBelonging);

watch.Stop();

Console.WriteLine("Врамя для элемента, не входящего в коллекцию: " + watch.Elapsed + "\n");

}

}

namespace LAB_2_PROVERKA

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("---№1---");

Student studentOne = new Student(new Person("Alex", "Dark", new DateTime(2004, 4, 12)), Education.Bachelor, 200);

studentOne.AddExams(new Exam("Физика", 4, new DateTime(2022, 6, 16)), new Exam("ЭВМ", 5, new DateTime(2022, 6, 20)), new Exam("Java", 3, new DateTime(2022, 6, 16)), new Exam("C#", 4, new DateTime(2022, 7, 3)));

studentOne.AddTests(new Test("ЭВМ", true), new Test("Английский язык", false), new Test("Python", true));

Console.WriteLine("\nБез сортировки:");

Console.WriteLine(studentOne.ToString());

Console.WriteLine("\nСортировка по названию предмета:");

studentOne.sortingSubject();

Console.WriteLine(studentOne.ToString());

Console.WriteLine("\nСортировка по оценке:");

studentOne.sortingGrade();

Console.WriteLine(studentOne.ToString());

Console.WriteLine("\nСортировка по дате:");

studentOne.sortingDate();

Console.WriteLine(studentOne.ToString());

Console.WriteLine("\n---№2---");

KeySelector<string> keySelector = delegate (Student student)

{

return student.Exams.GetHashCode().ToString();

};

Student studentTwo = new Student(new Person("Will", "White", new DateTime(2002, 11, 4)), Education.Specialist, 250);

studentTwo.AddExams(new Exam("Алгебра", 3, new DateTime(2022, 7, 6)), new Exam("ЭВМ", 5, new DateTime(2022, 6, 20)), new Exam("Электротехника", 3, new DateTime(2022, 6, 23)));

studentTwo.AddTests(new Test("ЭВМ", false), new Test("Информатика", true), new Test("ООП", true));

Student studentThree = new Student(new Person("Anna", "Green", new DateTime(2003, 11, 17)), Education.Bachelor, 217);

studentThree.AddExams(new Exam("Математика", 4, new DateTime(2022, 6, 26)), new Exam("ЭВМ", 5, new DateTime(2022, 6, 20)));

studentThree.AddTests(new Test("Python", true), new Test("Информатика", true), new Test("ООП", false));

var studentCollection = new StudentCollection<string>(keySelector);

studentCollection.AddStudents(studentOne, studentTwo, studentThree);

Console.WriteLine(studentCollection.ToString());

Console.WriteLine("\n---№3---");

Console.WriteLine("Максимальный средний балл среди студентов: " + studentCollection.MaxAverage);

Console.WriteLine("\nСтуденты с заданной формой обучения:");

foreach (var education in studentCollection.EducationForm(Education.Bachelor))

Console.WriteLine(education.ToString() + "\n");

Console.WriteLine("\nГруппировка элементов коллекции по форме обучения: ");

foreach (var student in studentCollection.GroupEducation)

{

Console.WriteLine(student.Key + ":\n");

foreach (var information in student)

Console.WriteLine(information + "\n");

}

Console.WriteLine("\n---№4---");

GenerateElement<Person, Student> test = delegate (int number)

{

var key = new Person("Студент", "Номер: " + number, new DateTime(2000+number, 1, 1));

var value = new Student(key, Education.Bachelor, 100 + number);

return new KeyValuePair<Person, Student>(key, value);

};

int count = 1;

int flag = 1;

while (flag == 1)

{

try

{

count = Convert.ToInt32(Console.ReadLine());

if (count < 1)

{

Console.WriteLine("Невозможное число!");

continue;

}

flag = 0;

}

catch

{

Console.WriteLine("Введено не число!");

}

}

var testTime = new TestCollections<Person, Student>(count, test);

testTime.searchTimeTKeyList();

testTime.searchTimeStringList();

testTime.searchTimeTKeyDictKey();

testTime.searchTimeStringDictKey();

testTime.searchTimeTKeyDictValue();

testTime.searchTimeStringDictValue();

Console.ReadKey();

}

}

}

Соседние файлы в папке ЛР3