James Michael Hare

...hare-brained ideas from the realm of software development...
posts - 142 , comments - 1176 , trackbacks - 0

My Links

News

Welcome to my blog! I'm a Sr. Software Development Engineer who has been performing C++/C#/Java development for over 20 years, but have definitely learned that there is always more to learn!

All thoughts and opinions expressed in my blog and my comments are my own and do not represent the thoughts of my employer.

Blogs I Read

Follow BlkRabbitCoder on Twitter

Tag Cloud

Archives

Post Categories

C# 6

Little Puzzler Solutions

Thursday, March 26, 2015

C#/.NET Little Wonders: String Interpolation in C# 6

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. 

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

For those who haven’t been keeping up with the announcements, allow me to take some blog time for the next few Little Wonders posts to talk about some of the neat new things that will be part of C# 6. 

Then, once it’s available for you to consume, you can hit the ground running with an arsenal of new little ways to make your code cleaner and more maintainable.

String Formatting

Often times, when you want to log information to a file, console, or status label you end up having to format that information into a string.  There are, of course, several ways to do this.  The problem is that the more complex your formatting gets, the harder it is to understand and maintain the code.

For example, let’s say we have a very simple class representing a Point:

   1: public class Point
   2: {
   3:     public int X { get; set; }
   4:     public int Y { get; set; }
   5: }

And we have a pair of points (perhaps bounding a rectangle) that we wish to log:

   1: var p1 = new Point { X = 5, Y = 10 };
   2: var p2 = new Point { X = 7, Y = 3 };

We could, of course, perform string concatenation to do this:

   1: Console.WriteLine("The area of interest is bounded by (" 
   2:     + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");     

This works fine and performs relatively well (multiple string concatenations in the same statement are generally optimized with a behind-the-scenes StringBuilder).  However, the problem is that the more things we concatenate together, the harder it is to understand the original intention of the output statement because it is broken up by multiple opening and closing quotes and the concatenation operator (+).

To some extent, we can make this a bit better by using String.Format() and other methods (such as Console.WriteLine) that accept a format, for example:

   1: Console.WriteLine("The area of interest is bounded by({0},{1}) and ({2},{3})", 
   2:     p1.X, p1.Y, p2.X, p2.Y);

This solves the problem of breaking up the formatting with quotation marks and the concatenation operator, however, it also creates new problems. 

First of all, you have to maintain the position of the placeholders and the order of the arguments.  Thus, if you need to add a new item earlier in the string, you’d either have to bump up all the other indexes or add the new item at the end and have your placeholders out of order:

// inserting before means bumping the index of each other placeholder up
Console.WriteLine("The area of interest for {0} is bounded by({1},{2}) and ({3},{4})",
    "My Rectangle", p1.X, p1.Y, p2.X, p2.Y);
 
// putting it at the end means your arguments are not in their actual display order
Console.WriteLine("The area of interest for {4} is bounded by({0},{1}) and ({2},{3})", 
    p1.X, p1.Y, p2.X, p2.Y, "My Rectangle");

Neither of these are fully desirable since you now have to make sure any change you make to the string or arguments keeps the two in sync.  And this can be especially bad if you have a placeholder for an argument index that no longer exists:

   1: // Oops, Removed the argument, but forgot the placeholder
   2: Console.WriteLine("The area of interest for {4} is bounded by({0},{1}) and ({2},{3})", 
   3:     p1.X, p1.Y, p2.X, p2.Y);

It isn’t a compiler error, but a runtime error, which may pop up when you least expect it, especially if it’s not on a well travelled code branch:

   1: Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
   2:    at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   3:    at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   4:    at System.String.Format(IFormatProvider provider, String format, Object[] args)
   5:    at System.IO.TextWriter.WriteLine(String format, Object[] arg)
   6:    at System.IO.TextWriter.SyncTextWriter.WriteLine(String format, Object[] arg)
   7:    at System.Console.WriteLine(String format, Object[] arg)
   8:    at VNextScratchpad.Program.Main(String[] args) in C:\source\VNextScratchpad\Program.cs:line 31

There has to be a happy medium between the two.  On one hand, concatenation is nice because it has everything right in its actual place in the string, but the syntax is cumbersome as the string gets longer.  On the other hand, formatting is nice because it makes the string very clean but then it separates the placeholders from the arguments.

Well, that is what string interpolation sets out to fix in C# 6.  This is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well.

What this means is that you will be able to embed expressions in the actual string you are trying to build by enclosing them with “\{“ and “}”.

For example, the line of output from before now looks like:

   1: // notice how the expressions are now embedded in the string itself
   2: Console.WriteLine("The area of interest is bounded by (\{p1.X},\{p1.Y}) and (\{p2.X},\{p2.Y})");

It looks a lot like the String.Format() placeholders, but instead of an index, it is prefaced by an escape backslash and the expression is inside the curly braces.  In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

Advanced Formatting with Interpolation

Because interpolation is really compile-time magic and syntactical sugar for String.Format(), you can use alignment and format arguments (See the MSDN on Composite Formatting) in the placeholder as well. 

Consider the syntax for a format element placeholder:

{index[,alignment][:formatString]}

The only difference with interpolation is that we will replace the index with the expression. 

For example, consider the code on the MSDN Composite Formatting page:

for (int ctr = 0; ctr < names.Length; ctr++)
   Console.WriteLine("{0,-20} {1,5:N1}", names[ctr], hours[ctr]);

We can change this to take advantage of interpolation and make it:

for (int ctr = 0; ctr < names.Length; ctr++)
    Console.WriteLine("\{names[ctr],-20} \{hours[ctr],5:N1}");

This means that names[ctr]’s value will be left justified and padded to 20 spaces, and hours[ctr]’s value will take 5 spaces and be formatted as a number 1 digit behind the decimal point.

This feature is currently available in the preview for VisualStudio 2015 and C# 6, though it’s possible they may simplify the syntax in the final release – there’s talk of using a $ prefix on the string to specify an interpolated string, much like the current @ prefix to specify a verbatim string.

Summary

String interpolation is yet another tool that will be coming out in C# 6 that will allow you to make code easier to maintain.  By embedding the values directly in the string to print, there is less confusion as to what values go with what placeholder – but you still maintain the ability to specify formatting as well.

Stay tuned for more Little Wonders of C# 6!

Posted On Thursday, March 26, 2015 9:39 PM | Comments (0) | Filed Under [ My Blog C# Software .NET Little Wonders C# 5.0 And Beyond MyBlog ]

Monday, March 23, 2015

Little Puzzlers–Is Tree a Binary Search Tree?

I like to keep my brain sharp by working on programming puzzlers. On off weeks I'm going to start posting programming puzzlers I've collected over the years. Hopefully you'll find them as entertaining as I do.

The Problem:

Given a standard definition of a binary tree node, i.e.:

   1: public class Node<T>
   2: {
   3:     ​T Data { get; set; }
   4:     Node<T> Left { get; set; }
   5:     Node<T> Right { get; set; }
   6: }

And a reference to the root of the tree:

   1: Node<T> root = ....;

Write a method that will determine if the tree has the ordered property.  A binary tree has the ordered property such that for any node x, the left sub-tree of x is < x and the right sub-tree of x is > x for all nodes. 

Examples:

That is, the following tree has the ordered property:

           5

        /    \        

      3        7      

    /   \     /       

   2     4   6     

But this tree does not:               

           5

        /    \        

      3        8      

    /   \     /       

   2     6   7     

Because even though 6 is on the right of 3 and is > 3, it is on the left sub-tree of 5 so it must be < 5.

Spoiler Alert

Fair Warning: discussion of the problem and potential solutions may be discussed in the comments below. 

Posted On Monday, March 23, 2015 9:05 AM | Comments (21) |

Thursday, March 19, 2015

C#/.NET Little Wonders: Auto-property initialization in C# 6

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. 

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

For those who haven’t been keeping up with the announcements, allow me to take some blog time for the next few Little Wonders posts to talk about some of the neat new things that will be part of C# 6. 

Then, once it’s available for you to consume, you can hit the ground running with an arsenal of new little ways to make your code cleaner and more maintainable.

Auto-Property Initialization

Remember than in C#, auto-properties are a way to create the boilerplate code for a basic, field-backed property in C#. 

For instance, if you wanted to create a Point class with members X, and Y you used to have to define that with code like this:

   1: public class Point
   2: {
   3:     private int x;
   4:     private int y;
   5:  
   6:     public int X
   7:     {
   8:         get { return x; }
   9:         set { x = value; }
  10:     }
  11:  
  12:     public int Y
  13:     {
  14:         get { return y; }
  15:         set { y = value; }
  16:     }
  17: }

The developers on the C# team realized that this was really just standard boiler-plate for accessors and mutators.  You were simply defining a backing field with the get returning the field and the set assigning the field, so they allowed a syntactical shortcut called auto-properties:

   1: public class Point
   2: {
   3:     public int X { get; set; }
   4:  
   5:     public int Y { get; set; }
   6: }

Essentially, these two classes are nearly identical behind the scenes.  Both still have the backing fields, but in the second example the compiler is the one creating the backing field and naming it and hiding all that boilerplate code for you.  You are simply saying in the { get; set; } that you wish for it to generate a getter and a setter.

Similarly, if you want the setter to be private (like in an immutable class) you can modify the access for either the set to make it different:

   1: // Make Point immutable by passing value in constructor and setting privately
   2: public class Point
   3: {
   4:     // setters now private
   5:     public int X { get; private set; }
   6:  
   7:     public int Y { get; private set; }
   8:  
   9:     public Point(int x, int y)
  10:     {
  11:         X = x;
  12:         Y = y;
  13:     }
  14: }

This is all well and good, but there has been for quite some time a disparity between VB.NET and C#.NET around auto-properties.  Namely, VB.NET allowed you to assign a non-default initialization value to an auto-property, but C# did not.

For example, let’s say you are creating a resource pool and you want an auto-property for the pool size, but you want it to default to 10, not 0.  You used to have to do this by setting the value in the constructor, (or by abandoning the auto-property and creating a field):

   1: public class ResourcePool
   2: {
   3:     // couldn't initialize an auto-property before
   4:     int PoolSize { get; set; }
   5:  
   6:     // would have to set in constructor if you wanted a different value on construction
   7:     public ResourcePool()
   8:     {
   9:         PoolSize = 10;
  10:     }
  11:  
  12:     // ...
  13: }

With VB.NET, they’ve had the ability to initialize an auto-property for a while now.  But finally, with C# 6.0, we get that feature as well. 

This means the code above could now look like this:

   1: public class ResourcePool
   2: {
   3:     // can now set an initialization value, no longer have to set in constructor
   4:     int PoolSize { get; set; } = 10;
   5:  
   6:     // ...
   7: }

Notice that now, you can assign an initialization value to the property right after the closing brace.  Simple and intuitive!

This also means that you can create immutable properties without needing a setter, for instance if we wanted to add a MaxPoolSize that would be exposed as a property (instead of an exposed const field):

   1: public class ResourcePool
   2: {
   3:     // true read-only property, has no setter 
   4:     public static int MaxPoolSize { get; } = 50;
   5:  
   6:     // ...
   7: }

Notice that there is no setter at all (not even private).  Thus once this field is created it keeps its initial value permanently.

Summary

C# 6.0 is going to add several Little Wonders that can help make your code cleaner and easier to maintain.  Stay tuned next time (in between my puzzlers) for more up-and-coming C# 6.0 goodness!

Posted On Thursday, March 19, 2015 4:19 PM | Comments (1) |

Sunday, March 15, 2015

Solution–Little Puzzlers: First Non-Repeating Character

This is the way I would go about this problem if I were asked to perform it at an evaluation. However, keep in mind there are multiple ways to solve this, so don't worry if your solution has variations.

When solving these sorts of problems, the first thing you should do before writing any code is test your assumptions and clarify requirements. Often times tech companies use these sort of questions to see if you just dive into coding with no set design, or if you really think out the edge cases.

First thing I would do would be to question the makeup of the sequence of characters. The example shows only letters, but it's possible the example given was just being simplistic so I shouldn't assume that. If the person asking the problem would reply that yes, indeed, it is only letters (assuming English), I would then ask if they would conflate uppercase and lower case letters or if they'd consider them separate. Once I know my full problem space, I can pick the best data structure for the task.

I would definitely not try to read the entire stream into a list​, as this could get very memory intensive if the stream is extremely long (since it's unbounded). Thus, I should look for ways to solve the problem as I go in one linear pass.

So, for each character, I want to be able to note, in effect, two things:

  1. Have i seen it before, and
  2. Where did i first see it.

So, we could either design a small POCO to hold the position and whether it was found, or we could use the same indicator for both. After all, we only care about position if we don't find a duplicate.

If I were just dealing with uppercase letters, I would build an array of int and initialize all elements to -1. Or if I were dealing with a larger data set, I'd use a Dictionary<char,int>. Then, for each char pass, I'd look it up in the array/table. If the char doesn't exist in the table, or if it's -1 in the array, I'd note the position as the current position.

If the char does exist in the table or in the array, I'd set it to another value such as int.MaxValue. Then, once I've read all the characters, I'd find the minimum position in the table where pos >= 0 (linear pass) and print the pos and the char as long as pos != int.MaxValue.

Let’s assume that the examiner asked for only the uppercase alphabet, but you can imagine how to modify this example for different input variations.

using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

// Base interface for char stream 
public interface ICharStream
{
    bool HasNext { get; }
    char GetNext();
}

// Test implementation of char stream 
public class RandomCharStream : ICharStream
{
    private readonly int maxSize;
    private readonly Random generator = new Random();
    private int generatedCount;

    // Creates a random stream of characters 
    public RandomCharStream(int maxSize)
    {
        this.maxSize = maxSize;
        this.generatedCount = 0;
    }

    // Returns true if still characters to generate 
    public bool HasNext
    {
        get { return generatedCount < maxSize; }
    }

    // Generates a random character  
    public char GetNext()
    {
        ++generatedCount;
        return (char)('A' + generator.Next(0, 26));
    }
}

// Solution for problem 1 
public class Problem1
{
    public static void Main()
    {
        var charMap = Enumerable.Repeat(-1, 26).ToArray();
        var stream = new RandomCharStream(20);

        int pos = 0;
        while (stream.HasNext)
        {
            var ch = stream.GetNext();
            var index = ch - 'A';

            Console.Write(ch + " ");
            if (charMap[index] != int.MaxValue)
            {
                charMap[index] = charMap[index] == -1 ? pos : int.MaxValue;
            }
            ++pos;
        }
        Console.WriteLine();
        int firstNonRepeatedPos = charMap.Where(i => i >= 0).Min();

        if (firstNonRepeatedPos != int.MaxValue)
        {
            Console.WriteLine("The first non - repeated char was at position: " + firstNonRepeatedPos);
        }
        else { 
            Console.WriteLine("All characters were repeated at least once.");
        }
    }
}

Posted On Sunday, March 15, 2015 8:54 PM | Comments (21) |

Monday, March 9, 2015

Little Puzzlers: First Non-Repeating Character

I like to keep my brain sharp by working on programming puzzlers. On off weeks I'm going to start posting programming puzzlers I've collected over the years. Hopefully you'll find them as entertaining as I do.

The Problem

​Given an unbounded sequence of characters, find the value and position of the first non-repeated character.

e.g., in the stream: A,B,C,D,C,B,A,F,A,F the first non-repeated character is D.

For the purposes of this exercise, consider the following interface as the source of the stream:

   1: // C#
   2: public interface ICharStream
   3: {
   4:     bool HasNext { get; }
   5:     char GetNext();
   6: }

Spoiler Alert

Fair Warning: discussion of the problem and potential solutions may be discussed in the comments below. 

Posted On Monday, March 9, 2015 9:22 AM | Comments (22) |

Powered by: