Another One For Interview … This Time Recursion

Recursion has been famous technique of eliminating loop and breaking the execution of code into regular call of methods.
Some times your interview is going good and there comes recursion which just shocks you….
It is simple but it’s simplicity makes you in trouble especially during strict time bound interview.
Basically recursion is a technique of calling a method from it’s own method.
It is similar to divide and break the complex logic into simple executable code.
Key to remember before starting to code any recursion solution is this equation

F(n)=F(x) + – F(n)

.
Where F(n) calls it self multiple times using the old value.

Let say we have to multiply two positive unknown values without using the multiplication sign.
So the function would
F(0) =b+F(1) —– F(1)=b+F(0) …. and so on ….

So lets write the code.

using System;

public class Test
{
public static void Main()
{
int d= multiply (10,2);
Console.WriteLine(d);
}
public static int multiply(int a,int b)
{
if(b==0)
{
return 0;
}
else
{
return a+multiply(a,b-1);
}
}
}

 

Here you can see the function is calling itself and reusing the old returned value until and unless value becomes 0. We can do factorial and division using the same technique with little bit enhancement.

 

Advertisements

1 million prime number generation in less then half of a second …

This is an optimized code of prime number generation.
This question was asked in an entry test of a software house that how can you generate 1 million prime numbers in less then a second.
I wrote the code that generates the prime number and add to a list in 0.39 seconds to be specific 390.8387 milliseconds.

Important key point here to understand is that except 2 no even number is prime so that is why i have started it from 3 and increment 2 so by this why we will not be checking any even number.
public static void prime()
{
List l = new List(1000000);

l.add(1);
l.add(2);
for (uint i = 3; i < 1000000; i += 2)
{
bool isprime = true;
for (uint j = 3; j*j <= i; j += 2)
{
if (i % j == 0)
{
isprime = false;
break;
}
}
if (isprime == true)
{
l.Add(i);
//Console.WriteLine(i);
}
}
}

And to execute code and also calculate the running time you will need the following code.

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
prime();//Prime Function
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
Console.WriteLine("RunTime " + stopWatch.Elapsed.TotalMilliseconds);

Interview- Swamping two variables

This is a simple question that how to swap two values let say a and without using third variable. But this question gets confusing when you are asked to swap negative and positive value together.
Let say a=2
b=-3
Now swap a value into b and b value into a.

So the code will be:-

{
int a;
int b;
a=2;
b=-3;
a=b-a;
b=-(a)+b;
a=a+b;
Console.WriteLine(“a=”+a);

Console.WriteLine(“b=”+b);
}

a=-3
b=2

The good part about this code is that you can enter any value in a or b whether negative or positive it will swap it with ease.

The Use of Using statement in C#

After reading the topic heading many readers will refer the using keyword which is use in the top of the code in C# some thing like this 

using system.Data;

But right now i am referring to another using statement which is also the part of C#. The syntax of this statement is some thing like this 

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // execute sql statement here on the connection you created
}

This statement is use in place of a try catch statement where you may need to add a try block and a catch block. So instead of these two statements the using statement automatically calls IDesposible method after the work is done on a resource it also automatically closes the connection even when there is an exception which  means it also removes the extra code used for finally statement.

 
 if (myRes!= null)
            // Call the object's Dispose method.
            ((IDisposable)myRes).Dispose();

Stack Push Operation on Link List C#

Now i will be presenting the implementation  of stack on linked list.

Every body would be aware of coding stack on arrays which is a very simple step. But some people find difficulty while implementing the stack on link list.
First you should know what is a stack, Stack or LIFO Stack (last in first out) is a type of data structure which is use to put the values in a proper from and is implemented in various computer programs, It contains one entry and exit point from where values can push in or pop out of the Stack.
*/for more details on stack you can view stack description at (www.farazashraf.wordpress.com/stack)*/

Link List is also another form of data structure which contains item and it’s linking next node.
*/for more details on stack you can view stack description at (www.farazashraf.wordpress.com/linklist)*/

So i will implementing the stack push operation in link list.
It will be done through a C# class which i have named test_Stack.
It contains the private variable first which will be null.
A private inner class Node is used to declare string item and next node.
A bool method is just used to check if the first node is empty .

class test_Stack
    {
        private Node first = null;
        private class Node
        {
            public string item ;
            public Node next;
        }
       public bool check()
        {
            return first == null;
        }
       public void push(string item)
        {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
        
        }
You can call the method in the main function to check if the class is working fine. By just creating an object and calling the method.

static void Main(string[] args)
        {
            test_Stack test1 = new test_Stack();
            string item=null;
            int i=2;
            while (i != 0)
            {
                Console.WriteLine(“enter the test value”);
                item = Console.ReadLine();
                test1.push(item);
                i–;
            }
       

Common Tool Box Initializing With C# Code

  • Ø Button Common Properties

Button newButton[20]=new Button();

For(int i=1;i<=20;i++)

newButtons[i] = new Button();

newButtons[i].ForeColor=Color.Green;

newButtons[i].BackColor = Color.Gray;

newButtons[i].Name = “Button4” + i.ToString();

newButtons[i].Click += new EventHandler(NewButtons_Click);

newButtons[i].Text = buttontext[i];

newButtons[i].Location = new System.Drawing.Point(350, 350);

newButtons[i].Size = new System.Drawing.Size(76, 38);

newButtons[i].Font = FontStyle.Bold;

newButton[i].TabIndex=I;

newButton[i].Enabled=true;

newButton[i].Dock=BockStyle.Left;

this.Controls.Add(newButtons[i]);

newButton[i].FlatStyle = FlatStyle.Flat;
  • Ø Common Label
  • propertie Description

 

Label label1 = new Label();

label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
label1.ImageList = imageList1;
label1.ImageIndex = 1;
label1.ImageAlign = ContentAlignment.TopLeft;
label1.UseMnemonic = true;
label1.Text = "First &Name:";
label1.Name=”LABEL!”;
label.Font = new Font("Georgia", 16);

label1.Font = FontStyle.Bold;

label1TabIndex=I;

label1Enabled=true;

 
label1.Size = new Size (label1.PreferredWidth, label1.PreferredHeight);
this.Controls.Add(label1);

label1.TextAlign  = HorizontalAlignment.Center;

int size = label1.TextLength;

 

  • Ø TextBox Common Properties

TextBox T1 = new TextBox();

 
T1.Text = "First &Name:";
T1.Name=”LABEL!”;
Tl.Font = new Font("Georgia", 16);

T1.Font = FontStyle.Bold;

T1.TabIndex=I;

T1.Enabled=true;

T1.Size = new Size (370,240);
      this.Controls.Add(T1);
       T1.Multiline=True; 
       T1. ReadOnly=True;
       T1.UseSystemPasswordChar=True;
 
  • Panel properties Description
  • CheckBox Common Properties
Panel p1=New Panel();
This.Control.Add(P1);
P1. AutoScroll=true;
P1. BorderStyle=BorderStyle.Fixed3d;
 
CheckBox checkBox1 = new CheckBox();

checkBox1.Text = “created”;

checkBox1.Name = “Created”;

checkBox1.Location = newPoint(50, 50);

checkBox1.ForeColor = System.Drawing.Color.White;

checkBox1.BackColor = System.Drawing.Color.Black

checkBox1.TabIndex = 2;

 
checkBox1.Appearance = Appearance.Button;
 
 
checkBox1.AutoCheck = false;
Controls.Add(checkBox1);
  • RadioButton Common Properties

  • PictureBox Common Properties
RadioButton Rb=New RadioButton();
Rb.Checked=true;
 
PictureBox PictureBox1=New PictureBox();
Image image = Image.FromFile("BeigeMonitor1.png");

PictureBox1.Name = “Created”;

PictureBox1.Location = newPoint(50, 50);

PictureBox1.ForeColor = System.Drawing.Color.White;

PictureBox1.BackColor = System.Drawing.Color.Black

PictureBox1.TabIndex = 2;

 
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
this.Control.Add(PictureBox1);
 
 
  • ToolTip properties Common Properties

 

ToolTip toolTip1=New ToolTip();

toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
toolTip1.ShowAlways = true;
 
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
 
 
  • NumericUpDown Common Properties
 

 
NumaricUpDown numericUpDown1 = new NumericUpDown();
numericUpDown1.Value = 5;

numericUpDown1.Name = “Created”;

numericUpDown1.Location = newPoint(50, 50);

numericUpDown1.ForeColor = System.Drawing.Color.White;

numericUpDown1.BackColor = System.Drawing.Color.Black

numericUpDown1.TabIndex = 2;

 
numericUpDown1.Maximum = 2500;
numericUpDown1.Minimum = -100;
numericUpDown1.DecimalPlaces = 0;
numericUpDown1.Increment = 0.25M;
numericUpDown1.ThousandsSeparator = true;
numericUpDown1.Hexadecimal = true;
This.Control.Add(numaricUpDown1);
 
  • MenuStrip and ToolStripMenuItem  Properties

MenuStrip ms = new MenuStrip();

ms.Value = 5;

ms.Name = “Created”;

ms.Location = newPoint(50, 50);

ms.ForeColor = System.Drawing.Color.White;

ms.BackColor = System.Drawing.Color.Black

ms.TabIndex = 2;

 

ToolStripMenuItem windowMenu = new ToolStripMenuItem(“Window”);

ToolStripMenuItem windowNewMenu = new ToolStripMenuItem(“New”, null, new EventHandler(windowNewMenu_Click));

 

windowMenu.DropDownItems.Add(windowNewMenu);

((ToolStripDropDownMenu)(windowMenu.DropDown)).ShowImageMargin = false;

((ToolStripDropDownMenu)(windowMenu.DropDown)).ShowCheckMargin = true;

 

ms.MdiWindowListItem = windowMenu;

 

ms.Items.Add(windowMenu);

 

ms.Dock = DockStyle.Top;

 

this.MainMenuStrip = ms;

this.Control.Add(ms);

 
·        MonthCalendar properties
MonthCalendar monthCalendar1=new MonthCalendar();
     this.monthCalendar1 = new System.Windows.Forms.MonthCalendar();
this.monthCalendar1.Location = new System.Drawing.Point(47, 16);
this.monthCalendar1.BackColor = System.Drawing.SystemColors.Info;
this.monthCalendar1.ForeColor = System.Drawing.Color.FromArgb(
((System.Byte)(192)), ((System.Byte)(0)), ((System.Byte)(192)));
this.monthCalendar1.TitleBackColor = System.Drawing.Color.Purple;
this.monthCalendar1.TitleForeColor = System.Drawing.Color.Yellow;
this.monthCalendar1.TrailingForeColor = System.Drawing.Color.FromArgb(
((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(0)));
this.monthCalendar1.AnnuallyBoldedDates =
new System.DateTime[] { new System.DateTime(2002, 4, 20, 0, 0, 0, 0),
new System.DateTime(2002, 4, 28, 0, 0, 0, 0),
new System.DateTime(2002, 5, 5, 0, 0, 0, 0),
new System.DateTime(2002, 7, 4, 0, 0, 0, 0),
new System.DateTime(2002, 12, 15, 0, 0, 0, 0),
new System.DateTime(2002, 12, 18, 0, 0, 0, 0)};
this.monthCalendar1.CalendarDimensions = new System.Drawing.Size(4, 3);
this.monthCalendar1.FirstDayOfWeek = System.Windows.Forms.Day.Monday;
this.monthCalendar1.MaxSelectionCount = 21;
this.monthCalendar1.ScrollChange = 1;
this.monthCalendar1.ShowWeekNumbers = true;
this.Control.Add(monthCalendar1);
  • DateTimePicker Properties
  • LinkLabel Common Properties
DateTimePicker dateTimePicker1 = new DateTimePicker();
 
dateTimePicker1.MinDate = new DateTime(1985, 6, 20);
dateTimePicker1.MaxDate = DateTime.Today;
 
dateTimePicker1.CustomFormat = "MMMM dd, yyyy - dddd";
dateTimePicker1.Format = DateTimePickerFormat.Custom;
 
dateTimePicker1.ShowCheckBox = true;
dateTimePicker1.ShowUpDown = true;
 
 

LinkLabel linkLabel1=new LinkLabel1();

this.linkLabel1 = new System.Windows.Forms.LinkLabel();
linkLabel1.Value = 5;

linkLabel1.Name = “Created”;

linkLabel1.ForeColor = System.Drawing.Color.White;

linkLabel1.BackColor = System.Drawing.Color.Black

linkLabel1.TabIndex = 2;

 
this.linkLabel1.Location = new System.Drawing.Point(34, 56);
this.linkLabel1.Size = new System.Drawing.Size(224, 16);
this.linkLabel1.AutoSize = true;

this.linkLabel1.DisabledLinkColor = System.Drawing.Color.Red;
this.linkLabel1.VisitedLinkColor = System.Drawing.Color.Blue;
this.linkLabel1.LinkBehavior =  System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabel1.LinkColor = System.Drawing.Color.Navy;
 
this.linkLabel1.TabIndex = 0;
this.linkLabel1.TabStop = true;
 
 
 
this.linkLabel1.LinkArea = new System.Windows.Forms.LinkArea(0,8);
 
this.linkLabel1.Links[0].Visited = true;
this.linkLabel1.Text = "www.FarazAshraf.WordPress.com";
 

 

 

 

 

  • ListBox Common Properties
ListBox listBox1 = new ListBox();

listBox1.Text = “created”;

listBox1.Name = “Created”;

listBox1.ForeColor = System.Drawing.Color.White;

listBox1.BackColor = System.Drawing.Color.Black

listBox1.TabIndex = 2;

 
listBox1.Size = new System.Drawing.Size(200, 100);
listBox1.Location = new System.Drawing.Point(10,10);
this.Controls.Add(listBox1);
listBox1.MultiColumn = true;
listBox1.SelectionMode = SelectionMode.MultiExtended;
 
 
listBox1.BeginUpdate();
for (int x = 1; x <= 50; x++)
{
listBox1.Items.Add("Item " + x.ToString());
}
listBox1.EndUpdate();
 
 
listBox1.SetSelected(1, true);
listBox1.SetSelected(3, true);
listBox1.SetSelected(5, true);
System.Diagnostics.Debug.WriteLine(listBox1.SelectedItems[1].ToString());
System.Diagnostics.Debug.WriteLine(listBox1.SelectedIndices[0].ToString());
 
·        RichTextBox Properties
 

RichTexMYTEXTBOX MYRICHTEXMYTEXTBOXOX = newRichTexMYTEXTBOX();

this.Controls.Add(MYRICHTEXMYTEXTBOXOX);

MYRICHTEXMYTEXTBOXOX.Text = “created”;

MYRICHTEXMYTEXTBOXOX.Dock = DockStyle.Fill;

MYRICHTEXMYTEXTBOXOX.Name = “created”;

MYRICHTEXMYTEXTBOXOX.Enabled = true;

MYRICHTEXMYTEXTBOXOX.Location = newPoint(250,100);

MYRICHTEXMYTEXTBOXOX.ForeColor = System.Drawing.Color.Blue;

MYRICHTEXMYTEXTBOXOX.BackColor = System.Drawing.Color.Brown;

MYRICHTEXMYTEXTBOXOX.TabIndex = 7;

MYRICHTEXMYTEXTBOXOX.Size = newSystem.Drawing.Size(100,50);

 

 

 

  • Ø ListView Common Properties

ListView listView1 = new ListView();

listView1.Name = “Created”;

listView1.ForeColor = System.Drawing.Color.White;

listView1.BackColor = System.Drawing.Color.Black

listView1..TabIndex = 2;

 

 

listView1.Bounds = new Rectangle(new Point(10,10), new Size(300,200));

    listView1.View = View.Details;

  listView1.LabelEdit = true;

    listView1.AllowColumnReorder = true;

listView1.CheckBoxes = true;

listView1.FullRowSelect = true;

    listView1.GridLines = true;

    listView1.Sorting = SortOrder.Ascending;

ListViewItem item1 = new ListViewItem(“item1”,0);

item1.Checked = true;

item1.SubItems.Add(“1”);

item1.SubItems.Add(“2”);

item1.SubItems.Add(“3”);

ListViewItem item2 = new ListViewItem(“item2”,1);

item2.SubItems.Add(“4”);

item2.SubItems.Add(“5”);

item2.SubItems.Add(“6”);

ListViewItem item3 = new ListViewItem(“item3”,0);

// Place a check mark next to the item.

    item3.Checked = true;

item3.SubItems.Add(“7”);

item3.SubItems.Add(“8”);

item3.SubItems.Add(“9”);

 

    listView1.Columns.Add(“Item Column”, -2, HorizontalAlignment.Left);

    listView1.Columns.Add(“Column 2”, -2, HorizontalAlignment.Left);

    listView1.Columns.Add(“Column 3”, -2, HorizontalAlignment.Left);

    listView1.Columns.Add(“Column 4”, -2, HorizontalAlignment.Center);

 

       listView1.Items.AddRange(new ListViewItem[]{item1,item2,item3});

 

ImageList imageListSmall = new ImageList();

ImageList imageListLarge = new ImageList();

 

    imageListSmall.Images.Add(Bitmap.FromFile(“C:\\MySmallImage1.bmp”));

    imageListSmall.Images.Add(Bitmap.FromFile(“C:\\MySmallImage2.bmp”));

    imageListLarge.Images.Add(Bitmap.FromFile(“C:\\MyLargeImage1.bmp”));

    imageListLarge.Images.Add(Bitmap.FromFile(“C:\\MyLargeImage2.bmp”));

 

listView1.LargeImageList = imageListLarge;

    listView1.SmallImageList = imageListSmall;

 

this.Controls.Add(listView1);

 

 

  • Ø Tree View Common Properties 
  treeView1 = new TreeView();
      treeView1.Location = new Point(0, 25);
        treeView1.Size = new Size(292, 248);
        treeView1.Anchor = AnchorStyles.Top | AnchorStyles.Left | 
            AnchorStyles.Bottom | AnchorStyles.Right;
        treeView1.CheckBoxes = true;
node = treeView1.Nodes.Add(String.Format("Node{0}", x*4));
node = node.Nodes.Add(String.Format("Node{0}", x*4 + y));
treeView1.Nodes[1].Nodes[0].Nodes[0].Checked = true;
treeView1.ExpandAll();
 

        treeView1.BeforeCollapse += checkForCheckedChildren;

        treeView1.CollapseAll();
 
        treeView1.BeforeCollapse -= checkForCheckedChildren;
        treeView1.EndUpdate();

this.Control.Add(treeView1);

 

 

 

 

 

  • Form Common Properties

AcceptButton Button that is clicked when Enter is pressed.

AutoScroll bool value that allows or disallows scrollbars when needed.

CancelButton Button that is clicked when the Escape key is pressed.

FormBorderStyle Border style for the Form (e.g., none, single, three-dimensional).

Font Font of text displayed on the Form, and the default font for controls added to the Form.

Text Text in the Form’s title bar.

 

 

ASCII input …

using System;
using System.Text;

class ASCIIEncodingExample {
public static void Main() {
// The encoding.
ASCIIEncoding ascii = new ASCIIEncoding();

// A Unicode string with two characters outside the ASCII code range.
String unicodeString =
“This Unicode string contains two characters ” +
“with codes outside the ASCII code range, ” +
“Pi (\u03a0) and Sigma (\u03a3).”;
Console.WriteLine(“Original string:”);
Console.WriteLine(unicodeString);

// Save positions of the special characters for later reference.
int indexOfPi = unicodeString.IndexOf(‘\u03a0’);
int indexOfSigma = unicodeString.IndexOf(‘\u03a3’);

// Encode string.
Byte[] encodedBytes = ascii.GetBytes(unicodeString);
Console.WriteLine();
Console.WriteLine(“Encoded bytes:”);
foreach (Byte b in encodedBytes) {
Console.Write(“[{0}]”, b);
}
Console.WriteLine();

// Notice that the special characters have been replaced with
// the value 63, which is the ASCII character code for ‘?’.
Console.WriteLine();
Console.WriteLine(
“Value at position of Pi character: {0}”,
encodedBytes[indexOfPi]
);
Console.WriteLine(
“Value at position of Sigma character: {0}”,
encodedBytes[indexOfSigma]
);

// Decode bytes back to string.
// Notice missing Pi and Sigma characters.
String decodedString = ascii.GetString(encodedBytes);
Console.WriteLine();
Console.WriteLine(“Decoded bytes:”);
Console.WriteLine(decodedString);
}
}