Interview Question (C#)


/ Published in: C#
Save to your folder(s)

Sort a file that contains integers between 1 and thousand. The output file should contain the entries like (n-times 1, followed by n-times 2 and so on): 1111222333555... But - you are not allowed to load all entries into memory at once. How to solve it? Here is my solution.


Copy this code and paste it in your HTML
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace testhash
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14.  
  15. var table = new int[1000];
  16.  
  17. using (TextWriter tw = new StreamWriter(@"d:\test\TestDataFile.txt"))
  18. {
  19.  
  20. Random r = new Random(23874837);
  21.  
  22.  
  23.  
  24. for (int i = 1; i < 1000000; i++)
  25. {
  26.  
  27. tw.Write(r.Next(1, 1000));
  28. tw.Write(Environment.NewLine);
  29.  
  30. }
  31.  
  32.  
  33.  
  34. }
  35.  
  36. using(TextReader reader = new StreamReader(@"d:\test\TestDataFile.txt"))
  37. {
  38. string line;
  39.  
  40. while((line = reader.ReadLine()) != null)
  41. {
  42. table[Convert.ToInt32(line)] += 1;
  43. }
  44.  
  45. //int sum = table.Sum();
  46.  
  47. //Console.WriteLine(sum);
  48.  
  49.  
  50. using (TextWriter tw = new StreamWriter(@"d:\test\TestDataFileOutup.txt"))
  51. {
  52. for(var i = 0; i <= table.Count()-1;i++)
  53. {
  54.  
  55. for(int writeTimes = 1; writeTimes <= table[i];writeTimes++)
  56. {
  57. tw.Write(i);
  58. tw.Write(Environment.NewLine);
  59. }
  60.  
  61. }
  62. }
  63. }
  64.  
  65. }
  66.  
  67.  
  68.  
  69.  
  70.  
  71. }
  72.  
  73.  
  74. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.