Advertisement
another90sm

Population_Counter

May 21st, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.25 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Numerics;
  5. using System.Text;
  6.  
  7. class PopulationCounter
  8. {
  9.     static void Main()
  10.     {
  11.         var populationStructure = new Dictionary<string, Dictionary<string, int>>();
  12.         string inputline = Console.ReadLine();
  13.  
  14.         while (inputline != "report")
  15.         {
  16.             string[] tokens = inputline.Split('|');
  17.             string city = tokens[0];
  18.             string country = tokens[1];
  19.             int population = int.Parse(tokens[2]);
  20.  
  21.             if (populationStructure.ContainsKey(country))
  22.             {
  23.                 if (populationStructure[country].ContainsKey(city))
  24.                 {
  25.                     populationStructure[country][city] += population;
  26.                 }
  27.                 else
  28.                 {
  29.                     populationStructure[country][city] = population;
  30.                 }
  31.             }
  32.             else
  33.             {
  34.                 populationStructure[country] = new Dictionary<string, int>();
  35.                 populationStructure[country][city] = population;
  36.             }
  37.  
  38.             inputline = Console.ReadLine();
  39.         }
  40.  
  41.         var sortedCountries =
  42.             from country in populationStructure
  43.             orderby TotatCountryPopulation(country.Value) descending
  44.             select country;
  45.  
  46.         foreach (var countryKeyValuePair in sortedCountries)
  47.         {
  48.             var totalPopulation = TotatCountryPopulation(countryKeyValuePair.Value);
  49.             Console.WriteLine($"{countryKeyValuePair.Key} (total population: {totalPopulation})");
  50.  
  51.             var sortedCities =
  52.                 from city in countryKeyValuePair.Value
  53.                 orderby city.Value descending
  54.                 select city;
  55.  
  56.             foreach (var cityKeyValuePair in sortedCities)
  57.             {
  58.                 Console.WriteLine($"=>{cityKeyValuePair.Key}: {cityKeyValuePair.Value}");
  59.             }
  60.         }            
  61.     }
  62.  
  63.     public static BigInteger TotatCountryPopulation(Dictionary<string, int> innerDictionary)
  64.     {
  65.         BigInteger result = 0;
  66.         foreach (var keyValuePair in innerDictionary)
  67.         {
  68.             result += keyValuePair.Value;
  69.         }
  70.         return result;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement