C# Algorithms – Phone Book Implementation – List of int and string with a tuple
Today I had to write a solution of the following problem – imagine you have two lists like this:
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:
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! 🙂
