Cut the sticks

Problem source: https://www.hackerrank.com/challenges/cut-the-sticks

You are given N sticks, where the length of each stick is a positive integer. A cut operation is performed on the sticks such that all of them are reduced by the length of the smallest stick.

Suppose we have six sticks of the following lengths:

5 4 4 2 2 8

Then, in one cut operation we make a cut of length 2 from each of the six sticks. For the next cut operation four sticks are left (of non-zero length), whose lengths are the following:

3 2 2 6

The above step is repeated until no sticks are left.

Given the length of N sticks, print the number of sticks that are cut in subsequent cut operations.

Note: For each cut operation, you have to recalcuate the length of smallest sticks (excluding zero-length sticks).

Input Format
The first line contains a single integer N.
The next line contains N integers: a0, a1,…aN-1 separated by space, where ai represents the length of ith stick.

Output Format
For each operation, print the number of sticks that are cut, on separate lines.

Constraints
1 ≤ N ≤ 1000
1 ≤ ai ≤ 1000

Sample Input #00

6
5 4 4 2 2 8

Sample Output #00

6
4
2
1

Sample Input #01

8
1 2 3 4 3 3 2 1

Sample Output #01

8
6
4
1

 

class Cut_The_Stick
{
static void Main(string[] args)
{
int noOfSticks = Convert.ToInt32(Console.ReadLine());
string strInput = Console.ReadLine();
List<int> list = new List<int>();
int min = 0;
list.AddRange(strInput.Split(‘ ‘).Select(x => Convert.ToInt32(x)));

while (list.Count() > 0)
{
Console.WriteLine(list.Count());
min = list.Min();
list = list.Select(x => x – min).Where(x => x > 0).ToList();
}
Console.ReadKey();
}
}

Check whether a given number’s binary format is Palindrome or not in C#

I/p: 5

Binary format of 5: 101

Palindrome: True

 

class Binary_Palindrome_Number
{
static void Main(string[] args)
{
ConsoleKeyInfo keyPress;
do
{
Console.WriteLine(“Enter a number:”);
int num = Convert.ToInt32(Console.ReadLine());
string numBinary = num.ConvertToBinary();
bool isPalindrome = CheckPalindromeNUmber(numBinary);
Console.WriteLine(string.Format(“Binary format of given number {0} is {1} and it is {2} Palindrome number.”, num, numBinary, isPalindrome ? “a” : “not a”));
Console.WriteLine(“Press Esc key to exit or any key to continue…”);
keyPress = Console.ReadKey();
}
while (keyPress.Key != ConsoleKey.Escape);
}

private static bool CheckPalindromeNUmber(string num)
{
int start = 0, end = num.Length – 1;
bool flag = true;
while (start <= end)
{
if (!num[start].Equals(num[end]))
{
flag = false;
break;
}
else
{
++start;
–end;
}
}
return flag;
}
}

public static partial class ExtensionMethods
{
public static string ConvertToBinary(this int num)
{
string strBinary = string.Empty;
while (num > 0)
{
strBinary += num % 2;
num = num / 2;
}

return strBinary.ReverseString();
}

public static string ReverseString(this string str)
{
string sb = string.Empty;
for (int i = str.Length – 1; i >= 0; –i)
{
sb += str[i];
}

return sb;
}
}

Encapsulation in OOPs.

Encapsulation is the ability of an object oriented language (C# in this context) to hide unnecessary implementation details from the object user. Encapsulation makes coding simpler and helps to preserve data integrity.

According to the concept of encapsulation, an object’s internal data should not be directly accessible from an object instance. Members of a class that represent an object’s state should not be marked as public. The state of an object should only be altered indirectly by using public members. C# prefers properties to encapsulate data.

Ex.

class ABC
{
// private data members
private int roll;
private int class;
private string name;
// public properties
public int Roll
{
get { return roll; }
set { roll = value; }
}
public int Class
{
get { return class; }
set { class = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
// constructor
public ABC()
{
// values are assigned to data members via properties
Roll = 10;
Class = 9;
Name = “Sunil Kumar Meena”;
}
}

Polymorphism in OOPs.

Polymorphism is the ability of an object oriented language (C# in this context) to allow a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendents. A class’s polymorphic interface is constructed using any number of virtual or abstract members.
A virtual member is a member in a base class that defines a default implementation that may be changed (overridden) by a derived class.
In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type.
In either case (virtual or abstract), when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.
Method Overriding – Method Overriding is a process in which a derived class can define its own version of a method, which was originally defined by its base class.
Virtual Keyword – The virtual keyword indicates that the base class wants to define a method which may be (but does not have to be) overridden by a derived class. A virtual method provides a default implementation that all derived types automatically inherit. If a child class so chooses, it may override the method but does not have to.
Note: Subclasses are never required to override virtual methods.
Override Keyword – The override keyword is used by a derived class to to change the implementation details of a virtual method (defined in the base class). Each overridden method is free to leverage the default behavior of the parent class using the base keyword.
Sealed Keyword – The sealed keyword is basically applied to classes to prevent other types from extending its behavior via inheritance.
It can also be applied to virtual methods to prevent derived types from overriding those methods. Ex.
public override sealed void GiveBonus(float amount)
{
}
Any effort to override the above sealed method in the derived class will generate compile time error.
Abstract Classes – The abstract keyword can be used in the class definition to prevent direct creation of an instance of the class. Although abstract classes cannot be created directly, it is still assembled in memory when derived classes are created. Thus, it is perfectly fine for abstract classes to define any number of constructors that are called indirectly when derived classes are allocated.
An abstract class can define any number of abstract members (members that does not supply a default implementation, but must be accounted for by each derived class).
The polymorphic interface of an abstract base class simply refers to its set of virtual and abstract methods. Methods marked with abstract are pure protocol. They simply define the name, return type (if any), and parameter set (if required).
If you do not override an abstract method (of the base abstract class) in the derived class, the derived class will also be considered abstract, and would have to be marked abstract with the abstract keyword.
Although it is not possible to directly create an instance of an abstract base class, you can freely store references to any subclass with an abstract base variable.

Static Constructors – What is the output of the C# code?

class A
{
  public A(string text)
  {
    Console.WriteLine(text);
  }
}
 
class B
{
  static A a1 = new A(“a1”);
 
  A a2 = new A(“a2”);
 
  static B()
  {
    a1 = new A(“a3”);
  }
 
  public B()
  {
    a2 = new A(“a4”);
  }
}
 
class Program
{
  static void Main(string[] args)
  {
    B b = new B();
  }
}
Before any code of the type B gets executed, its static constructor will be invoked first. It initializes static data fields and then executes statements inside the static constructor. Therefore, it prints a line of “a1”, and then another line of “a3”.
When the execution flow reaches the statement B b = new B(), the ordinary constructor is invoked. It initializes its data fields first and then the statements in its constructor method, so it prints a line of “a2”, and then another line of “a4”.
Output:
a1
a3
a2
a4

Operator overloading in C#.

Overloading is one of the best concept introduced in OOPs and it also supports Operator overloading. Sometime we don’t want actual functionality of operator in that case we need to overload that operator. For example in case of ‘+’ operator I want to multiple the result with 2 that is:

double opp1=5, opp2=10, result=0;

Actual result:

result = opp1 + opp2;  // 15

I want:

result = opp1 + opp2; // 30

class OperatorOverLoading
    {
        static void Main()
        {
            Operators opp1, opp2, result;
            Console.WriteLine(“Please enter two values: “);

            // user input
            opp1 = new Operators(Convert.ToDouble(Console.ReadLine()));
            opp2 = new Operators(Convert.ToDouble(Console.ReadLine()));

            // + operator overloading, (first sum two values and then double this value)
            result = opp1 + opp2;
            result.Show(“Result for operator ‘+’ :”);

            // + operator overloading, (first sum two values and then double this value)
            result = opp1 – opp2;
            result.Show(“Result for operator ‘-‘ :”);

            // + operator overloading, (first sum two values and then double this value)
            result = opp1 * opp2;
            result.Show(“Result for operator ‘*’ :”);

            // + operator overloading, (first sum two values and then double this value)
            result = opp1 / opp2;
            result.Show(“Result for operator ‘/’ :”);
        }
    }

    class Operators
    {
        // variable declaration
        double opp1, result;

        // default constructor
        public Operators()
        {
        }

        // parameterized constructor
        public Operators(double x)
        {
            opp1 = x;
        }

        // method that will display final result
        public void Show(string msg)
        {
            Console.WriteLine(msg + result);
            Console.ReadLine();
        }

        // method that overloads + operator’s actual functionality
        public static Operators operator +(Operators x, Operators y)
        {
            Operators op = new Operators();
            op.result = (x.opp1 + y.opp1) * 2;
            return op;
        }

        // method that overloads – operator’s actual functionality
        public static Operators operator -(Operators x, Operators y)
        {
            Operators op = new Operators();
            op.result = (x.opp1 – x.opp1) * 2;
            return op;
        }

        // method that overloads * operator’s functionality
        public static Operators operator *(Operators x, Operators y)
        {
            Operators op = new Operators();
            op.result = (x.opp1 * y.opp1) * 2;
            return op;
        }

        // method that overloads / operator’s functionality
        public static Operators operator /(Operators x, Operators y)
        {
            Operators op = new Operators();
            op.result = (x.opp1 / y.opp1) * 2;
            return op;
        }
    }

For more details: http://www.msdotnet.co.in/2013/07/operator-overloading-in-c.html?utm_source=feedburner&utm_medium=email&utm_campaign=Feed%3A+msdotnet+%28Microsoft+.NET%29

Abstraction in OOPs

Abstraction means to show essential details to the client.

Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT. When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine? No but what matter to you is that Gear must get changed that’s it!! This is abstraction; show only the details which matter to the user.

Encapsulation the mechanism by which Abstraction is implemented.

Example1: I have class Animal and I am making a sub class of the class Animal called Tiger.
Then I will say that its color is yellow and running is very fast.
Also I can make the class Hippo but it’s color is black and running is very slow.
This is an example of Abstraction.

Example2: Abstraction , we have a class car and we’ve declared it as abstract, there another class called Audi that inherits car class and implement its method with its own functionalities, there are one more class called BMW, and it also inherits car class and implements its method with its own functionality. Both classes BMW & Audi implemented the same method with different functionalities, this is called abstraction.

Interfaces are again a form of absstraction , Getter/Setter (properties) are abstraction , Delegates are abstraction  , Lambda and LINQ are abstraction.

public abstract class Car{
    public abstract void StartCar();
}
 public class Audi : Car{
    #region Overrides of Car
     public override void StartCar(){
        UseCarKey();
    } 
    #endregion
} 
public class BMW : Car{
    #region Overrides of Car 
    public override void StartCar()    {
        UseCarChipcard();
    } 
    #endregion
}