…meie igapäevast IT’d anna meile igapäev…


Some fun with FizzBuzz in C#

Filed under: Isiklikud,Programmeerimine — Sander @ 13:34:03
Tags: ,

image As a very first thing, I must say that I don’t like whiteboard coding exercises during the job interviews.

These exercises have almost never any relation to real-life programming problems (“Reverse a linked list?” If your reply is anything besides “linkedList.Reverse();”, your answer is wrong.). There are only a few dozen common whiteboard coding questions – and every candidate with a common sense will review those before the interview.

Finally, success with whiteboard coding seems to have next to no connection with the actual qualities of the candidate. And yes, this includes “solving a problem under pressure”.

I much prefer to give the candidates a small task, to do at home in 2..3h. This will give me much more information – what is his coding style? Can he write high-quality and well-commented code? Did he actually manage to finish all parts of the task – and if not, then why? Does he even want the position enough to do a proper job?

That all said, FizzBuzz does have one good use – it can be used to quickly weed out the candidates who cannot program at all. If they cannot do a simple logical exercise, and write a loop with a couple of if-clauses inside it, they really shouldn’t be hired as developers.

That is why ex-coworker Erti-Chris and I were rather surprised after reading “Tales of a Non-Unicorn: A Story About The Trouble with Job Titles and Descriptions” (reddit thread). A person claiming to be “designer/developer if there ever was one” goes “OMG MATH” and cannot solve FizzBuzz (which has almost nothing to do with math)?!

Out of boredom we started to play around with FizzBuzz – albeit in C#, not JS (but all our ideas work with Javascript as well, with a little prodding) – first the “standard solution” and then limiting ourselves further and further.

The “standard solution” using modulus:

  1. Enumerable.Range(1, 100).ToList().ForEach(x =>
  2. {
  3.     var d3 = x % 3;
  4.     var d5 = x % 5;
  6.     Print(d3 == 0, d5 == 0, x);
  7. });

Method Print is used repeatedly, it is the same everywhere:

  1. private static void Print(bool three, bool five, int i)
  2. {
  3.     if (three && !five)
  4.         Console.WriteLine("Fizz");
  5.     else if (five && !three)
  6.         Console.WriteLine("Buzz");
  7.     else if (five)
  8.         Console.WriteLine("FizzBuzz");
  9.     else
  10.         Console.WriteLine(i);
  11. }

But what if we don’t allow modulus to be used?

  1. Enumerable.Range(1, 100).ToList().ForEach(x =>
  2. {
  3.     var d3 = x / 3f == Math.Round(x / 3f);
  4.     var d5 = x / 5f == Math.Round(x / 5f);
  6.     Print(d3, d5, x);
  7. });

But what about not using neither round nor modulus?

  1. Enumerable.Range(1, 100).ToList().ForEach(x =>
  2. {
  3.     var d3 = x / 3 * 3 == x;
  4.     var d5 = x / 5 * 5 == x;
  6.     Print(d3, d5, x);
  7. });

(and also the same limitations as above, nutcase version. Proudly mine).

  1. Enumerable.Range(1, 100).ToList().ForEach(x =>
  2. {            
  3.     var d3 = !(x / 3f).ToString().Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
  4.     var d5 = !(x / 5f).ToString().Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
  6.     Print(d3, d5, x);
  7. });

Still too easy. What about not allowing modulus, rounding, multiplication and division?

  1. for (int i = 0, three = 0, five = 0; i < 100; i++, three++, five++)
  2. {
  3.     if (three == 3 && five == 5)
  4.     {
  5.         Console.WriteLine("FizzBuzz");
  6.         three = 0;
  7.         five = 0;
  8.     }
  9.     else if (three == 3)
  10.     {
  11.         Console.WriteLine("Fizz");
  12.         three = 0;
  13.     }
  14.     else if (five == 5)
  15.     {
  16.         Console.WriteLine("Buzz");
  17.         five = 0;
  18.     }
  19.     else
  20.         Console.WriteLine(i);
  21. }

Amusingly, the last version is fastest of them all.

And by now we were out of time and bored of this. It was fun, though – a sort of minor coding kata.

All the code above can be seen and executed in dotNetFiddle, https://dotnetfiddle.net/84PodI


Microsoft Exam 70-483: Programming in C#

Filed under: Programmeerimine — Sander @ 10:44:40
Tags: , , ,


Yesterday I passed MS exam 70-483: Programming in C#. It was not an exam I really needed for MS Visual Studio 2012 certifications, as I already have MCPD (VS 2010 certifications) for both Windows and Web – so I could have done just the two exams required for an upgrade. However, I wanted to ensure I am properly up to date with .NET 4.5.

As of now, there really aren’t any “official” study materials. Microsoft’s Exam Ref 70-483: Programming in C# will come out in April 2013, Wrox’s MCSD Certification Toolkit (Exam 70-483): Programming in C# won’t be out until May 2013. Andreas Hammar has collected study links for the exam in his blog.

I read Pro C# 5.0 and the .NET 4.5 Framework, skipping quite a few sections as it is a very basic introduction (and the attempted humor in the book is just bad). Jeffrey Richter’s excellent CLR via C#, 4th Edition was both more interesting and in-depth – I read only Part II: Designing Types and  Part III: Essential Types for the exam, rest will be my Christmas reading (hey, to each his own!).

The exam itself was easy – probably easiest out of all eight Microsoft exams I’ve done so far. That wasn’t really surprising, as I am working daily with those areas covered in the exam. Maybe I should have paid more attention to performance counters, but despite Microsoft pushing those heavily, next to no one uses performance counters, opting for various other profilers instead.

However, what was surprising was how bad the exam questions were. Yes, that is a new, fresh exam – but that is not an excuse for sloppiness. Obviously I cannot go into details of the questions, but several of the questions were ambiguous – i.e. they did not cover all the requirements. Formatting of the code sometimes skipped spaces, i.e. instead of int i there was inti and so forth.

At least one question promoted just horrible way of coding. Yes, the problems are artificially constructed, but whoever prepared the exam should realize a lot of newbie programmers will see the code and think this is the way that particular casting operation should be done – and they will use it in their production code, causing bad performance and hard-to-find bugs.

And even worse, one question about nullable types and LINQ did not have a simplest and most logical answer. Again, this is something I have been working with daily for years, often implementing complex business logic.

I left quite a few comments to the exam review, but unfortunately, I really doubt anyone will actually read those and fix the issues. Which is a shame, as exams (same as study books) should always promote best practices and clean code.


C#: kill process by name for the current user

Filed under: Programmeerimine — Sander @ 09:59:20
Tags: ,

Quite often there is a need to kill a specific process or several processes. While processes are easy to get with Process.GetProcessesByName(), Process class doesn’t give us the owner of the process, so we will invariably get processes for all users. We have to turn to WMI to get the owner of the process:

  1. ///<summary>
  2. /// Kill the processes specified by the name (“notepad.exe”)
  3. ///</summary>
  4. ///<param name=”processName”>Name of the process, case-insensitive.</param>
  5. ///<param name=”currentUserOnly”>If true, kill only processes by current user</param>
  6. public static void KillProcessByName(string processName, bool currentUserOnly = true)
  7. {
  8.     try
  9.     {
  10.         string userName = null;
  11.         if (currentUserOnly)
  12.         {
  13.             WindowsIdentity user = WindowsIdentity.GetCurrent();
  14.             if (user == null)
  15.                 throw new InvalidCredentialException(“No current user?!”);
  16.             userName = user.Name;
  17.         }
  18.         var processFinder = new ManagementObjectSearcher(string.Format(“Select * from Win32_Process where Name='{0}‘”, processName));
  19.         var processes = processFinder.Get();
  20.         if (processes.Count == 0)
  21.             return;
  22.         foreach (ManagementObject managementObject in processes)
  23.         {
  24.             var pId = Convert.ToInt32(managementObject[“ProcessId”]);
  25.             var process = Process.GetProcessById(pId);
  26.             if (currentUserOnly) //current user
  27.             {
  28.                 var processOwnerInfo = new object[2];
  29.                 managementObject.InvokeMethod(“GetOwner”, processOwnerInfo);
  30.                 var processOwner = (string)processOwnerInfo[0];
  31.                 var net = (string)processOwnerInfo[1];
  32.                 if (!string.IsNullOrEmpty(net))
  33.                     processOwner = string.Format(“{0}\\{1}”, net, processOwner);
  34.                 if (string.CompareOrdinal(processOwner, userName) == 0)
  35.                     process.Kill();
  36.             }
  37.             else //any user                    
  38.                 process.Kill();
  39.         }
  40.     }
  41.     catch (Exception ex)
  42.     {
  43.         //There is a good chance for UnauthorizedAccessException here, so
  44.         //log the error or handle otherwise
  45.     }
  46. }

You can easily modify the method not to work only with current user, but any user you specify – just make userName into a parameter. Or you can use this to return information about user having processes with that name – don’t use it as a replacement for Mutex or EventWaitHandle, though.

Järgmine lehekülg »

The Rubric Theme. Blog at WordPress.com.


Get every new post delivered to your Inbox.

Join 83 other followers