Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Dictionary<string,List<int>> grades = new Dictionary<string,List<int>>();
- grades["Peshi"] = new List<int>() {5,5,6,7,8 };
- grades["Gosho"] = new List<int>() { 5, 8 };
- grades["Kondio"] = new List<int>() { 2, 2, 3, 74, 8 };
- grades["Ivan"] = new List<int>() { 6, 6, 6, 6, 6 };
- grades["SHOSHO"] = new List<int>() { 54, 57, 86,47, 58 };
- grades.Remove("Gosho");
- if (grades.ContainsKey("Kondio"))
- {
- Console.WriteLine("Kondio ima takiva ocenki :");
- foreach (var g in grades["Kondio"])
- {
- Console.Write(g + " ");
- }
- Console.WriteLine();
- }
- else
- {
- Console.WriteLine("NQMA OCENKI");
- }
- //////////////////////////////////////////////////////////////////////
- // Create an events table: a set of pairs of (date -> event)
- Dictionary<DateTime, string> events = new Dictionary<DateTime, string>();
- // Put a few events
- events[new DateTime(1998, 9, 4)] = "Google's birth date";
- events[new DateTime(2013, 11, 5)] = "Software University's birth date";
- events[new DateTime(1975, 4, 4)] = "Microsoft's birth date";
- events[new DateTime(2004, 2, 4)] = "Facebook's birth date";
- events[new DateTime(2013, 11, 5)] =
- "Nakov left Telerik Academy to establish the Software University";
- Console.WriteLine("List of all events:");
- foreach (var entry in events)
- {
- Console.WriteLine("{0:dd-MMM-yyyy}: {1}", entry.Key, entry.Value);
- }
- Console.WriteLine();
- Console.WriteLine("List of all dates:");
- foreach (var date in events.Keys)
- {
- Console.WriteLine("{0:dd-MMM-yyyy}", date);
- }
- Console.WriteLine();
- Console.WriteLine("List of all event names:");
- foreach (var name in events.Values)
- {
- Console.WriteLine("{0}", name);
- }
- /////////////////////////////////////////////////////////////////////////////////
- // Create a phone book: a set of pairs of (person name -> phone number)
- Dictionary<string, string> phonebook = new Dictionary<string, string>()
- {
- {"Steve Ryan", "+1-555-1730"},
- {"Alex Shillds", "+1-555-1256"},
- };
- // Add a few entries in the phonebook
- phonebook["John Smith"] = "+1-555-8976";
- phonebook["Lisa Smith"] = "+1-555-1234";
- phonebook["Sam Doe"] = "+1-555-5030";
- phonebook["Nakov"] = "+359-899-555-592";
- // Print the phonebook
- foreach (var entry in phonebook)
- {
- Console.WriteLine("{0} has phone number {1}", entry.Key, entry.Value);
- }
- // Modify Nakov's number
- phonebook["Nakov"] = "+359-2-981-9819";
- // Delete an existing number
- phonebook.Remove("John Smith");
- Console.WriteLine();
- // Print the phonebook (another way)
- foreach (var name in phonebook.Keys)
- {
- Console.WriteLine("{0} --> {1}", name, phonebook[name]);
- }
- ///////////////////////////////////// counting words DICTIONARY ////////////////////////
- static void Main()
- {
- string text = "Welcome to our C# course. In this " +
- "course you will learn how to write simple " +
- "programs in C# and how to use data structures";
- Console.WriteLine("Dictionary<TKey,TValue>");
- Console.WriteLine("-----------------------");
- IDictionary<string, int> wordsCount = new Dictionary<string, int>();
- CountWords(text, wordsCount);
- Console.WriteLine();
- Console.WriteLine("SortedDictionary<TKey,TValue>");
- Console.WriteLine("-----------------------------");
- IDictionary<string, int> sortedWordsCount =
- new SortedDictionary<string, int>();
- CountWords(text, sortedWordsCount);
- }
- private static void CountWords(string text, IDictionary<string, int> wordsCount)
- {
- string[] words = text.Split(new char[] { ' ', ',', '.' },
- StringSplitOptions.RemoveEmptyEntries);
- foreach (string word in words)
- {
- int count = 1;
- if (wordsCount.ContainsKey(word))
- {
- count = wordsCount[word] + 1;
- }
- wordsCount[word] = count;
- }
- foreach (var pair in wordsCount)
- {
- Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
- }
- }
- }
- //////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
- Dictionary<string, int> studentsMarks =
- new Dictionary<string, int>();
- studentsMarks.Add("Ivan", 4);
- studentsMarks.Add("Peter", 6);
- studentsMarks.Add("Maria", 6);
- studentsMarks.Add("George", 5);
- int peterMark = studentsMarks["Peter"];
- Console.WriteLine("Peter's mark: {0}", peterMark);
- Console.WriteLine("Is Peter in the hash table: {0}",
- studentsMarks.ContainsKey("Peter"));
- studentsMarks.Remove("Peter");
- Console.WriteLine("Peter removed.");
- Console.WriteLine("Is Peter in the hash table: {0}",
- studentsMarks.ContainsKey("Peter"));
- Console.WriteLine("Ivan's mark: {0}", studentsMarks["Ivan"]);
- studentsMarks["Ivan"] = 3;
- Console.WriteLine("Ivan's mark changed.");
- // Print all elements of the hash table
- Console.WriteLine("Students and grades:");
- foreach (var studentMark in studentsMarks)
- {
- Console.WriteLine("{0} --> {1}",
- studentMark.Key, studentMark.Value);
- }
- ////////////////////////////////////////////////////////////////////////
- static Dictionary<string, List<int>> studentGrades =
- new Dictionary<string, List<int>>();
- private static void AddGrade(string name, int grade)
- {
- if (! studentGrades.ContainsKey(name))
- {
- studentGrades[name] = new List<int>();
- }
- studentGrades[name].Add(grade);
- }
- private static void PrintAllGrades()
- {
- foreach (var studentAndGrade in studentGrades)
- {
- Console.WriteLine(studentAndGrade.Key + ": ");
- foreach (var grade in studentAndGrade.Value)
- {
- Console.WriteLine("\t" + grade);
- }
- }
- }
- static void Main()
- {
- AddGrade("Nakov", 6);
- AddGrade("Nakov", 5);
- AddGrade("Maria", 3);
- AddGrade("Maria", 4);
- AddGrade("Nakov", 6);
- AddGrade("Maria", 3);
- AddGrade("Kiril", 4);
- PrintAllGrades();
- }
- /////////////////////////////////////////// izkarvane list o ocenki po4ti sushstoto kato goranata zadacha /////////////////
- static SortedDictionary<string, List<int>> grades = new SortedDictionary<string, List<int>>();
- static void Main()
- {
- grades["Peshi"] = new List<int>() { 5, 5, 6, 7, 8 };
- grades["Gosho"] = new List<int>() { 5, 8 };
- grades["Kondio"] = new List<int>() { 2, 2, 3, 74, 8 };
- grades["Ivan"] = new List<int>() { 6, 6, 6, 6, 6 };
- grades["SHOSHO"] = new List<int>() { 54, 57, 86, 47, 58 };
- foreach (KeyValuePair<string, List<int>> stud in grades)
- {
- Console.Write(stud.Key + " : ");
- foreach (var mark in stud.Value)
- {
- Console.Write(mark + " ");
- }
- Console.WriteLine();
- }
- }
- static void addmark ( string studentName , int mark )
- {
- List<int> studMarks;
- if (grades.ContainsKey(studentName))
- {
- studMarks = grades[studentName];
- }
- else
- {
- studMarks = new List<int>();
- grades[studentName] = studMarks;
- }
- studMarks.Add(mark);
- }
- ///////////////////////// broene na dumi 2 reshenie napisano s natrupvane na dumi po dr nachin i sortirane po VALUE /////
- string text = "Welcome to our C# course. In this " +
- "course you will learn how to write simple " +
- "programs in C# and how to use data structures";
- Console.WriteLine("Dictionary<TKey,TValue>");
- Console.WriteLine("-----------------------");
- IDictionary<string, int> wordsCount = new Dictionary<string, int>();
- CountWords(text, wordsCount);
- Console.WriteLine();
- Console.WriteLine("SortedDictionary<TKey,TValue>");
- Console.WriteLine("-----------------------------");
- IDictionary<string, int> sortedWordsCount =
- new SortedDictionary<string, int>();
- CountWords(text, sortedWordsCount);
- }
- private static void CountWords(string text, IDictionary<string, int> wordsCount)
- {
- string[] words = text.Split(new char[] { ' ', ',', '.' },
- StringSplitOptions.RemoveEmptyEntries);
- foreach (string word in words)
- {
- if (!wordsCount.ContainsKey(word))
- {
- wordsCount.Add(word, 1);
- }
- else
- {
- wordsCount[word]++;
- }
- }
- wordsCount = wordsCount.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
- foreach (var pair in wordsCount)
- {
- Console.WriteLine("{0} --> {1}", pair.Key, pair.Value);
- }
- /////////////////////////////// za stavnqvane na to4ki //////////////////////////////////////////////
- List<Point> points = new List<Point>();
- points.Add(new Point { X = 5, Y = 106 });
- points.Add(new Point { X = 54, Y = 105 });
- points.Add(new Point { X = 55, Y = 104 });
- points.Add(new Point { X = 56, Y = 10 });
- points.Add(new Point { X = 58, Y = 103 });
- points.Add(new Point { X = 45, Y = 103 });
- points.Add(new Point { X = 35, Y = 10 });
- points.Add(new Point { X = 85, Y = 102 });
- points.Add(new Point { X = 95, Y = 10 });
- points.Sort();
- foreach (var item in points)
- {
- Console.WriteLine( item.X + " - " + item.Y);
- }
- }
- //////////////////////////////////
- public struct Point : IComparable<Point>
- {
- public int X { get; set; }
- public int Y { get; set; }
- public int CompareTo(Point otherPoint)
- {
- if (X != otherPoint.X)
- {
- return this.X.CompareTo(otherPoint.X);
- }
- else
- {
- return this.Y.CompareTo(otherPoint.Y);
- }
- }
- }
- ///////////////////// java basic exam zadachi ///////////////////////////////////////////////////////
- ////// 3 septemvri za msecite begachite i raztoqnieto ///////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- class ActivityTracker
- {
- static void Main()
- {
- SortedDictionary<int, SortedDictionary<string, int>> dataDictionary =
- new SortedDictionary<int, SortedDictionary<string, int>>();
- int dataLinesNumber = int.Parse(Console.ReadLine());
- string lineContents = String.Empty;
- string[] lineTokens;
- int month = 0;
- string user = String.Empty;
- int distance = 0;
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ', '/' }, StringSplitOptions.RemoveEmptyEntries);
- month = int.Parse(lineTokens[1]);
- user = lineTokens[3];
- distance = int.Parse(lineTokens[4]);
- if (!dataDictionary.ContainsKey(month))
- {
- dataDictionary[month] = new SortedDictionary<string, int>();
- }
- if (!dataDictionary[month].ContainsKey(user))
- {
- dataDictionary[month][user] = distance;
- }
- else
- {
- dataDictionary[month][user] += distance;
- }
- }
- bool isFirstPair = true;
- foreach (var dataPair in dataDictionary)
- {
- Console.Write("{0}: ", dataPair.Key);
- isFirstPair = true;
- foreach (var subPair in dataPair.Value)
- {
- if (isFirstPair)
- {
- Console.Write("{0}({1})", subPair.Key, subPair.Value);
- isFirstPair = false;
- }
- else
- {
- Console.Write(", {0}({1})", subPair.Key, subPair.Value);
- }
- }
- Console.WriteLine();
- }
- }
- }
- 26 may 2014 //////////////////////////////////////////////////////////////////////
- ///// dvoiki 4isla 3 4, 4 2 , 2 3, kolko puti se povtarqt i da izkarva i procentite
- string allLangs = @"3 4 2 3 4 2 1 12 2 3 4".ToUpper();
- string[] langs = allLangs.Split(new char[] { ',', ';', ' ', '.', '!', '\'', '"', '$', '?', '+', '"', '\n', '\r' },
- StringSplitOptions.RemoveEmptyEntries);
- List<string> lettersCouples = new List<string>();
- string kor = langs[0];
- for (int i = 1; i < langs.Length; i++)
- {
- string DigitCouple = kor + " " +langs[i];
- lettersCouples.Add(DigitCouple);
- kor = langs[i];
- }
- Dictionary<string, int> dict = new Dictionary<string, int>();
- double countLetter = 0;
- foreach (var t in lettersCouples)
- {
- if (!dict.ContainsKey(t))
- {
- dict.Add(t, 1);
- countLetter++;
- }
- else
- {
- dict[t]++;
- countLetter++;
- }
- }
- List<KeyValuePair<string, int>> myList = dict.ToList();
- myList.Sort(
- delegate(KeyValuePair<string, int> firstPair,
- KeyValuePair<string, int> nextPair)
- {
- return firstPair.Value.CompareTo(nextPair.Value);
- }
- );
- myList.Reverse();
- foreach (var dr in myList)
- {
- double Procent = (dr.Value / countLetter) * 100;
- Console.WriteLine("{0,4} = {1,3} -> {2,1}>% {3:0.00}", dr.Key, dr.Value, new string('#', dr.Value), Procent);
- }
- /////////////////////// 27 may 4 zadacha ORDERS /////////////////////////////////////////////////////////////////
- SortedDictionary<string, SortedDictionary<string, int>> dataDictionary =
- new SortedDictionary<string, SortedDictionary<string, int>>();
- int dataLinesNumber = int.Parse(Console.ReadLine());
- string lineContents = String.Empty;
- string[] lineTokens;
- string fruit = "";
- string user = String.Empty;
- int kolichestvo = 0;
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- fruit = (lineTokens[2]);
- user = lineTokens[0];
- kolichestvo = int.Parse(lineTokens[1]);
- if (!dataDictionary.ContainsKey(fruit))
- {
- dataDictionary[fruit] = new SortedDictionary<string, int>();
- }
- if (!dataDictionary[fruit].ContainsKey(user))
- {
- dataDictionary[fruit][user] = kolichestvo;
- }
- else
- {
- dataDictionary[fruit][user] += kolichestvo;
- }
- }
- bool isFirstPair = true;
- foreach (var dataPair in dataDictionary)
- {
- Console.Write("{0}: ", dataPair.Key);
- isFirstPair = true;
- foreach (var subPair in dataPair.Value)
- {
- if (isFirstPair)
- {
- Console.Write("{0}({1})", subPair.Key, subPair.Value);
- isFirstPair = false;
- }
- else
- {
- Console.Write(", {0}({1})", subPair.Key, subPair.Value);
- }
- }
- Console.WriteLine();
- /////// 1 uni 192.168.0.11 peter 33 10.10.17.33 alex 12 10.10.17.35 peter 30 /////////////////////////////////
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication4
- {
- class Program
- {
- static void Main(string[] args)
- {
- SortedDictionary<string, int> dataDictionary =
- new SortedDictionary<string, int>();
- SortedDictionary<string, SortedSet<string>> dataIp =
- new SortedDictionary<string, SortedSet<string>>();
- int dataLinesNumber = int.Parse(Console.ReadLine());
- string lineContents = String.Empty;
- string[] lineTokens;
- string ip = "";
- string user = String.Empty;
- int kolichestvo = 0;
- int count = 0;
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- ip = (lineTokens[0]);
- user = lineTokens[1];
- kolichestvo = int.Parse(lineTokens[2]);
- if (!dataDictionary.ContainsKey(user))
- {
- dataDictionary[user] = kolichestvo;
- count++;
- }
- else
- {
- dataDictionary[user] += kolichestvo;
- }
- //////////////// 2 dictonary
- if (!dataIp.ContainsKey(user))
- {
- dataIp[user] = new SortedSet<string>();
- dataIp[user].Add(ip);
- }
- else
- {
- dataIp[user].Add(ip);
- }
- }
- int kondio = 0;
- bool kur = true;
- /////////////// output
- foreach (var dataPair in dataDictionary)
- {
- kur = true;
- foreach (var item in dataIp)
- {
- kondio++;
- if (kondio == 1 || kondio == 4)
- {
- Console.Write(item.Key + ": ");
- Console.Write(dataPair.Value + " ");
- Console.Write("[");
- foreach (var ink in item.Value)
- {
- if (kur)
- {
- Console.Write(ink);
- kur = false;
- }
- else
- {
- Console.Write(", " + ink);
- }
- }
- Console.Write("]");
- Console.WriteLine();
- }
- }
- }
- }
- }
- }
- 2 reshenie //////////////////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- class LogsAggregator
- {
- static void Main()
- {
- int n = int.Parse(Console.ReadLine());
- SortedDictionary<string, SortedDictionary<string, int>> dataDic =
- new SortedDictionary<string, SortedDictionary<string, int>>();
- string input = string.Empty;
- string[] inputTokens;
- string name = string.Empty;
- string ip = string.Empty;
- int number;
- for (int i = 0; i < n; i++)
- {
- input = Console.ReadLine();
- inputTokens = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- name = inputTokens[1];
- ip = inputTokens[0];
- number = int.Parse(inputTokens[2]);
- if (!dataDic.ContainsKey(name))
- {
- dataDic[name] = new SortedDictionary<string, int>();
- }
- if (!dataDic[name].ContainsKey(ip))
- {
- dataDic[name][ip] = number;
- }
- else
- {
- dataDic[name][ip] += number;
- }
- }
- //output
- foreach (var entry in dataDic)
- {
- string ips = String.Empty;
- int finalDuration = 0;
- foreach (var innnerEntry in entry.Value)
- {
- ips += innnerEntry.Key;
- ips += " ";
- finalDuration += innnerEntry.Value;
- }
- Console.WriteLine(entry.Key + ": " + finalDuration + " [" + ips.Trim().Replace(" ", ", ") + "]");
- }
- }
- }
- tui ////////////////////////////////////////////////////////////////////////////////////////
- SortedDictionary<string, List<int>> dataDictionary =
- new SortedDictionary<string, List<int>>();
- SortedDictionary<string, List<string>> dataIp =
- new SortedDictionary<string, List<string>>();
- int dataLinesNumber = int.Parse(Console.ReadLine());
- string lineContents = String.Empty;
- string[] lineTokens;
- string names = "";
- string score = String.Empty;
- int sredno = 0;
- int count = 0;
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- names = (lineTokens[0]);
- score = lineTokens[1];
- sredno = int.Parse(lineTokens[2]);
- if (!dataDictionary.ContainsKey(score))
- {
- dataDictionary[score] = new List<int>();
- dataDictionary[score].Add(sredno);
- count++;
- }
- else
- {
- dataDictionary[score].Add(sredno);
- }
- //////////////// 2 dictonary
- if (!dataIp.ContainsKey(score))
- {
- dataIp[score] = new List<string>();
- dataIp[score].Add(names);
- }
- else
- {
- dataIp[score].Add(names);
- }
- }
- int kondio = 0;
- bool kur = true;
- /////////////// output
- foreach (var dataPair in dataDictionary)
- {
- kur = true;
- foreach (var item in dataIp)
- {
- kondio++;
- if (kondio == 1 || kondio == 4)
- {
- Console.Write(item.Key + ": ");
- Console.Write(dataPair.Value + " ");
- Console.Write("[");
- foreach (var ink in item.Value)
- {
- if (kur)
- {
- Console.Write(ink);
- kur = false;
- }
- else
- {
- Console.Write(", " + ink);
- }
- }
- Console.Write("]");
- Console.WriteLine();
- }
- }
- }
- ////////////////////////////// 8 february 2015 ///////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- class NightLife
- {
- static void Main()
- {
- SortedDictionary<string, SortedDictionary<string, int>> nightLifeDictionary =
- new SortedDictionary<string, SortedDictionary<string, int>>();
- string[] eventTokens;
- string user = String.Empty;
- string ip = String.Empty;
- int broi = 0;
- string eventInformation = Console.ReadLine();
- int count = 0;
- while (eventInformation != "END")
- {
- eventTokens = eventInformation.Split(new char[] { '=', ' ' }, StringSplitOptions.RemoveEmptyEntries);
- user = eventTokens[5];
- ip = eventTokens[1];
- if (!nightLifeDictionary.ContainsKey(user))
- {
- nightLifeDictionary[user] = new SortedDictionary<string, int>();
- }
- if (!nightLifeDictionary[user].ContainsKey(ip))
- {
- count = 0;
- count = 1;
- nightLifeDictionary[user][ip] = count;
- }
- nightLifeDictionary[user][ip] = count++;
- eventInformation = Console.ReadLine();
- }
- foreach (var cityPair in nightLifeDictionary)
- {
- Console.WriteLine(cityPair.Key);
- foreach (var venuePair in cityPair.Value)
- {
- Console.WriteLine("->{0}: = {1}", venuePair.Key, String.Join(", ", venuePair.Value));
- }
- }
- }
- }
- //////////////////// 7 qnuari / Student systemi u4enici predmeti i srednite ocenki /////////////////////////////////
- using System;
- using System.Collections.Generic;
- class NightLife
- {
- static void Main()
- {
- Dictionary<string, SortedDictionary<string, List<int>>> nightLifeDictionary =
- new Dictionary<string, SortedDictionary<string, List<int>>>();
- int dataLinesNumber = int.Parse(Console.ReadLine());
- string lineContents = String.Empty;
- string[] eventTokens;
- string student = String.Empty;
- string predmet = String.Empty;
- int ocenka = 0;
- // string eventInformation = Console.ReadLine();
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- eventTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- student = (eventTokens[0]) + " " + (eventTokens[1]);
- predmet = eventTokens[2];
- ocenka = int.Parse(eventTokens[3]);
- if (!nightLifeDictionary.ContainsKey(student))
- {
- nightLifeDictionary[student] = new SortedDictionary<string, List<int>>();
- }
- if (!nightLifeDictionary[student].ContainsKey(predmet))
- {
- nightLifeDictionary[student][predmet] = new List<int>();
- }
- nightLifeDictionary[student][predmet].Add(ocenka);
- }
- /////////////// out put
- string kondio = "";
- double sum = 0;
- double count = 0;
- double avg = 0;
- bool isFirst = true;
- foreach (var cityPair in nightLifeDictionary)
- {
- isFirst = true;
- Console.Write(cityPair.Key + ": ");
- Console.Write("[");
- foreach (var venuePair in cityPair.Value)
- {
- if (isFirst)
- {
- Console.Write("{0}", venuePair.Key);
- isFirst = false;
- }
- else
- {
- Console.Write(", {0}", venuePair.Key);
- }
- count = 0;
- sum = 0;
- foreach (var item in venuePair.Value)
- {
- count++;
- sum += item;
- }
- avg = sum / count;
- if (isFirst)
- {
- Console.Write(" - {0:F2}", avg);
- isFirst = false;
- }
- else
- {
- Console.Write(" - {0:F2}", avg);
- }
- }
- Console.Write("]");
- Console.WriteLine();
- }
- }
- }
- 2 reshenie ////////////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication28
- {
- internal class Program // Nasko Lapchev
- {
- private static void Main(string[] args)
- {
- // databases
- SortedDictionary<string,
- SortedDictionary<string, List<double>>> dataDictionary =
- new SortedDictionary<string, SortedDictionary<string, List<double>>>(); // тук събираме студенти, предмети, оценки
- // тук слагаме накрая форматираните за печат резултати от събраната информация
- SortedDictionary<string, SortedSet<string>> finals = new SortedDictionary<string, SortedSet<string>>();
- //SortedDictionary<string, SortedDictionary<string, double>> dataO =
- //new SortedDictionary<string, SortedDictionary<string, double>>();
- // input
- int dataLinesNumber = int.Parse(Console.ReadLine());
- // declarations - страхотна идея - дава яснота на кода по-нататък
- string lineContents = String.Empty;
- string[] lineTokens;
- string student = "";
- string predmet = String.Empty;
- int ocenka = 0;
- // reading and parsing the lines
- // имаме 3 основни случая:
- // 1. такъв студент още не е добавян:
- // * правим List<double> за оценките му, и прибавяме оценката към този лист
- // * правим SortedDictionary<string, List<double>> studentData, и към него прибавяме предмета, и списъка с оценки (списък за да можем да прибавим и следващи оценки ако се появят
- // * чак сега вече можем да прибавим към dataDictionary.Add(student, studentData);
- // 2. Вече има такъв студент додразбира се че и SortedDictionary<string, List<double>> studentData вече има, тъй като този речник се прибавя заедно със студента),
- // но предмета е нов: правим List<double> ocenki = new List<double>();, и прибавяме dataDictionary[student].Add(predmet, ocenki);
- // 3. има такъв студент, има такъв предмет, само оценката е нова
- // тогава: dataDictionary[student][predmet].Add(ocenka);
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- student = (lineTokens[0]) + " " + (lineTokens[1]);
- predmet = lineTokens[2];
- ocenka = int.Parse(lineTokens[3]);
- if (!dataDictionary.ContainsKey(student))
- {
- // ако в речника още няма такъв студент - няма как да прибавяме към него, трябва първо да го създадем
- // същото с информацията за студента (SortedDictionary<string, List<double>> studentData) -
- // използвах твоята идея за речника предмет-оценка, но го развих в предмет-оценки: за да може в един List<double> с оценки да пълним всички оценки
- // между другото - за разлика от теб щях да се сетя че трябва оценките да са double - не по рано от 1 час селд като съм почнала да пиша кода :)
- SortedDictionary<string, List<double>> studentData = new SortedDictionary<string, List<double>>();
- List<double> ocenki = new List<double>(); // ако искаш може да смениш "ocenka/i" с grade/s
- ocenki.Add(ocenka);
- studentData.Add(predmet, ocenki);
- dataDictionary.Add(student, studentData); // чак сега вече можем да добавим нов студент в речника
- }
- else if (dataDictionary.ContainsKey(student))
- {
- if (!dataDictionary[student].ContainsKey(predmet))
- {
- //dataDictionary[student][predmet] = new List<double>(); // мисля че няма да можем да прибавим оценки ако няма такъв студент и ние още не сме го добавили
- // иначе казано, за да го има студента вече в речника, тяй е бил добавен заедно с SortedDictionary<string, List<double>> studentData, и там вече си има друг предмет, с други оценки
- // остава само да добавим във вътрешня речник studentDatа нов предмет, с оценките към него
- List<double> ocenki = new List<double>();
- ocenki.Add(ocenka);
- dataDictionary[student].Add(predmet, ocenki);
- }
- else if (dataDictionary[student].ContainsKey(predmet))
- {
- // за да го има предмета, той е бил добавен с List<double> с оценки, сега остава само да прибавим още една оценка
- dataDictionary[student][predmet].Add(ocenka);
- }
- }
- }
- // сега идеяата е точно както ти попита: да се подготвим за печатане, ще превърнем всичката информация за студента в един форматиран стринг
- foreach (var pair in dataDictionary)
- {
- SortedSet<string> infoPoPredmeti = new SortedSet<string>();
- foreach (var pair2 in pair.Value) // трябва ни само информацияята за студента, без самия студент
- {
- string predmet_srednaocenka = String.Format("{0} - {1:F2}", pair2.Key, pair2.Value.Average()); // така форматираме с колко знака след десетичната точка ще се печата средната оценка
- // и за всеки предмет ще получим нещо такова: "history – 5.00"
- infoPoPredmeti.Add(predmet_srednaocenka); // тук са събрани всички стрингове от типа "history – 5.00", за един студент само
- }
- finals.Add(pair.Key, infoPoPredmeti); // тук прибавяме студента, със съответната infoPoPredmeti
- }
- foreach (var pair in finals)
- {
- string infoZaStudenta = string.Join(", ", pair.Value);
- Console.WriteLine("{0}: [{1}]", pair.Key, infoZaStudenta);
- }
- }
- }
- }
- 3 reshenie ///////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace SchoolSystem
- {
- class Program
- {
- static void Main()
- {
- var count = int.Parse(Console.ReadLine());
- var students = new SortedDictionary<string, SortedDictionary<string, List<double>>>();
- for (int i = 0; i < count; i++)
- {
- var inputRow = Console.ReadLine();
- var student = inputRow.Split(' ');
- var fullName = student[0] + " " + student[1];
- var subject = student[2];
- var score = double.Parse(student[3]);
- if (students.ContainsKey(fullName))
- {
- if (students[fullName].ContainsKey(subject))
- {
- students[fullName][subject].Add(score);
- }
- else
- {
- var scores = new List<double>();
- scores.Add(score);
- students[fullName].Add(subject, scores);
- }
- }
- else
- {
- var scores = new List<double>();
- scores.Add(score);
- var subjects = new SortedDictionary<string, List<double>>();
- subjects.Add(subject, scores);
- students.Add(fullName, subjects);
- }
- }
- foreach (var student in students)
- {
- var sub = student.Value.Select(x=> x.Key + " - " + x.Value.Average().ToString("0.00")).Aggregate((x, y)=> x + ", " + y);
- Console.WriteLine("{0}: [{1}]", student.Key, sub);
- }
- }
- }
- }
- ////////////////////////////////////// 22 uni 3 zadacha exam score / rezultat broi studenti i sredna ocenka ///////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication4
- {
- class Program
- {
- static void Main(string[] args)
- {
- SortedDictionary<string, SortedSet<string>> dataDictionary =
- new SortedDictionary<string, SortedSet<string>>();
- SortedDictionary<string, double> dataIp =
- new SortedDictionary<string, double>();
- int dataLinesNumber = int.Parse(Console.ReadLine());
- string lineContents = String.Empty;
- string[] lineTokens;
- string stud = "";
- string ExamScore = String.Empty;
- double sredno = 0;
- int count = 0;
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- stud = (lineTokens[0]) + " " + (lineTokens[1]);
- ExamScore = lineTokens[2];
- sredno = double.Parse(lineTokens[3]);
- if (!dataDictionary.ContainsKey(ExamScore))
- {
- dataDictionary[ExamScore] = new SortedSet<string>();
- count++;
- dataDictionary[ExamScore].Add(stud);
- }
- else
- {
- dataDictionary[ExamScore].Add(stud);
- }
- //////////////// 2 dictonary
- if (!dataIp.ContainsKey(ExamScore))
- {
- dataIp[ExamScore] = sredno;
- }
- else
- {
- dataIp[ExamScore] += sredno;
- }
- }
- /////////////// output
- bool isFirstPair = true;
- double unt = 0;
- double avg = 0;
- int Index = 0;
- foreach (var dataPair in dataDictionary)
- {
- unt = 0;
- Console.Write(dataPair.Key + " -> ");
- Console.Write("[");
- isFirstPair = true;
- foreach (var ku in dataPair.Value)
- {
- if (isFirstPair)
- {
- Console.Write("{0}", ku);
- unt++;
- isFirstPair = false;
- }
- else
- {
- Console.Write(", {0}", ku);
- unt++;
- }
- }
- Console.Write("]; ");
- for (int i = Index; i < dataIp.Keys.Count - ((count-1) - Index); i++)
- {
- avg = dataIp.ElementAt(i).Value / unt;
- // Console.WriteLine(dataIp.ElementAt(i).Value);
- Console.Write("avg = {0:0.00}", avg);
- }
- Index++;
- Console.WriteLine();
- }
- }
- }
- }
- ///////////// 2 reshenie na tazi gornata zadacha / 22 uni exam score ///////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Threading;
- class ExamScore
- {
- static void Main()
- {
- Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
- string firstLine = Console.ReadLine();
- string secondLine = Console.ReadLine();
- string thirdLine = Console.ReadLine();
- SortedDictionary<int, SortedDictionary<string, double>> dataInfo = new SortedDictionary<int, SortedDictionary<string, double>>();
- string inputLine = String.Empty;
- string[] inputTokens;
- int examScore = 0;
- string name = String.Empty;
- double grade = 0;
- while (true)
- {
- inputLine = Console.ReadLine();
- inputTokens = inputLine.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
- if (inputTokens.Length < 3)
- {
- break;
- }
- name = inputTokens[0].Trim();
- examScore = int.Parse(inputTokens[1].Trim());
- Console.WriteLine(inputTokens[2].Trim());
- string number = inputTokens[2].Trim();
- grade = double.Parse(number);
- if (!dataInfo.ContainsKey(examScore))
- {
- dataInfo.Add(examScore, new SortedDictionary<string, double>());
- }
- dataInfo[examScore].Add(name, grade);
- }
- foreach (var currentExamScore in dataInfo)
- {
- Console.WriteLine("{0} -> [{1}]; avg={2:F2}", currentExamScore.Key, String.Join(", ", currentExamScore.Value.Keys), currentExamScore.Value.Values.Average());
- }
- }
- }
- 21 septemvri EVEning 04.Ofisse stufff //////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApplication28
- {
- internal class Program // Nasko Lapchev
- {
- private static void Main(string[] args)
- {
- // databases
- SortedDictionary<string,
- Dictionary<string, List<double>>> dataDictionary =
- new SortedDictionary<string, Dictionary<string, List<double>>>(); // тук събираме студенти, предмети, оценки
- // тук слагаме накрая форматираните за печат резултати от събраната информация
- Dictionary<string, HashSet<string>> finals = new Dictionary<string, HashSet<string>>();
- //SortedDictionary<string, SortedDictionary<string, double>> dataO =
- //new SortedDictionary<string, SortedDictionary<string, double>>();
- // input
- int dataLinesNumber = int.Parse(Console.ReadLine());
- // declarations - страхотна идея - дава яснота на кода по-нататък
- string lineContents = String.Empty;
- string[] lineTokens;
- string student = "";
- string predmet = String.Empty;
- int ocenka = 0;
- // reading and parsing the lines
- // имаме 3 основни случая:
- // 1. такъв студент още не е добавян:
- // * правим List<double> за оценките му, и прибавяме оценката към този лист
- // * правим SortedDictionary<string, List<double>> studentData, и към него прибавяме предмета, и списъка с оценки (списък за да можем да прибавим и следващи оценки ако се появят
- // * чак сега вече можем да прибавим към dataDictionary.Add(student, studentData);
- // 2. Вече има такъв студент додразбира се че и SortedDictionary<string, List<double>> studentData вече има, тъй като този речник се прибавя заедно със студента),
- // но предмета е нов: правим List<double> ocenki = new List<double>();, и прибавяме dataDictionary[student].Add(predmet, ocenki);
- // 3. има такъв студент, има такъв предмет, само оценката е нова
- // тогава: dataDictionary[student][predmet].Add(ocenka);
- for (int i = 0; i < dataLinesNumber; i++)
- {
- lineContents = Console.ReadLine();
- lineTokens = lineContents.Split(new char[] { ' ', '|', '-' }, StringSplitOptions.RemoveEmptyEntries);
- student = lineTokens[0];
- predmet = lineTokens[2];
- ocenka = int.Parse(lineTokens[1]);
- if (!dataDictionary.ContainsKey(student))
- {
- // ако в речника още няма такъв студент - няма как да прибавяме към него, трябва първо да го създадем
- // същото с информацията за студента (SortedDictionary<string, List<double>> studentData) -
- // използвах твоята идея за речника предмет-оценка, но го развих в предмет-оценки: за да може в един List<double> с оценки да пълним всички оценки
- // между другото - за разлика от теб щях да се сетя че трябва оценките да са double - не по рано от 1 час селд като съм почнала да пиша кода :)
- Dictionary<string, List<double>> studentData = new Dictionary<string, List<double>>();
- List<double> ocenki = new List<double>(); // ако искаш може да смениш "ocenka/i" с grade/s
- ocenki.Add(ocenka);
- studentData.Add(predmet, ocenki);
- dataDictionary.Add(student, studentData); // чак сега вече можем да добавим нов студент в речника
- }
- else if (dataDictionary.ContainsKey(student))
- {
- if (!dataDictionary[student].ContainsKey(predmet))
- {
- //dataDictionary[student][predmet] = new List<double>(); // мисля че няма да можем да прибавим оценки ако няма такъв студент и ние още не сме го добавили
- // иначе казано, за да го има студента вече в речника, тяй е бил добавен заедно с SortedDictionary<string, List<double>> studentData, и там вече си има друг предмет, с други оценки
- // остава само да добавим във вътрешня речник studentDatа нов предмет, с оценките към него
- List<double> ocenki = new List<double>();
- ocenki.Add(ocenka);
- dataDictionary[student].Add(predmet, ocenki);
- }
- else if (dataDictionary[student].ContainsKey(predmet))
- {
- // за да го има предмета, той е бил добавен с List<double> с оценки, сега остава само да прибавим още една оценка
- dataDictionary[student][predmet].Add(ocenka);
- }
- }
- }
- // сега идеяата е точно както ти попита: да се подготвим за печатане, ще превърнем всичката информация за студента в един форматиран стринг
- foreach (var pair in dataDictionary)
- {
- HashSet<string> infoPoPredmeti = new HashSet<string>();
- foreach (var pair2 in pair.Value) // трябва ни само информацияята за студента, без самия студент
- {
- string predmet_srednaocenka = String.Format("{1:F2}-{0}", pair2.Value.Sum(), pair2.Key); // така форматираме с колко знака след десетичната точка ще се печата средната оценка
- // и за всеки предмет ще получим нещо такова: "history – 5.00"
- infoPoPredmeti.Add(predmet_srednaocenka); // тук са събрани всички стрингове от типа "history – 5.00", за един студент само
- }
- finals.Add(pair.Key, infoPoPredmeti); // тук прибавяме студента, със съответната infoPoPredmeti
- }
- foreach (var pair in finals)
- {
- string infoZaStudenta = string.Join(", ", pair.Value);
- Console.WriteLine("{0}: {1}", pair.Key, infoZaStudenta);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement