FizzBuzz using C# yield

Yield.

[TestClass]
public class FizzBuzzTest
{
    [TestMethod]
    public void Test1()
    {
        var iEnumerableString = new FizzBuzz().GenerateFizzBuzzUpto(100);
        var list = iEnumerableString.ToList();
        Assert.IsTrue(list[0] == "Fizz:3");
        Assert.IsTrue(list[1] == "Buzz:5");
        Assert.IsTrue(list[6] == "FizzBuzz:15");
    }
}
public class FizzBuzz
{
    public IEnumerable<string> GenerateFizzBuzzUpto(int numberUpto)
    {
        for (var counter = 1; counter < numberUpto; counter++)
        {
            if (counter%3 == 0 && counter%5 == 0)
            {
//The use of the yield keyword controls the iterator’s behavior. If the consumer requests an iterator 
//to produce a value, it runs until a yield statement is encountered. At that point, the iterator is 
//suspended until the consumer asks for the next value.
                yield return $"FizzBuzz:{counter}";
            }
            if (counter % 3 == 0)
            {
                yield return $"Fizz:{counter}";
            }
            if (counter % 5 == 0)
            {
                yield return $"Buzz:{counter}";
            }
        }
    }
}
Continue Reading

Concurrent and immutable Collections in C#-Primer

Concurrent(or Threadsafe) collections allow multiple threads to update them simultaneously in a safe way. Concurrent collections are more efficient than implementing a regular collection with a lock.
An immutable collection cannot actually be modified. Instead, to modify an immutable collection, you create a new collection that represents the modified collection.

The .Net framework has several different collection types.
ImmutableList<T> Use this data structure when
a. the collection data does not change very often
b. the collection can be accessed by multiple threads safely.
c. They allow indexing like Lists but they have lower performance than Lists.

ImmutableStack<T> Use this data structure when
a. you need a first-in, first-out data structure
b. the collection data does not change very often
b. the collection can be accessed by multiple threads safely.
c. ImmutableStack have lower performance than Stack data structures.

ImmutableQueue<T> Use this data structure when
a. you need a first-in, last-out data structure
b. the collection data does not change very often
b. the collection can be accessed by multiple threads safely.
c. ImmutableQueue have lower performance than Queue data structures.

ImmutableDictionary<T, TValue> is a key-value collection of items. Use this type when you
a. need a key-value collection of items.
b. the collection data does not change very often
c. can be accessed by multiple threads safely.
d. the items in ImmutableDictionary have an unpredictable order.
Performance of ImmutableDictionary is faster than ImmutableSortedDictionary.

ImmutableSortedDictionary<T, TValue> is a key-value collection of items sorted by key. Use this type when you
a. need a key-value collection of items.
b. the collection data does not change very often
c. can be accessed by multiple threads safely.
d. the items are sorted in the collection.

ImmutableHashSet<T> is just a collection of unique items. Use this type when you
a. do not need to store duplicates
b. the collection data does not change very often
c. can be accessed by multiple threads safely.
d. the items in the ImmutableHashSet have an unpredictable order.
Performance of ImmutableHashSet is faster than ImmutableSortedHashSet.

ImmutableSortedSet<T> is a sorted collection of unique items. Use this type when you
a. do not need to store duplicates
b. the collection data does not change very often
c. can be accessed by multiple threads safely.
d. the items are sorted in the collection.

ConcurrentDictionary<T, TValue> is a key-value collection of items. Use this type when you
a. need a key-value collection of items.
b. can be accessed by multiple threads safely.
Use the ConcurrentDictionary<T, TValue> when you have multiple threads reading and writing to the shared collection. If the updates are more rare then the ImmutableDictionary<T, TValue> is a better choice.

Continue Reading

C# Tuple

Tuple.
The Tuple is a typed, immutable, generic construct. It has many items, each item can have any type(even complex items like array inside it). The Tuple type is a class. Once we create the Tuple, we cannot change the values of its fields.
Tuple is generally used as a short-term container.

using System;
class Program
{
    static void Main()
    {
        Tuple<int, string, bool> tuple =new Tuple<int, string, bool>(1, "cat", true);
        Console.WriteLine(tuple.Item1);
        Console.WriteLine(tuple.Item2);
        Console.WriteLine(tuple.Item3);
    }
}

Output
1
cat
True

The Tuple.Create method returns a reference to a tuple. eg: var tuple = Tuple.Create(“cat”, 2, true);

Continue Reading

C# Func and Action types

The Func type provides a way to store anonymous methods. For the Func type, the first type parameters are the arguments to the methods, and the final type parameter is the return value.

Example.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void FuncTypeTest()
    {
        Func<string, bool> validator =
        word =>
        {
            var count = word.Length;
            return count > 4;
        };
        var isValid = validator("AjitGoel");
        Assert.IsTrue(isValid);
    }
}

Action type objects do not return a value. They are similar to a void method.
A Func type on the other hand returns a result.

Action<int> action1 = (int counter) => Console.WriteLine("Write {0}", counter);
Continue Reading

Generate fibonacci series

Lately I have been reading up on interview related questions. One of the other favorite interview questions interviewers have is to “write a program to generate fibonacci set of series for a user defined input number”. In mathematics, the Fibonacci numbers are the numbers in the following integer sequence(Fibonacci sequence)
0,1,1,2,3,5,8,13,21,34,55,89,144………….
So if the user inputs 8 then the output should be
0,1,1,2,3,5,8,13.

Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void GenerateFibonanciSeries()
        {
            var result = new StringHelper().GenerateFibonanciSeries(8);
            Assert.AreEqual(result[0], 0);
            Assert.AreEqual(result[1], 1);
            Assert.AreEqual(result[2], 1);
            Assert.AreEqual(result[3], 2);
            Assert.AreEqual(result[4], 3);
            Assert.AreEqual(result[5], 5);
            Assert.AreEqual(result[6], 8);
            Assert.AreEqual(result[7], 13);
        }
    }

    public class StringHelper
    {
         public List<long> GenerateFibonanciSeries(long numbersToGenerate)
        {
            if (numbersToGenerate <= 0)
            {
                throw new ArgumentException();
            }
            var result = new List<long>();
            long previousNumber = 0;
            long currentNumber = 1;
            result.Add(previousNumber);
            result.Add(currentNumber);
            for (int counter= 2; counter < numbersToGenerate; counter++)
            {
                long tempNumber = currentNumber + previousNumber;
                result.Add(tempNumber);
                previousNumber = currentNumber;
                currentNumber = tempNumber;                
            }
            return result;
        }
    }
}
Continue Reading

Is string same as its reversed string(i.e Is it a Palindrome)

Lately I have been reading up on interview related questions. One of the favorite interview questions interviewers have is to “write a program to check if a string is the same as its reversed string i.e check that a string is a Palindrone”. To make it more interesting, they ask to not use Array.Reverse.

Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void IsStringSameAsItsReversedStringThatIsItIsAPalinDrome()
        {
            var result=new StringHelper().IsStringSameAsItsReversedStringThatIsItIsAPalinDrome("Anna");
            Assert.AreEqual(result, true);
        }
    }

    public class StringHelper
    {
         public bool IsStringSameAsItsReversedStringThatIsItIsAPalinDrome(string tempString)
        {
            if(String.IsNullOrEmpty(tempString))
            {
                throw new ArgumentException();
            }
            var tempStringLower= tempString.ToLower();
            var tempArray= tempStringLower.ToCharArray();
            var tempArray1 = Reverse(tempArray);
            var reversedString=new string(tempArray1);
            if (reversedString.Equals(tempStringLower))
                return true;
            return false;
        }
        //This function just reverses a array of characters.
        private char[] Reverse(char[] characters)
        {
            for(int counter=0; counter<characters.Length/2;counter++)
            {
                char character = characters[counter];
                characters[counter] = characters[characters.Length - counter -1];
                characters[characters.Length - counter - 1] = character;
            }
            return characters;
        }
    }
}
Continue Reading

Compute value of string that has numbers seperated by arithmetic operators.

One of my friends recently went to an interview to a very well known startup company. It is supposed to hire only the very best technical people in the industry.  One of the problems that he was asked to write a unit test was,

Suppose a string has numbers separated by arithmetic operators, how do you compute the value of it?

BTW, I personally feel that you are not really testing the knowledge of a person by asking such questions and expecting them to solve it in 6 minutes.

Solution

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Data;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var operator1= new Operator();
            int result = operator1.Maths("2+3");
            Assert.AreEqual(result, 5);
        }

        [TestMethod]
        public void TestMethod2()
        {
            var operator1 = new Operator();
            int result = operator1.Maths("2+3*4");
            Assert.AreEqual(result, 14);
        }
        [TestMethod]
        public void TestMethod3()
        {
            var operator1 = new Operator();
            int result = operator1.Maths("2+3*10/5");
            Assert.AreEqual(result, 8);
        }
    }

    public class Operator
    {
        public int Maths(string operation)
        {
            object result=new DataTable().Compute(operation, null);
            return Int32.Parse(result.ToString());
        }
    }
}
Continue Reading

Adapter Pattern with a twist

One of my friends recently went to an interview to a very well known startup company. It is supposed to hire only the very best people in the industry.  One of the problem that he was asked to white board was:

You have a robot that can turn left and right. It can also move forward and backwards. You have a legacy robot that can only turn right and move forward. You want the legacy robot to turn left and to move backwards. Design a adapter class that would allow the legacy robot to turn right and to move backwards.

Solution

Adapter Design Pattern With A Twist

using System;
using System.Collections.Generic;
using System.Linq;
public interface IRobot
{
    void GoFront(int noOfSteps);
    void GoBack(int noOfSteps);
    void TurnRight(int degrees);
    void TurnLeft(int degrees);
}
public class LegacyRobot
{
    public void GoFront(int noOfSteps)
    {
    }
    public void TurnRight(int degrees)
    {
    }
}
public class Robot : IRobot
{
    public void GoFront(int noOfSteps)
    {
    }
    public void GoBack(int noOfSteps)
    {
    }
    public void TurnRight(int degrees)
    {
    }
    public void TurnLeft(int degrees)
    {
    }
}
public class LegacyRobotAdapter : IRobot
{
    LegacyRobot legacyRobot;
    public LegacyRobotAdapter(LegacyRobot legacyRobot)
    {
        this.legacyRobot = legacyRobot;
    }
    public void GoFront(int noOfSteps)
    {
        this.legacyRobot.GoFront(noOfSteps);
    }
    //The legacy robot can go back by turning right by 180 degrees
    //then going front by the number of steps requested by the client
    //then turning right by 180 degrees to be facing from where the robot started from. 
    public void GoBack(int noOfSteps)
    {
        this.legacyRobot.TurnRight(180);
        this.legacyRobot.GoFront(noOfSteps);
        this.legacyRobot.TurnRight(180);
    }
    public void TurnRight(int degrees)
    {
        this.legacyRobot.TurnRight(degrees);
    }
    //The legacy robot can turn left by turning right by 360 degrees minus the client requested degrees to turn
    public void TurnLeft(int degrees)
    {
        this.legacyRobot.TurnRight(360 - degrees);
    }
}
Continue Reading