Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping numbers to letters

Tags:

c#

I had an interview question asking this:

text file has following lines>

            1: A C D
            4: A B
            5: D F
            7: A E
            9: B C  

*Every line has a unique integer followed by a colon and one or more letters. These letters are delimited spaces (one or more)>

                            #2 Write a short program in the language

of your choice that outputs a sorted list like

            A: 1 4 7
            B: 4 9
            C: 1 9
            D: 1 5
            E: 7
            F: 5

I'm not looking for someone to solve it, but I always get confused with problems like this. I'd like to do it in C# and was wondering should I store each line in a 2d array? What is the best way to handle this. After storing it how do I relist each line with letters rather then numbers?

Just looking for pointers here.

like image 268
oJM86o Avatar asked Jun 23 '11 12:06

oJM86o


2 Answers

You can solve the problem by creating a Lookup mapping letters to a collection of numbers. You can use the extension method ToLookup to create a Lookup.


Warning: Spoilers ahead

Using LINQ you can do it like this (breaks on invalid input):

var text = @"1: A C D
4: A B
5: D F
7: A E
9: B C";

var lookup = text
  .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
  .Select(
    line => new {
      Number = Int32.Parse(line.Split(':').First()),
      Letters = line.Split(':').Skip(1).First().Split(
        new[] {' '}, StringSplitOptions.RemoveEmptyEntries
      )
    }
  )
  .SelectMany(x => x.Letters, (x, letter) => new { x.Number, Letter = letter })
  .OrderBy(x => x.Letter)
  .ToLookup(x => x.Letter, x => x.Number);

foreach (var item in lookup)
  Console.WriteLine(item.Key + ": " + String.Join(" ", item.ToArray()));
like image 71
Martin Liversage Avatar answered Oct 11 '22 12:10

Martin Liversage


In case you are familiar with LINQ the below code can give you what you are looking for:

var result = File.ReadAllLines("inFile").SelectMany(line =>
                {
                    var ar = line.Split(" ".ToCharArray());
                    var num = int.Parse(ar[0].Split(":".ToCharArray())[0]);
                    return ar.Skip(1).Select(s => new Tuple<string, int>(s, num));
                }).GroupBy(t => t.Item1).OrderByDescending(g => g.Count())
                .Select(g => g.Key + ": " + g.Select(t => t.Item2.ToString()).Aggregate( (a,b) => a + " " + b));
            File.WriteAllLines("outFile", result);
like image 25
Ankur Avatar answered Oct 11 '22 12:10

Ankur