static void Main(string[] args)
        {
            var lectures = new Dictionary<string, Tuple<int, int>>();
            int count = int.Parse(Console.ReadLine().Split(' ')[1]);
            for (int i = 0; i < count; i++)
            {
                var tokens = Console.ReadLine().Split(new[] { ' ', '-', ':' }, StringSplitOptions.RemoveEmptyEntries);
                lectures.Add(tokens[0], new Tuple<int, int>(int.Parse(tokens[1]), int.Parse(tokens[2])));
            }

            int resCount = 0;
            int earliestFinish = 0;
            var sortedLectures = lectures.OrderBy(l => l.Value.Item2);
            foreach (var lecture in sortedLectures)
            {
                if (lecture.Value.Item1 >= earliestFinish)
                {
                    earliestFinish = lecture.Value.Item2;
                    resCount++;
                    continue;
                }

                lectures.Remove(lecture.Key);
            }

            Console.WriteLine($"Lectures ({resCount}):");
            foreach (var lecture in lectures.OrderBy(l => l.Value.Item2))
            {
                Console.WriteLine($"{lecture.Value.Item1}-{lecture.Value.Item2} -> {lecture.Key}");
            }
        }
Example #2
0
        public string Encode() {
            var values = new Dictionary<string, string>();
            values.Add("bank_type", "WX");
            values.Add("body", Body);
            if (!string.IsNullOrEmpty(Attach))
                values.Add("attach", Attach);
             
            values.Add("partner", WxPayConfig.PARTER_ID);
            values.Add("out_trade_no", OutTradeNo);
            values.Add("total_fee", TotalFee.ToString());
            values.Add("fee_type", FeeType.ToString());
            values.Add("notify_url", string.IsNullOrEmpty(NotifyUrl)?WxPayConfig.NOTIFY_URL:NotifyUrl);
            values.Add("spbill_create_ip", SPBill_Create_IP);
            if (!string.IsNullOrEmpty(Time_Start))
                values.Add("time_start", Time_Start);
            if (!string.IsNullOrEmpty(Time_End))
                values.Add("time_expire", Time_End);
            values.Add("transport_fee", TransportFee.ToString());
            values.Add("product_fee", ProductFee.ToString());
            if (!string.IsNullOrEmpty(GoodsTag))
                values.Add("goods_tag", GoodsTag);
            values.Add("input_charset", InputCharset);

            var signingStr = values.OrderBy(b => b.Key).Aggregate(new StringBuilder(), (s, b) => s.AppendFormat("{0}={1}&", b.Key, b.Value), s => s.ToString()).TrimEnd('&');
            signingStr = string.Format("{0}&key={1}", signingStr, WxPayConfig.PARTER_KEY);
            var signedStr = Util.MD5_Encode(signingStr).ToUpper();
            var resultStr = values.OrderBy(b => b.Key).Aggregate(new StringBuilder(), (s, b) => s.AppendFormat("{0}={1}&", b.Key,Util.UrlEncode(b.Value)), s => s.ToString()).TrimEnd('&');
            return string.Format("{0}&sign={1}", resultStr, signedStr);
        }
 public static string Distance()
 {
     Dictionary<string, double> distance;
     distance = new Dictionary<string,double>();
     distance.Add("normal", CalculateDistance(0, 0));
     distance.Add("up", CalculateDistance(0, -1));
     distance.Add("down", CalculateDistance(0, 1));
     distance.Add("left", CalculateDistance(-1, 0));
     distance.Add("right", CalculateDistance(1, 0));
     Console.WriteLine(distance.OrderBy(kvp => kvp.Value).First().Key);
     return distance.OrderBy(kvp => kvp.Value).First().Key;
 }
Example #4
0
 public static int[] GetRanked(int[] A, int ABegin, int ALength)
 {
     Dictionary<int, int> Dict = new Dictionary<int, int>();
     for (int i = 0; i < ALength; i++) Dict.Add(i, A[i + ABegin]);
     Dictionary<int, int> Dict2 = new Dictionary<int, int>();
     int index = 0;
     foreach (var item in Dict.OrderBy(pair => pair.Value)) Dict[item.Key] = index++;
     int[] ret = new int[ALength];
     foreach (var item in Dict.OrderBy(pair => pair.Key))
     {
         ret[item.Key] = item.Value;
     }
     return ret;
 }
        private static void Main(string[] args)
        {

            var reader = new StreamReader("..//..//text.txt", Encoding.UTF8);
            string[] words;
            using (reader)
            {
                words =
                    reader.ReadToEnd()
                          .Split(new[] { ' ', '.', '!', '?', '-', ',', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                          .Select(x => x.ToLower())
                          .ToArray();
            }
            var wordsDict = new Dictionary<string, int>();
            for (int i = 0; i < words.Length; i++)
            {
                string word = words[i];
                if (!wordsDict.ContainsKey(word))
                {
                    wordsDict[word] = 0;
                }

                wordsDict[word]++;
            }

            var sortedWords = wordsDict.OrderBy(x => x.Value);
            foreach (var i in sortedWords)
            {
                Console.WriteLine(i.Key + " -> " + i.Value + " times");
            }
        }
Example #6
0
        private static void CountWordsFromFile(string line)
        {
            var words = line.Trim().Split(new[] { ' ', '-', '.', ',', '!', '?' });
            var meanWords = new Dictionary<string, int>();

            foreach (var word in words)
            {
                if (word != string.Empty && word != "?" && word != "!" && word != "." && word != ",")
                {
                    var lowerWord = word.ToLower();
                    if (meanWords.ContainsKey(lowerWord))
                    {
                        meanWords[lowerWord]++;
                    }
                    else
                    {
                        meanWords.Add(lowerWord, 1);
                    }
                }
            }
            var dict = meanWords.OrderBy(x => x.Value);
            foreach (var word in dict)
            {
                Console.WriteLine("{0} -> {1} times", word.Key, word.Value);
            }
        }
Example #7
0
 static void Main()
 {
     string input = "prela baba tri 4%^&!nedeli, ta izprela tri kadeli!";
     string[] words = Regex.Split(input, @"[\[email protected]#$%^&*()_+,=-`/?.,<>\|'"";:]");
     Dictionary<char, int> countchars = new Dictionary<char, int>();
     for (int i = 0; i < words.Length; i++)
     {
         foreach (var character in words[i])
         {
             if (countchars.ContainsKey(character))
             {
                 countchars[character]++;
             }
             else
             {
                 countchars.Add(character, 1);
             }
         }
     }
        var sortedLetters = countchars.OrderBy(x => x.Key);
     foreach (var letter in sortedLetters)
     {
         Console.WriteLine("Letter --> {0} - Number --> {1}", letter.Key, letter.Value);
     }
 }
Example #8
0
        /// <summary>释放模版文件</summary>
        public static Dictionary<String, String> GetTemplates()
        {
            var ss = Assembly.GetExecutingAssembly().GetManifestResourceNames();
            if (ss == null || ss.Length <= 0) return null;

            var dic = new Dictionary<String, String>();

            //找到资源名
            foreach (var item in ss)
            {
                if (item.StartsWith("XCoder.App."))
                {
                    ReleaseFile(item, "XCoder.exe.config");
                }
                else if (item.StartsWith("XCoder.Template."))
                {
                    var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(item);
                    var tempName = item.Substring("XCoder.Template.".Length);
                    var buffer = new Byte[stream.Length];
                    var count = stream.Read(buffer, 0, buffer.Length);

                    var content = Encoding.UTF8.GetString(buffer, 0, count);
                    dic.Add(tempName, content);
                }
            }

            return dic.OrderBy(e => e.Key).ToDictionary(e => e.Key, e => e.Value);
        }
 static void Main()
 {
     string text = "It’s your 10 digit Fido number 4%^&[email protected] ( for example [email protected] ).";
     string[] words = Regex.Split(text, @"[\[email protected]#$%^&*()_+,=-`/?.,<>\|'"";:]");
     Dictionary<char, int> countchars = new Dictionary<char, int>();
     for (int i = 0; i < words.Length; i++)
     {
         foreach (var character in words[i])
         {
             if (countchars.ContainsKey(character))
             {
                 countchars[character]++;
             }
             else
             {
                 countchars.Add(character, 1);
             }
         }
     }
     var sortedLetters = countchars.OrderBy(x => x.Key);
     foreach (var letter in sortedLetters)
     {
         Console.WriteLine("Letter --> {0} - Number --> {1}", letter.Key, letter.Value);
     }
 }
 private static string GetTypeKey(Dictionary<string, Type> fields)
 {
     string key = string.Empty;
     foreach (var field in fields.OrderBy(v => v.Key).ThenBy(v => v.Value.Name))
         key += field.Key + ";" + field.Value.Name + ";";
     return key;
 }
        public static void Main()
        {
            var testString = "This is the TEXT. Text, text, text – THIS TEXT! Is this the text?";
            var splitted = testString.Split(new char[] { ' ', ',', '.', '?', '!', ';', '–' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(w => w.ToLower())
                .ToList();

            var result = new Dictionary<string, int>();

            foreach (var word in splitted)
            {
                if (result.ContainsKey(word))
                {
                    result[word] += 1;
                }
                else
                {
                    result[word] = 1;
                }
            }

            var ordered = result.OrderBy(x => x.Value).ToList();
            foreach (var item in ordered)
            {
                Console.WriteLine("{0, 10} --> {1}", item.Key, item.Value);
            }
        }
Example #12
0
        public static void Dump(Dictionary<string, ObjectMemoryCounters> objects, Dictionary<string, string> totals)
        {
            try
            {
                if (objects != null && _objectsLogger != null && _objectsLogger.IsInfoEnabled)
                {
                    foreach (var omc in objects.Values)
                    {
                        var collector = new Dictionary<string, string>();
                        omc.FormatTo(collector);
                        var data = collector.OrderBy(kvp => kvp.Key);
                        CheckFirstObjectWrite(data);
                        _objectsLogger.InfoFormat("{0};{1}", omc.Name, string.Join(";", data.Select(kvp => kvp.Value).ToArray()));
                    }
                }

                if (totals != null && _mainLogger != null && _mainLogger.IsInfoEnabled)
                {
                    var data = totals.OrderBy(kvp => kvp.Key);
                    CheckFirstMainWrite(data);
                    _mainLogger.Info(string.Join(";", data.Select(kvp => kvp.Value).ToArray()));
                }
            }
            catch
            {
                // don't care
            }
        }
Example #13
0
    public static void Main()
    {
        string[] specialSigns = { " ", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+" };

        string input = Console.ReadLine();

        for (int i = 0; i < specialSigns.Length; i++)
        {
            input = input.Replace(specialSigns[i], string.Empty);
        }

        Dictionary<char, int> allLetters = new Dictionary<char, int>();

        for (int i = 0; i < input.Length; i++)
        {
            if (allLetters.ContainsKey(input[i]))
            {
                allLetters[input[i]]++;
            }
            else
            {
                allLetters.Add(input[i], 1);
            }
        }

        var sortedLetters = allLetters.OrderBy(x => x.Key);
        foreach (var item in sortedLetters)
        {
            Console.WriteLine("Letter --> {0} - Number --> {1}", item.Key, item.Value);
        }
    }
		public static bool IsAnagram(string a, string b)
		{
			Dictionary<char, int> dictionary1 = new Dictionary<char, int>();
			foreach (var chaR in a)
			{
				if (dictionary1.ContainsKey(chaR))
				{
					dictionary1[chaR] += 1;
				}
				else
				{
					dictionary1.Add(chaR, 1);
				}
			}

			Dictionary<char, int> dictionary2 = new Dictionary<char, int>();
			foreach (var chaR in b)
			{
				if (dictionary2.ContainsKey(chaR))
				{
					dictionary2[chaR] += 1;
				}
				else
				{
					dictionary2.Add(chaR, 1);
				}
			}

			bool isEqual = dictionary1.OrderBy(r => r.Key).SequenceEqual(dictionary2.OrderBy(r => r.Key));
			return isEqual;
		}
        static void Main(string[] args)
        {
            var text = new StreamReader("text.txt").ReadToEnd().ToLower();
            //             string regex = @"\b\w+\b";
            //             MatchCollectionollection words = Regex.Matches(text, regex);
            var words = text.Split(new char[] { '.', '!', '?', ';', ' ', ':', ',', '-' }, StringSplitOptions.RemoveEmptyEntries);
            var dictionary = new Dictionary<string, int>();
            foreach (var item in words)
            {
                if (dictionary.ContainsKey(item))
                {
                    dictionary[item]++;
                }
                else
                {
                    dictionary.Add(item, 1);
                }
            }

            foreach (var item in dictionary.OrderBy(x => x.Value))
            {
                Console.WriteLine("{0} -> {1}", item.Key, item.Value);
            }

            Console.ReadKey(true);
        }
        static void Main()
        {
            string source = Console.ReadLine();
            Dictionary<char, int> chars = new Dictionary<char, int>();
            for (char i = 'a'; i <= 'z'; i++)
            {
                chars.Add(i, 0);
            }
            for (char i = 'A'; i <= 'Z'; i++)
            {
                chars.Add(i, 0);
            }

            foreach (char curr in source)
            {
                if (chars.ContainsKey(curr))
                {
                    chars[curr]++;
                }
            }

            var ordered = chars.OrderBy(x => x.Key); //to sort by the letter
            foreach (var item in ordered)
            {
                if (item.Value != 0)
                {
                    Console.WriteLine("{0} -> {1} ", item.Key, item.Value);
                }
            }
        }
Example #17
0
        static void Main()
        {
            var occurences = new Dictionary<string, int>();
            var reader = new StreamReader("text.txt", Encoding.UTF8);

            using (reader)
            {
                var line = reader.ReadLine();

                while (line != null)
                {
                    string regexPattern = @"[^\p{L}]*\p{Z}[^\p{L}]*";
                    var currentLineWords = Regex.Split(line, regexPattern);
                    
                    foreach (var word in currentLineWords)
                    {
                        if (!occurences.ContainsKey(word.ToLower()))
                        {
                            occurences.Add(word.ToLower(), 1);
                        }
                        else
                        {
                            occurences[word.ToLower()]++;
                        }
                    }
                    line = reader.ReadLine();
                }
            }
            var sortedValues = occurences.OrderBy(kvp => kvp.Value);

            foreach (var item in sortedValues)
            {
                Console.WriteLine("{0} -> {1} times", item.Key, item.Value);
            }
        }
        private void FillData()
        {
            conn = DBconnection.GetConnection();
            if (conn.State.ToString() == "Closed")
            {
                conn.Open();
            }

            Dictionary<string, string> UserListDictionary = new Dictionary<string, string>();
            SqlCommand usrListCmd = new SqlCommand("SELECT x_id,fname,lname FROM [sms].[dbo].[user] as us INNER JOIN [sms].[dbo].[teacher] as teach ON us.x_id = teach.teach_id INNER JOIN [sms].[dbo].[person] as pr ON pr.id = teach.id WHERE Role='User'", conn);
            SqlDataReader dr = usrListCmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    int IndexXID = dr.GetOrdinal("x_id");
                    int IndexFname = dr.GetOrdinal("fname");
                    int IndexLname = dr.GetOrdinal("lname");

                    string UserXID = dr.GetString(IndexXID);
                    string Fname = dr.GetString(IndexFname);
                    string Lname = dr.GetString(IndexLname);
                    UserListDictionary = UserListDictionary.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
                    UserListDictionary.Add(UserXID, Fname + " " + Lname);
                }
            }

            usrList.DisplayMember = "Value";
            usrList.ValueMember = "Key";
            usrList.DataSource = new BindingSource(UserListDictionary, null);
        }
Example #19
0
        /// <summary>
        /// To do. Create a clever search algorithm.
        /// </summary>
        /// <param name="Word"></param>
        /// <param name="Collection"></param>
        /// <returns></returns>
        public string GetSimilar(string Word, List<string> Collection)
        {
            if (Word.IsNullOrEmpty())
            {
                return Word;
            }

            Dictionary<string, int> keys = new Dictionary<string, int>();

            /*foreach (string s in words.Keys)
            {
                if (s.EndsWith(Word))
                {
                    keys.Add(s, s.Length);
                }
            }*/

            Collection.AsParallel().ForAll(s =>
            {
                if (s.EndsWith(Word))
                {
                    keys.Add(s, s.Length);
                }
            });

            if (!keys.Any() && Word.Length > 2)
            {
                return this.GetSimilar(Word.Substring(1), Collection);
            }

            string key = keys.OrderBy(val => val.Value).FirstOrDefault().Key;

            return key;
        }
        public Dictionary<DateTime, decimal> Calculate()
        {
            var returnDictionary = new Dictionary<DateTime, decimal>();

            if (this.signals.Any())
            {
                returnDictionary.Add(this.signals.ElementAt(0).Date, this.startingEquity);

                var count = this.signals.Count();

                for (var i = 0; i <= count - 2; i++)
                {
                    var originalSignal = this.signals.ElementAt(i).SignalType;
                    if (originalSignal == SignalType.TakeProfits)
                    {
                        returnDictionary.Add(this.signals.ElementAt(i + 1).Date,
                                             returnDictionary.OrderBy(d => d.Key).Last().Value);
                        continue;
                    }

                    var startTradePrice = this.signals.ElementAt(i).Price;
                    var finalTradePrice = this.signals.ElementAt(i + 1).Price;
                    var percentageDifference = (finalTradePrice - startTradePrice)/startTradePrice;
                    var percentageDifferenceToEquity = originalSignal == SignalType.Buy && percentageDifference > 0 ||
                                                       originalSignal == SignalType.Sell && percentageDifference < 0
                                                           ? Math.Abs(percentageDifference)
                                                           : -Math.Abs(percentageDifference);
                    var newEquityValue = returnDictionary.Last().Value +
                                         (returnDictionary.Last().Value*percentageDifferenceToEquity);
                    returnDictionary.Add(this.signals.ElementAt(i + 1).Date, newEquityValue);
                }
            }

            return returnDictionary;
        }
    internal static void Main()
    {
        var reader = new StreamReader(@"..\..\words.txt");
        char[] separators = { ' ', '.', ',', '!', '?', '–' };

        using (reader)
        {
            string all = reader.ReadToEnd();
            string[] words = all.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            var result = new Dictionary<string, int>();

            for (int i = 0; i < words.Length; i++)
            {
                if (result.ContainsKey(words[i].ToLower()))
                {
                    result[words[i].ToLower()]++;
                }
                else
                {
                    result[words[i].ToLower()] = 1;
                }
            }

            foreach (var item in result.OrderBy(x => x.Value))
            {
                Console.WriteLine("{0} -> {1} {2}", item.Key, item.Value, item.Value == 1 ? "time" : "times");
            }
        }
    }
Example #22
0
        public static void Main(string[] args)
        {
            using (var sr = new StreamReader("words.txt"))
            {
                IDictionary<string, int> wordsCount = new Dictionary<string, int>();
                string[] words = GetWords(sr.ReadToEnd());

                for (int i = 0; i < words.Length; i++)
                {
                    string word = words[i].ToLower();
                    if (wordsCount.ContainsKey(word))
                    {
                        wordsCount[word]++;
                    }
                    else
                    {
                        wordsCount[word] = 1;
                    }
                }

                var wordsOrderedByOccurrences = wordsCount.OrderBy(x => x.Value);

                foreach (var word in wordsOrderedByOccurrences)
                {
                    Console.WriteLine("{0} => {1} times", word.Key, word.Value);
                }
            }
        }
        public string Get(string[] documentUris)
        {
            string prefix = "Content-Security-Policy: default-src 'none'";
            string result = "";
            cacheLock.EnterReadLock();
            try
            {
                var dictsToMerge = rules.Where(x => documentUris.Contains(x.Key)).Select(x => x.Value);
                var mergedDict = new Dictionary<string, HashSet<string>>();
                foreach (var dict in dictsToMerge)
                {
                    foreach (var e in dict)
                    {
                        if (!mergedDict.ContainsKey(e.Key))
                        {
                            mergedDict[e.Key] = new HashSet<string>();
                        }
                        mergedDict[e.Key] = new HashSet<string>(mergedDict[e.Key].Concat(e.Value));
                    }
                }

                result = mergedDict.OrderBy(x => x.Key).Select(entry => (
                    entry.Value.OrderBy(x => x).Aggregate(entry.Key, (total, next) => (total + " " + next))
                    )).Aggregate(prefix, (total, next) => (total + "; " + next));
            }
            finally
            {
                cacheLock.ExitReadLock();
            }

            return result;
        }
		public void LoadMatches(Dictionary<GameStats, List<GameStats>> games)
		{
			try
			{
				AllWrappers.Clear();
				foreach(var set in games.OrderBy(x => x.Value.Count))
				{
					var deck = DeckList.Instance.Decks.FirstOrDefault(d => d.DeckId == set.Key.DeckId);
					var tvi = new TreeViewItem
					{
						ItemTemplate = (DataTemplate)FindResource("DataTemplateCheckBox"),
						Header = $"[Original - Deck: {(deck != null ? deck.Name : "")}] : {GetMatchInfo(set.Key)} ({set.Value.Count} duplicate(s))",
						IsExpanded = true
					};
					foreach(var game in set.Value)
					{
						try
						{
							var wrapper = new GameStatsWrapper(game);
							tvi.Items.Add(wrapper);
							AllWrappers.Add(wrapper);
						}
						catch(Exception e)
						{
							Log.Error(e);
						}
					}
					TreeViewGames.Items.Add(tvi);
				}
			}
			catch(Exception ex)
			{
				Log.Error(ex);
			}
		}
        static void Main()
        {
            StreamReader reader = new StreamReader("someText.txt", Encoding.GetEncoding("UTF-8"));
            using (reader)
            {
                string text = reader.ReadToEnd();
                char[] separateBy = { ' ', '.', ',', '!', '?' };
                string[] values = text.ToLower().Split(separateBy, StringSplitOptions.RemoveEmptyEntries);

                Dictionary<string, int> dictionary = new Dictionary<string, int>();

                foreach (var value in values)
                {
                    int count = 0;
                    if (dictionary.ContainsKey(value))
                    {
                        count = dictionary[value];
                    }
                    dictionary[value] = count + 1;
                }

                foreach (KeyValuePair<string, int> item in dictionary.OrderBy(key => key.Value))
                {
                    Console.WriteLine("{0} -> {1} times", item.Key, item.Value);
                }
            }
        }
Example #26
0
        public static IEnumerable<KeyValuePair<string, string>> GetSpecialistList(AdGroup grp)
        {
            var list = new Dictionary<string, string>();

            using (WindowsImpersonationContextFacade impersonationContext
                = new WindowsImpersonationContextFacade(
                    nc))
            {
                var domain = new PrincipalContext(ContextType.Domain);
                var group = GroupPrincipal.FindByIdentity(domain, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp));
                if (group != null)
                {
                    var members = group.GetMembers(true);
                    foreach (var principal in members)
                    {
                        var userPrincipal = UserPrincipal.FindByIdentity(domain, principal.SamAccountName);
                        if (userPrincipal != null)
                        {
                            var name = MainHelper.ShortName(userPrincipal.DisplayName);
                            var sid = userPrincipal.Sid.Value;
                            list.Add(sid, name);
                        }
                    }
                }

                return list.OrderBy(x => x.Value);
            }
        }
        public string PrcessCoursesOutput(Dictionary<string, decimal> coursesCatalog)
        {
            var result = "";

            var lastItemType = "none";
            foreach(var resultPointer in coursesCatalog.OrderBy(p => p.Value))
            {
                if (resultPointer.Value % 1 == 0)
                {
                    if (lastItemType == "loop")
                    {
                        result = result.Substring(0, result.Length - 2);
                        result += ", ";
                    }
                    result += resultPointer.Key + ", ";
                }
                else
                {
                    result += resultPointer.Key + "- ";
                    lastItemType = "loop";
                }
            }
            result = result.Substring(0, result.Length - 2);

            if (result.Contains("-"))
                result = "Notice: A cricular reference was detected in the courses entered. " + result;

            return result;
        }
Example #28
0
    //public static char[, ,] cube;
    static void Main()
    {
        string[] rawDimentions = Console.ReadLine().Split();
        int width = int.Parse(rawDimentions[0]);
        int height = int.Parse(rawDimentions[1]);
        int depth = int.Parse(rawDimentions[2]);
        char[, ,] cube = new char[width, height, depth];

        for (int h = 0; h < height; h++)
        {
            string[] line = Console.ReadLine().Split();
            for (int d = 0; d < depth; d++)
            {
                string token = line[d];
                for (int w = 0; w < width; w++)
                {
                    cube[w, h, d] = token[w];
                }
            }
        }

        Dictionary<char, int> stars = new Dictionary<char, int>();
        for (int h = 1; h < height - 1; h++)
        {
            for (int d = 1; d < depth - 1; d++)
            {
                for (int w = 1; w < width - 1; w++)
                {
                    if (cube[w, h, d] == cube[w, h + 1, d]
                     && cube[w, h, d] == cube[w, h - 1, d]
                     && cube[w, h, d] == cube[w + 1, h, d]
                     && cube[w, h, d] == cube[w - 1, h, d]
                     && cube[w, h, d] == cube[w, h, d + 1]
                     && cube[w, h, d] == cube[w, h, d - 1])
                    {
                        if (stars.ContainsKey(cube[w, h, d]))
                        {
                            stars[cube[w, h, d]] += 1;
                        }
                        else
                        {
                            stars.Add(cube[w, h, d], 1);
                        }
                    }
                }
            }
        }

        int starsCount = 0;
        foreach (var star in stars)
        {
            starsCount += star.Value;
        }
        Console.WriteLine(starsCount);

        foreach (var star in stars.OrderBy(m => m.Key))
        {
            Console.WriteLine("{0} {1}", star.Key, star.Value);
        }
    }
        internal static string GetOAuthHeader(Dictionary<string, string> parameters, string url, string comsumeSercret, string tokenSecret)
        {
            parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value);

            string concat = string.Empty;

            string OAuthHeader = "OAuth ";
            foreach (var key in parameters.Keys)
            {
                concat += key + "=" + parameters[key] + "&";
                OAuthHeader += key + "=" + "\"" + parameters[key] + "\",";
            }

            concat = concat.Remove(concat.Length - 1, 1);
            concat = EncodeToUpper(concat);

            concat = "POST&" + EncodeToUpper(url) + "&" + concat;

            byte[] content = Encoding.UTF8.GetBytes(concat);

            HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(comsumeSercret + "&" + tokenSecret));
            hmac.ComputeHash(content);

            string hash = Convert.ToBase64String(hmac.Hash);

            hash = hash.Replace("-", "");

            OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\"";

            return OAuthHeader;
        }
Example #30
0
        static void Main()
        {
            StreamReader reader = new StreamReader(@"../../words.txt");
            using (reader)
            {
                string text = reader.ReadToEnd();
                string[] words = text.Split(new char[] { '.', ',', '!', '?', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                Dictionary<string, int> occurs = new Dictionary<string, int>();

                foreach (var word in words)
                {
                    if (occurs.ContainsKey(word.ToLower()))
                    {
                        occurs[word.ToLower()]++;
                    }
                    else
                    {
                        occurs.Add(word.ToLower(), 1);
                    }
                }

                var sortedOccurs = occurs.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);
                // for this task cast to a Dictionary is not nessesary it works with return form lambda expressin key-value-pair too.

                foreach (var occur in sortedOccurs)
                {
                    Console.WriteLine("{0} -> {1} times", occur.Key, occur.Value);
                }

            }
        }