Today I had to write a solution of the following problem – imagine you have two lists like this:
1 2 3 4 5 6 7 8 9 10 11 |
var liPhoneBook = new List<tuple<int,string>>(); liPhoneBook.Add(Tuple.Create(100, "Pesho")); liPhoneBook.Add(Tuple.Create(200, "Gosho")); liPhoneBook.Add(Tuple.Create(300, "Atanas")); liPhoneBook.Add(Tuple.Create(400, "Az")); liPhoneBook.Add(Tuple.Create(500, "Ivan")); liPhoneBook.Add(Tuple.Create(600, "Ivan Petrov")); liPhoneBook.Add(Tuple.Create(900, "Vitosh")); List liNumbers = new List (new int[]{900, 300,400,100,600}); |
What I needed to write was a program, printing the names of the users in liNumbers. Something like this. As far as using two embedded loops was pretty much the obvious solution, I have decided to go one step further and to optimize it … After all, this is algorithm implementation. Thus, I have decided to still use the two loops, but to start the inner loop only from the index which I have reached so far. As you see, in the printed version I am printing the indices of the inner loop and they do not repeat. Thus, it works better than just two loops. 🙂
So far so good! Here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Collections.Generic; using System.Linq; class MainClass { public static void Main () { var liPhoneBook = new List<tuple<int,string>>(); liPhoneBook.Add(Tuple.Create(100, "Pesho")); liPhoneBook.Add(Tuple.Create(200, "Gosho")); liPhoneBook.Add(Tuple.Create(300, "Atanas")); liPhoneBook.Add(Tuple.Create(400, "Az")); liPhoneBook.Add(Tuple.Create(500, "Ivan")); liPhoneBook.Add(Tuple.Create(600, "Ivan Petrov")); liPhoneBook.Add(Tuple.Create(900, "Vitosh")); List liNumbers = new List (new int[]{900, 300,400,100,600}); findNumbers (liNumbers, liPhoneBook); } public static void findNumbers(List liNumbers, List<tuple<int,string>> liPhoneBook) { liNumbers.Sort (); liPhoneBook.Sort (); int iPosition = 0; foreach (var item in liNumbers) { for (int i = iPosition; i < liPhoneBook.Count; i++) { Console.WriteLine (i); if (item == liPhoneBook[i].Item1) { Console.WriteLine (liPhoneBook[i].Item2); iPosition = i+1; break; } } } } } |
Enjoy it! 🙂