Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///////////////////////////////////// Java Basics Exam 3 September 2014 ///////////////////////////////////////////////////////////
- 01. Dozen Eggs/////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string lineContents = String.Empty;
- string[] eventTokens;
- string[] STRnumbers1;
- string kor = "";
- int hoi = 0;
- int sumEggs = 0;
- for (int i = 0; i < 7; i++)
- {
- lineContents = Console.ReadLine();
- eventTokens = lineContents.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- hoi = int.Parse(eventTokens[0]);
- kor = eventTokens[1];
- if (kor.Equals("eggs"))
- {
- sumEggs += hoi;
- }
- else if (kor.Equals("dozens"))
- {
- sumEggs += hoi * 12;
- }
- }
- int kondio = sumEggs / 12;
- int kila = sumEggs % 12;
- Console.WriteLine("{0} dozens + {1} eggs", kondio, kila);
- }
- }
- }
- 03. Biggest 3 Prime Numbers /////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- class Program
- {
- static void Main(string[] args)
- {
- string input = Console.ReadLine();
- string[] inputTokens = input.Split(new char[] { ' ', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);
- int[] numbers = inputTokens.Select(int.Parse).ToArray(); // converting string to int[];
- List<int> primes = new List<int>(); // Collecting prime numbers
- for (int i = 0; i < numbers.Length; i++)
- {
- if (isPrime(numbers[i]))
- {
- primes.Add(numbers[i]);
- }
- }
- primes.Sort();
- int index = 0;
- while (index < primes.Count - 1) // remove repeating numbers
- {
- if (primes[index] == primes[index + 1])
- primes.RemoveAt(index);
- else
- index++;
- }
- primes.Reverse();
- //foreach (var item in primes)
- //{
- // Console.WriteLine(item);
- //}
- for (int i = 0; i < primes.Count; i++)
- {
- if (primes.Count < 3)
- {
- Console.WriteLine("No");
- break;
- }
- else
- {
- Console.WriteLine(primes[0] + primes[1] + primes[2]);
- break;
- }
- }
- }
- public static bool isPrime(int number)
- {
- if ((number & 1) == 0)
- {
- if (number == 2)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- // Note:
- // ... This version was changed to test the square.
- // ... Original version tested against the square root.
- // ... Also we exclude 1 at the end.
- for (int i = 3; (i * i) <= number; i += 2)
- {
- if ((number % i) == 0)
- {
- return false;
- }
- }
- return number != 1;
- }
- }
- ////////////////////////////////////////////// 04. Activity Tracker ///////////////////////////////////////////////////////////
- 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();
- }
- }
- }
- ///////////////////////////////////////////////////////// Java Basics Exam 26 May 2014 //////////////////////////////////////////
- 04 zadacha Couples Frequency /////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- public class CouplesFrequency
- {
- public static void Main()
- {
- int[] numbers = Console.ReadLine()
- .Split()
- .Select(int.Parse)
- .ToArray();
- int totalNumberOfCouples = numbers.Length - 1;
- var coupleFrequencies = new Dictionary<string, int>();
- for (int i = 1; i < numbers.Length; i++)
- {
- string currentCouple = string.Format(
- "{0} {1}",
- numbers[i - 1],
- numbers[i]);
- if (!coupleFrequencies.ContainsKey(currentCouple))
- {
- coupleFrequencies.Add(currentCouple, 0);
- }
- coupleFrequencies[currentCouple]++;
- }
- foreach (var coupleFrequency in coupleFrequencies)
- {
- double frequency = coupleFrequency.Value * 100.0 / totalNumberOfCouples;
- Console.WriteLine(
- "{0} -> {1:F2}%",
- coupleFrequency.Key,
- frequency);
- }
- }
- }
- 03 zadacha Largest 3 Rectangles ////////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ','X','[',']','x' }, StringSplitOptions.RemoveEmptyEntries);
- int[] nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- List<int> listOfStrings = new List<int>();
- for (int i = 0; i < nums.Length; i += 2)
- {
- int hoi = nums[i] * nums[i + 1];
- listOfStrings.Add(hoi);
- }
- int sum = 0;
- int bestSum = 0;
- for (int i = 0; i < listOfStrings.Count-2; i++)
- {
- sum = 0;
- for (int j = i; j < 3 + i; j++)
- {
- sum += listOfStrings[j];
- }
- if (sum > bestSum)
- {
- bestSum = sum;
- }
- }
- Console.WriteLine(bestSum);
- }
- }
- }
- ////////////////////////////////////////// Java Basics Exam 27 May 2014 ////////////////////////////////////////////////////
- 04 zadacha ORDERS ///////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication2
- {
- class Program
- {
- static void Main(string[] args)
- {
- Dictionary<string, SortedDictionary<string, int>> dataDictionary =
- new Dictionary<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();
- }
- }
- }
- }
- 03 zadacha Longest Odd-Even Sequence ////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- using System.Text;
- class UseYourChainsBuddy
- {
- static void Main(string[] args)
- {
- string[] STRnumbers = Console.ReadLine().Split(new char[] { ' ','(',')' }, StringSplitOptions.RemoveEmptyEntries);
- int[] nums = Array.ConvertAll<string, int>(STRnumbers, int.Parse);
- int count = 0;
- int bestLen = 0;
- int len = 0;
- bool shouldBeOdd = (nums[0] % 2 != 0);
- for (int i = 0; i < nums.Length; i++)
- {
- bool isOdd = nums[i] % 2 != 0;
- if (isOdd == shouldBeOdd || nums[i] == 0) {
- len++;
- } else {
- shouldBeOdd = isOdd;
- len = 1;
- }
- shouldBeOdd = !shouldBeOdd;
- if (len > bestLen) {
- bestLen = len;
- }
- }
- Console.WriteLine(bestLen);
- }
- }
- //////////////////////////Java Basics Exam 1 June 2014 //////////////////////////////////////////////////////////////////////
- 03 zadacha Simple Expression /////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Collections;
- using System.Text.RegularExpressions;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string text = Console.ReadLine();
- string regex = @"\+|\-";
- // Stack words = new Stack();
- Queue separators = new Queue();
- Queue digits = new Queue();
- string[] wordsInSentence = Regex.Split(text, regex);
- foreach (var w in wordsInSentence)
- {
- digits.Enqueue(w.Trim());
- }
- MatchCollection separatorsInSentance = Regex.Matches(text, regex);
- foreach (var s in separatorsInSentance)
- {
- separators.Enqueue(s);
- }
- StringBuilder reversSentance = new StringBuilder();
- while (digits.Count > 0 || separators.Count > 0)
- {
- reversSentance.Append(digits.Dequeue());
- if (digits.Count == 0)
- {
- continue;
- }
- reversSentance.Append(" ");
- reversSentance.Append(separators.Dequeue());
- }
- string builder = reversSentance.ToString();
- string[] STRnumbers = builder.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- // int[] array = new int[STRnumbers.Length];
- // decimal[] array = Array.ConvertAll<string, decimal>(STRnumbers, decimal.Parse);
- // decimal sum = array.Sum();
- // Console.WriteLine("{0:F9}",sum);
- List<string> hoi = new List<string>();
- // listofIDs.Select(int.Parse).ToList()
- hoi.Add(STRnumbers[0]);
- string currvalue = STRnumbers[0];
- for (int i = 1; i < STRnumbers.Length; i++)
- {
- hoi.Add(STRnumbers[i]);
- }
- decimal total = hoi.Sum(x => Convert.ToDecimal(x));
- // hoi.select(int.parse).tolist();
- // ;
- Console.WriteLine("{0:F9}",total);
- }
- }
- }
- 04 zadacha Logs Aggregator ///////////////////////////////////////////////////////////////////////////////////////////
- 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(" ", ", ") + "]");
- }
- }
- }
- /////////////////////////////////// Java Basics - 22 uni ///////////////////////////////////////////////////////////////////////
- using System;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Collections.Generic;
- public class LittleJohn
- {
- public static void Main()
- {
- string STRnumbers = Console.ReadLine();
- string regex = @"[a-zA-Z]*";
- MatchCollection separatorsInSentance = Regex.Matches(STRnumbers, regex);
- List<string> words = new List<string>();
- foreach (var w in separatorsInSentance)
- {
- if (w.ToString() != "")
- {
- words.Add(w.ToString());
- }
- }
- HashSet<string> cognateWords = new HashSet<string>();
- for (int a = 0; a < words.Count; a++)
- {
- for (int b = 0; b < words.Count; b++)
- {
- for (int c = 0; c < words.Count; c++)
- {
- // Check if a!=b and a|b=c
- if (a != b)
- {
- bool check = (words[a].ToString() + words[b].ToString()).Equals(words[c].ToString());
- if (check)
- {
- cognateWords.Add(words[a].ToString() + "|" + words[b].ToString() + "=" + words[c].ToString());
- }
- }
- }
- }
- }
- if (cognateWords.Count == 0)
- {
- Console.WriteLine("No");
- }
- else
- {
- int i = 0;
- foreach (var item in cognateWords)
- {
- Console.WriteLine(item);
- }
- }
- }
- }
- ////////////////////////////// Java Basics - 21 Sept 2014 Evening ////////////////////////////////////////////////////////////////////
- 03. Valid Usernames ///////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Text.RegularExpressions;
- class ValidUsernames
- {
- static void Main(string[] args)
- {
- string text = Console.ReadLine();
- string pattern = @"\b[a-zA-Z]\w{2,24}\b";
- Regex users = new Regex(pattern);
- MatchCollection matches = users.Matches(text);
- int first = 0;
- int second = 1;
- int bestSum = int.MinValue;
- int sum = 0;
- for (int i = 0; i < matches.Count - 1; i++)
- {
- sum = matches[i].Length + matches[i + 1].Length;
- if (sum > bestSum)
- {
- bestSum = sum;
- first = i;
- second = i + 1;
- }
- }
- Console.WriteLine(matches[first]);
- Console.WriteLine(matches[second]);
- }
- }
- 04. Office Stuff //////////////////////////////////////////////////////////////////////////////////////////////////
- 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);
- }
- }
- }
- }
- //////////////////////////////// Java Basics - 7 January 2015 ///////////////////////////////////////////////////////////////////
- 01 zadacha PYRAMID
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- int n = int.Parse(Console.ReadLine());
- List<int> sequence = new List<int>();
- int previousNumber = int.Parse(Console.ReadLine().Trim());
- sequence.Add(previousNumber);
- for (int i = 1; i < n; i++)
- {
- string line = Console.ReadLine();
- string[] numbersAsString = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
- int[] numbers = new int[numbersAsString.Length];
- for (int j = 0; j < numbersAsString.Length; j++)
- {
- numbers[j] = int.Parse(numbersAsString[j]);
- }
- int minNumber = int.MaxValue;
- bool foundNumber = false;
- for (int k = 0; k < numbers.Length; k++)
- {
- int currentNumber = numbers[k];
- if (currentNumber < minNumber && currentNumber > previousNumber)
- {
- minNumber = currentNumber;
- foundNumber = true;
- }
- }
- if (foundNumber)
- {
- sequence.Add(minNumber);
- previousNumber = minNumber;
- }
- else
- {
- previousNumber++;
- }
- }
- Console.WriteLine(string.Join(", ",sequence));
- }
- }
- }
- 02. Terrorists Win!/////////////////////////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Text;
- class TerroristsWin
- {
- static void Main()
- {
- string inputText = Console.ReadLine();
- StringBuilder inputTextAsStringBuilder = new StringBuilder(inputText);
- int startIndex = inputText.IndexOf('|');
- int endIndex = 0;
- int unicodeSum = 0;
- int destroyedArea = 0;
- while (startIndex != -1)
- {
- unicodeSum = 0;
- endIndex = inputText.IndexOf('|', startIndex + 1);
- if (endIndex <= startIndex)
- {
- break;
- }
- for (int i = startIndex + 1; i <= endIndex - 1; i++)
- {
- unicodeSum += inputText[i];
- inputTextAsStringBuilder[i] = '.';
- }
- destroyedArea = unicodeSum % 10;
- for (int i = startIndex; i >= startIndex - destroyedArea && i >= 0; i--)
- {
- inputTextAsStringBuilder[i] = '.';
- }
- for (int i = endIndex; i <= endIndex + destroyedArea && i < inputTextAsStringBuilder.Length; i++)
- {
- inputTextAsStringBuilder[i] = '.';
- }
- startIndex = inputText.IndexOf('|', endIndex + 1);
- }
- Console.WriteLine(inputTextAsStringBuilder);
- }
- }
- 04. School System ////////////////////////////////////////////////////////////////////////////////////////
- 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);
- }
- }
- }
- }
- ///////////////////////////////////// Java Basics - 8 February 2015 //////////////////////////////////////////////////////////
- 02. Letters Change Numbers /////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string[] input = Console.ReadLine().Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
- double sum = 0;
- for (int i = 0; i < input.Length; i++)
- {
- string fromInput = input[i];
- char before = fromInput[0];
- char after = fromInput[fromInput.Length - 1];
- double num = double.Parse(fromInput.Substring(1, fromInput.Length - 2));
- if (char.IsUpper(before))
- {
- int beforePossition = before - 'A' + 1;
- num /= beforePossition;
- }
- else
- {
- int beforePossition = before - 'a' + 1;
- num *= beforePossition;
- }
- if (char.IsUpper(after))
- {
- int afrerPossition = after - 'A' + 1;
- num -= afrerPossition;
- }
- else
- {
- int afrerPossition = after - 'a' + 1;
- num += afrerPossition;
- }
- sum += num;
- }
- Console.WriteLine("{0:f2}", sum);
- }
- }
- }
- 04. User Logs /////////////////////////////////////////////////////////////////////////////////////
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- class Program
- {
- static void Main(string[] args)
- {
- SortedDictionary<string, SortedDictionary<string, int>> dataDic =
- new SortedDictionary<string, SortedDictionary<string, int>>();
- string input = Console.ReadLine();
- string[] inputTokens;
- string user;
- string ip;
- int counter;
- //Console.WriteLine("user = {0}", user);
- //Console.WriteLine("ip = {0}", ip);
- while (input != "end")
- {
- inputTokens = input.Split(new char[] { ' ', '=' }, StringSplitOptions.RemoveEmptyEntries);
- user = inputTokens[5];
- ip = inputTokens[1];
- counter = 1;
- if (!dataDic.ContainsKey(user))
- {
- dataDic[user] = new SortedDictionary<string, int>();
- }
- if (!dataDic[user].ContainsKey(ip))
- {
- dataDic[user][ip] = counter;
- }
- else
- {
- dataDic[user][ip] += counter;
- }
- input = Console.ReadLine();
- }
- foreach (KeyValuePair<string, SortedDictionary<string, int>> entry in dataDic)
- {
- char ch = ',';
- Console.WriteLine(entry.Key + ": ");
- int i = 1;
- foreach (KeyValuePair<string, int> item in entry.Value)
- {
- if (i == entry.Value.Count)
- {
- ch = '.';
- }
- Console.Write(item.Key + " => " + item.Value + ch + " ");
- i++;
- }
- Console.WriteLine();
- }
- //foreach (KeyValuePair<string, SortedDictionary<string, int>> entry in dataDic)
- //{
- // char ch = '.';
- // Console.WriteLine(entry.Key + ":");
- // foreach (KeyValuePair<string, int> item in entry.Value)
- // {
- // Console.WriteLine(item.Key + " => " + item.Value + ch);
- // }
- //}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement