Tuesday, 3 June 2014

Interview resources


Reverse a number
using System;  
  public class ReverseExample  
   {
     public static void Main(string[] args)  
      {
       int  n, reverse=0, rem;           
       Console.Write("Enter a number: ");      
       n= int.Parse(Console.ReadLine());     
       while(n!=0)      
       {   
        rem=n%10;     
        reverse=reverse*10+rem;   
        n/=10;   
       }   
       Console.Write("Reversed Number: "+reverse);       
    }
  }
  

reverse a string #1

  static void Main() {

      string myStr, rev;

      myStr = "Tom";
      rev ="";

      Console.WriteLine("String is {0}", myStr);

      // find string length
      int len;
      len = myStr.Length - 1;

      while (len >= 0) {
         rev = rev + myStr[len];
         len--;
      }
      Console.WriteLine("Reversed String is {0}", rev);
      Console.ReadLine();
   }

Reverse a string #2

 public static string ReverseString(string s)
    {
        char[] arr = s.ToCharArray();
        Array.Reverse(arr);
        return new string(arr);
    }

Reverse a string #3 with loop


public static string ReverseStringDirect(string s)
    {
        char[] array = new char[s.Length];
        int forward = 0;
        for (int i = s.Length - 1; i >= 0; i--)
        {
            array[forward++] = s[i];
        }
        return new string(array);
    }

Reverse a string with extension method

string s = "olleh";
s.Reverse();
They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:
public static string Reverse(this string input)
{
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}


FibonacciExample  :

using System;  
  public class FibonacciExample  
   {  
     public static void Main(string[] args)  
      {  
         int n1=0,n2=1,n3,i,number;    
         Console.Write("Enter the number of elements: ");    
         number = int.Parse(Console.ReadLine());  
         Console.Write(n1+" "+n2+" "); //printing 0 and 1    
         for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed    
         {    
          n3=n1+n2;    
          Console.Write(n3+" ");    
          n1=n2;    
          n2=n3;    
         }    
      }  
   } 


calculate steps
public static class CalculateSteps
    {
        public static int CalculateTotalStrides(int[] flights, int stepsPerStride)
        {
            //1. You will be given the number of strpes in each fight in an integer[] flights.
            //2. you will be given an integer StairsPerStride 
             Validate(flights, stepsPerStride);
           
            int numberOfStrides = 0;
 
            //loop through each flight in
            foreach (int flight in flights)
            {
                //Get numbner of strides per each flight and add it to totasl
                numberOfStrides += (flight / stepsPerStride);
 
                //check for remiander and add one if any remaining for extra stride
                if (flight % stepsPerStride != 0)
                {
                    numberOfStrides++;
                }
            }
            //add on the 2 steps for the landing for each floor
            var totalStrides = (numberOfStrides + (flights.Length - 1) * 2);
            return totalStrides;
        }
 
        private static void Validate(int[] stairs, int stride)
        {
 
            //Rule 1: staircase is between 1 and 50 stairs inclusive
            if (stairs.Length < 1 || stairs.Length > 50)
            {
                throw new ArgumentOutOfRangeException("flights are out of range.");
            }
            //rule 2: flight of stairs between 5 and 30 steps
            if (stairs.Any(nextFlight => nextFlight < 5 || nextFlight > 30))
            {
                throw new ArgumentOutOfRangeException("Stairs are out of range.");
            }
            // rule 3: stepsPerStride is between 2 and 5
            if (stride >= 2 && stride <= 5)
                throw new ArgumentOutOfRangeException("Stride is out of range.");
        }


call run up stairs


//Run Up the stairs 
           int[] flights = new int[7];
           flights[0] = 5;
           flights[1] = 11;
           flights[2] = 9;
           flights[3] = 13;
           flights[4] = 8;
           flights[5] = 30;
           flights[6] = 14;
           var result = CalculateSteps.CalculateTotalStrides(flights, 3);
 
          Console.Write(result);
           Console.ReadLine();

unit tests 

[TestMethod]
public void CalculateTotalStrides_StaircaseIsValid_Max50()
{
    int[] flights = new int[0];
 
    // Act
    var actual = CalculateSteps.CalculateTotalStrides(flights, 3);
 
    // Assert
    var expected = "flights are out of range.";
    Assert.AreEqual(expected, actual);
}
 
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void CalculateTotalStrides_StaircaseIsValid_Min1()
{
 
    // Arrange
    //min amount of staircases is 1
    int[] flights = new int[51];
 
    // Act
    var actual = CalculateSteps.CalculateTotalStrides(flights, 3);
 
    // Assert
   var expected = "flights are out of range.";
   Assert.AreEqual(expected, actual);
}

Adding

///Adding this , adding that
            var first = new byte[] { 1, 1, 255 };
            var sec = new byte[] { 0, 0, 1 };
            var result = AddingThisAddingThat.AddRecursive(first, sec);
 
            Console.Write(result);
            Console.ReadLine();


public static byte[] AddRecursive(byte[] a, byte[] b)
        {
            //#1
            //byte[] ret = new byte[first.Length + second.Length];
            //Buffer.BlockCopy(first, 0, ret, 0, first.Length);
            //Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
            //return ret;
 
            //#2
            //List<byte> list1 = new List<byte>(first);
            //List<byte> list2 = new List<byte>(second);
            //list1.AddRange(list2);
            //byte[] sum2 = list1.ToArray();
            //return sum2;
 
            //#3
            if (a.Length == 0) return new byte[] { };
 
            return
                new byte[] { (byte)(a[0] + b[0]) }.Concat(
                AddRecursive(a.Skip(1).ToArray(), b.Skip(1).ToArray())
                ).ToArray();
        }

[TestClass]
  public class AddingThisAddingThat_Test
  {
      [TestMethod]
 
     public void Add_UsingARecursiveAlgorithm_ValuesAreAdded()
        {
            //First Test
            byte[] expectedResult = AddingThisAddingThat.AddRecursive(new byte[] { 1, 1, 1 }, new byte[] { 1, 1, 1 }).Reverse().ToArray();
            Assert.AreEqual(expectedResult, new byte[] { 2, 2, 2 });
            //Sec Test
            expectedResult = AddingThisAddingThat.AddRecursive(new byte[] { 1, 1, 255 }, new byte[] { 0, 0, 1 }).Reverse().ToArray();
            Assert.AreEqual(expectedResult, new byte[] { 1, 1, 0 });
            //Third Test
            expectedResult = AddingThisAddingThat.AddRecursive(new byte[] { 255, 255, 255 }, new byte[] { 255, 255, 255 }).Reverse().ToArray();
            Assert.AreEqual(expectedResult, new byte[] { 255, 255, 254 });
        }
  }

More sample unit tests 

[TestMethod] public void Withdraw_ValidAmount_ChangesBalance() { // arrange double currentBalance = 10.0; double withdrawal = 1.0; double expected = 9.0; var account = new CheckingAccount("JohnDoe", currentBalance); // act account.Withdraw(withdrawal); double actual = account.Balance; // assert Assert.AreEqual(expected, actual); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void Withdraw_AmountMoreThanBalance_Throws() { // arrange var account = new CheckingAccount("John Doe", 10.0); // act account.Withdraw(20.0); // assert is handled by the ExpectedException }


Refactor the code under test

First, define two constants for the error messages at class scope. Put these in the class under test, BankAccount:

public const string DebitAmountExceedsBalanceMessage = "Debit amount exceeds balance";
public const string DebitAmountLessThanZeroMessage = "Debit amount is less than zero";

Then, modify the two conditional statements in the Debit method:

if (amount > m_balance)
    {
        throw new ArgumentOutOfRangeException("amount", amount, DebitAmountExceedsBalanceMessage);
    }

    if (amount < 0)
    {
        throw new ArgumentOutOfRangeException("amount", amount, DebitAmountLessThanZeroMessage);
    }

or

[[TestMethod]
public void Debit_WhenAmountIsMoreThanBalance_ShouldThrowArgumentOutOfRange()
{
    // Arrange
    double beginningBalance = 11.99;
    double debitAmount = 20.0;
    BankAccount account = new BankAccount("Mr. Bryan Walton", beginningBalance);

    // Act
    try
    {
        account.Debit(debitAmount);
    }
    catch (ArgumentOutOfRangeException e)
    {
        // Assert
        StringAssert.Contains(e.Message, BankAccount.DebitAmountExceedsBalanceMessage);
        return;
    }

    Assert.Fail("The expected exception was not thrown.");
}
Links to resources
https://www.c-sharpcorner.com/UploadFile/dacca2/fundamental-of-unit-testing-understand-mock-object-in-unit/

https://docs.microsoft.com/en-us/visualstudio/test/quick-start-test-driven-development-with-test-explorer?view=vs-2019

http://www.srimanjavagroup.com/thread/java-se-faq-8217-s-and-interview-questions-java-se/5273/interview-questions-state-street-corporation.htm

https://www.javatpoint.com/fibonacci-series-in-csharp

https://www.javatpoint.com/wcf-interview-questions

https://www.csharpstar.com/csharp-program-to-reverse-a-number-check-if-it-is-a-palindrome/
https://www.geeksforgeeks.org/count-set-bits-in-an-integer/

Delegate
Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
That works well in most situations. Sometimes, however, we don't want to call a function directly - we'd like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged.
By defining a delegate, you are saying to the user of your class "Please feel free to put any method that match this signature here and it will be called each time my delegate is called".
Lambda

A delegate will allow us to specify what the function we'll be calling looks like without having to specify which function to call

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.


A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type,