Everyone Is An Achiever

Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

Wednesday, January 14, 2015

Represent a number as a character string

1:21 AM Posted by Unknown 7 comments


Hello everyone,
Today we'll do something simple, cool and useful. Today we'll learn how to get the character representation of a number, for example: the number: 2456 is "Two Thousand Four Hundred Fifty Six"
You need such feature whenever you deal with bills and invoices.
Before we go to the code (although it could be lengthy but extremely easy) let's talk in theory first.
whenever we have a number, for example 2456, we pronounce the number starting from the left most to the right most; the 2, then 4, then 5, then 6. And for sure you know the place value of 2 which thousands, 4 is hundreds, 5 tens and lastly 6 which is the ones place. So, in our code we will 
1- accept the number from the user
2- split the number into digits, see [improved] Convert a whole integer to an array of integers
3- start reading the first location (that is 2 in this example)
4- store the corresponding character string of the number (Two Thousand in this example)
5- remove it so that the next number will hold the first location
6- keep reading the first location and storing the corresponding character strings one after the other until you reach the last number

You can think of this going in a hierarchy from the top level (left most number) to the first level (right most number)
In the following program 4 functions, the first one is for single digits (the ones place value) the second is for 2 digits (the tens place value), the third is for 3 digits (the hundred place value), the fourth is for 4 digits ( the thousands place value). And I created one extra function as a special case and I called it teen family which is for the numbers from 10 to 19.

How it works?
1- we first determine how many digits is the number?
2- we start from the top level,e.g. 2456 we'll start from the the 4 digits function
3- after storing the value of the first number, we remove it from the list and call the second downward function
4- in the 3 digit function we check whether the remaining numbers are in the category of teen family, if yes then we call the teen family instead of two digit function, if not we call the two digit function
5- the process continue with the next level downward until we reach the single digit function
6- lastly, the alphabetical representation of the number is returned to the user

NOTE that the code will work for number between 1 up to 9999. You can extend the code more if you like :)

lets, look at the code
1- main() code:

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

namespace NumbertoAlphabetsRepresentaiton
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number:");
            string number = Console.ReadLine();
            ConvertToIntegers conv = new ConvertToIntegers();
            byte[] numberArray = conv.doConvert(number);
            
            NumberToAlphabets nObj = new NumberToAlphabets();
            Console.WriteLine(nObj.Return(numberArray));

            Console.ReadLine();
        }
    }
}
2- NumberToAlphabets code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NumbertoAlphabetsRepresentaiton
{
    class NumberToAlphabets
    {
        static string numberString = "";
        
       
        public string Return(byte[] number)
        {
            // we first creat a list and copy the number to it
            // the list is automatically rezieable which is what we look for here
            List list = new List();
            for (int i = 0; i < number.Length; i++)
                list.Add(number[i]);

            int numberOfDigits = list.Count;
            //then we start by calling the correct function "the top most"
            if (numberOfDigits == 1)
                singleDigit(list);
            else if (numberOfDigits == 2)
                twoDigit(list);
            else if (numberOfDigits == 3)
                threeDigit(list);
            else if(numberOfDigits == 4)
                 fourDigit(list);

            return numberString;
        }
        //notice that we only check the location ZERO [0]
        //because this location will has the number we need to check
        //and after reading it we remove location [0] making the next number to hold this position
        private void singleDigit(List number)
        {
             if (number[0] == 1)
                numberString += "One";
            else if (number[0] == 2)
                numberString += "Two";
            else if (number[0] == 3)
                numberString += "Three";
            else if (number[0] == 4)
                numberString += "Four";
            else if (number[0] == 5)
                numberString += "Five";
            else if (number[0] == 6)
                numberString += "Six";
            else if (number[0] == 7)
                numberString += "Seven";
            else if (number[0] == 8)
                numberString += "Eight";
            else if (number[0] == 9)
                numberString += "Nine";
        }
        private void twoDigit(List number)
        {
           
            if (number[0] == 2)
                numberString += "Twinty ";
            else if (number[0] == 3)
                numberString += "Thirty ";
            else if (number[0] == 4)
                numberString += "Fourty ";
            else if (number[0] == 5)
                numberString += "fifty ";
            else if (number[0] == 6)
                numberString += "Sixty ";
            else if (number[0] == 7)
                numberString += "Seventy ";
            else if (number[0] == 8)
                numberString += "Eighty ";
            else if (number[0] == 9)
                numberString += "Ninty ";
            number.RemoveAt(0);
            singleDigit(number);
        }
        
        private void threeDigit(List number)
        {
            if (number[0] == 1)
                numberString += "One Hundred ";
            else if (number[0] == 2)
                numberString += "Two Hundred ";
            else if (number[0] == 3)
                numberString += "Three Hundred ";
            else if (number[0] == 4)
                numberString += "Four Hundred ";
            else if (number[0] == 5)
                numberString += "Five Hundred ";
            else if (number[0] == 6)
                numberString += "Six Hundred ";
            else if (number[0] == 7)
                numberString += "Seven Hundred ";
            else if (number[0] == 8)
                numberString += "Eight Hundred ";
            else if (number[0] == 9)
                numberString += "Nine Hundred ";
           
            number.RemoveAt(0);
            //here we check whether the rest number are between 10 and 19
            // if yes then we call the teenFamily() function
            //if the remaining number lets say [1][2] or [1][7]
            //we only check whther the location ZERO is == to 1
            //if yes then it is definitly a teen number
            if (number[0] == 1)
            {
                //in the list the numbers are stored individually [1][7]
                //and since we need the number to in full form lets say seventeen 17,
                //we add the first number + the second number + 9 => or you can add the second lcation [7] with 10 ;)
                int N = number[0] + number[1] + 9;
                    teenFamily(N);
            }
            else
                twoDigit(number);

        }
        private void fourDigit(List number)
        {
            if (number[0] == 1)
                numberString += "One Thousand ";
            else if (number[0] == 2)
                numberString += "Two Thousand ";
            else if (number[0] == 3)
                numberString += "Three Thousand ";
            else if (number[0] == 4)
                numberString += "Four Thousand ";
            else if (number[0] == 5)
                numberString += "Five Thousand ";
            else if (number[0] == 6)
                numberString += "Six Thousand ";
            else if (number[0] == 7)
                numberString += "Seven Thousand ";
            else if (number[0] == 8)
                numberString += "Eight Thousand ";
            else if (number[0] == 9)
                numberString += "Nine Thousand ";

            number.RemoveAt(0);
            threeDigit(number);
        }

        private void teenFamily(int teenNumber)
        {
            if (teenNumber == 10)
                numberString += "Ten ";
            else if (teenNumber == 11)
                numberString += "Eleven ";
            else if (teenNumber == 12)
                numberString += "Twilve ";
            else if (teenNumber == 13)
                numberString += "Thirteen ";
            else if (teenNumber == 14)
                numberString += "Fourteen ";
            else if (teenNumber == 15)
                numberString += "Fifteen ";
            else if (teenNumber == 16)
                numberString += "Sixteen ";
            else if (teenNumber == 17)
                numberString += "Seventeen ";
            else if (teenNumber == 18)
                numberString += "Eighteen ";
            else if (teenNumber == 19)
                numberString += "Ninteen ";
          
        }


    }
}

3- ConvertToIntegers code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NumbertoAlphabetsRepresentaiton
{
    class ConvertToIntegers
    {
        private byte[] numbers { get; set; }
        
        public byte [] doConvert(string strNumber)
        {
            numbers = new byte[strNumber.Length];
            for (int i = 0; i < numbers.Length; i++)
                numbers[i] =(byte)Convert.ToChar(strNumber[i] - '0');

            return numbers;
        }
        
    }
}


Download the solution here.
That's all. hope you enjoyed it.
Your comments are valuable to me and I'll be happy to read them.

Tuesday, January 13, 2015

[improved] Finding the missing numbers in a series

4:56 AM Posted by Unknown 4 comments


Hello everyone, today will improve the finding missing numbers program. In this improvements we will:

  •  find the missing elements and store them 
  •  capture the wrong entered elements 


So, I've been thinking about the ways I can handle this. Storing all numbers is not a big deal since you can use a list of integers and it will shrink or stretch automatically, the problem was in figuring out the wrong numbers.
I tried to develop some algorithms to handle it but I came across many possibilities and for each one I had to modify the code and add extra lines over and over again. So I thought: There might be a better way? Then I found a much more simpler way. What I did is that I tried to simulate what the user might want to do.
The user for example wants to enter a series that has 8 as a difference, lets say this series:
1 9 10 11 12 17 18 19 20 21 26 27 28 29 30 35 42

At first glance on the series you'll notice how mixed up it is. Since the first 2 numbers are always supposed to be correct, I assumed that the user is trying to get a series that has 8 difference between each two numbers and the maximum number cannot be more than 42, therefore, the series we're looking for is:
1 9 17 25 33 41

So, what I did is that I generated a new list apart from the original one containing the correct elements! that's it. You may say: What? but as I told you if you tried by yourself to design an algorithm to find each wrong number it will get really complicated and there will be tens of possibilities that you need to take into consideration, So, keep it simple :)

The drawback in this way is that it'll take extra space since you will use a new list. You can  optimize it by generating the numbers and over write the previous data on the same list.

In my program I maintained the original list and actually switched the original list to be a list of all wrong numbers and stored the correct series in a new list. here is the full CSharp code:

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace FindMissingNumbers

{

    class Program

    {

        static void Main(string[] args)

        {

            List originalSeries = new List();

            List newSeries = new List();



            Console.WriteLine("Enter the series initial size:");

            int n = int.Parse(Console.ReadLine());



            Console.WriteLine("Note:\n1-The series has equal difference between any two numbers, therefore,\n2-enter the first 2 elements correctly since they will be the key to find all missing elements");



            Console.WriteLine("Enter {0} elements:", n);

            for (int i = 0; i < n; i++)

                originalSeries.Add(int.Parse(Console.ReadLine()));



            Console.WriteLine("Your current series:");

            for (int i = 0; i < originalSeries.Count; i++)

                Console.Write(originalSeries[i] + " ");



          

            int difference = originalSeries[1] - originalSeries[0];

            int x = originalSeries[1] + difference;

          

            //setting the first two locations in the new series with the first two numbers from the original series since they're always correct

            newSeries.Add(originalSeries[0]);

            newSeries.Add(originalSeries[1]);



            // generating a correct list based on the difference and the maximum number entered in the series, mostly the last elements

            // we keep on generating untill the value of x become as the value (or greater) of the last number in the list (supposing it is the greatest number)

            for (int i = 0; x <= originalSeries[originalSeries.Count -1] ; i++)

            {

                newSeries.Add(x);

                x += difference;

            }



            //removing the correct numbers from the original series so that the original series will has all wrong numbers

            for (int i = 0; i < newSeries.Count; i++)

            {

               if(originalSeries.Contains(newSeries[i]))

                   originalSeries.Remove(newSeries[i]);

            }



            Console.WriteLine("\nCorrect series:");

            for (int i = 0; i < newseries.count; i++)                Console.Write(newSeries[i] + " ");



             Console.WriteLine("\nWrong elements:");

             for (int i = 0; i < originalSeries.Count; i++)

                 Console.Write(originalSeries[i] + " ");



            Console.ReadLine();

        }

      

    }

}


Sunday, January 4, 2015

Finding the missing numbers in a series

9:34 PM Posted by Unknown 2 comments


Hello everyone, Today's tutorial is fun. We'll be given a series of numbers that has the EXACT difference, and we will find the missing numbers between them.
Lets see an example. If we entered a series of initial 10 numbers as:
10 20 60 70 130 140 150 180 200 210
Since the difference between every two numbers is the same throughout the series, in this example we're missing 11 numbers:
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 210

Before going to the program part lets talk little bit in theory.
1) The difference between every two numbers is exactly equal thru the series. This is an important note since it will help us finding all the missing numbers

2) The number of missing numbers differs, which mean we need to create a mechanism to figure out how many missing numbers are there? What are they?. This is the core of our program

3) The first two numbers in the series must be present correctly. From them well figure out the missing number and achieve all the requirements

So, lets do the program. This is the full CSharp code, beneath it is the line-by-line explanation:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the series size:");
            int n = int.Parse(Console.ReadLine());
            int[] numbers = new int[n];

            
            Console.WriteLine("Note:\n1- The series has equal difference between any two numbers, therefore,\n2-enter the first 2 elements correctly since they will be the key to find all missing elements");

            Console.WriteLine("Enter {0} elements:", n);
            for (int i = 0; i < numbers.Length; i++)
                numbers[i] = int.Parse(Console.ReadLine());

            Console.WriteLine("Your series:");
            for (int i = 0; i < numbers.Length; i++)
                Console.Write(numbers[i] + " ");

            Console.WriteLine();

            int differenece = 0;
            int numberOFmissingEelements = 0;
            int x = 0;
          
            differenece = numbers[1] - numbers[0];
            for (int i = 1; i < numbers.Length; i++)
            {
                if (i == numbers.Length - 1)
                    break;

                if (numbers[i + 1] - numbers[i] != differenece)
                {
                    numberOFmissingEelements = (numbers[i + 1] - numbers[i] - differenece) / differenece;
                    x = numbers[i] + differenece; // take the current value in the series and add the difference to it which will be the first missing elements
                    for (int j = 0; j < numberOFmissingEelements; j++)
                    {
                        Console.WriteLine("Number {0} is missing", x);
                        x = x + differenece; // each time add the differene to the value of x

                    }
                }
            }
            Console.ReadLine();
        }
    }
}


  • We start by asking the user how much is the initial length of the series and we prompt a message to the user about the program. Then we ask the user to enter the numbers and we display them. Nothing serious here:

          
Console.WriteLine("Enter the series size:");
            int n = int.Parse(Console.ReadLine());
            int[] numbers = new int[n];

            
   Console.WriteLine("Note:\n1- The series has equal difference between any two numbers, therefore,\n2-enter the first 2 elements correctly since they will be the key to find all missing elements");

            Console.WriteLine("Enter {0} elements:", n);
            for (int i = 0; i < numbers.Length; i++)
                numbers[i] = int.Parse(Console.ReadLine());

            Console.WriteLine("Your series:");
            for (int i = 0; i < numbers.Length; i++)
                Console.Write(numbers[i] + " ");

            Console.WriteLine();


  • Now, lets convert the theory part into practice. We declared 3 integers, the first to hold the difference, the second to hold the number of missing numbers and third one will hold a missing number.

int differenece = 0;
            int numberOFmissingEelements = 0;
            int x = 0;


  • We first figure out the difference and this is pretty simple since we only subtract the second number from the first number.

differenece = numbers[1] - numbers[0];


  • Now we iterate thru a loop, in each iteration we check if the number[i+1] – number[i] is equal to the difference? If yes then there are NO missing numbers if it's NOT equal then there are a missing number or numbers. 

e.g.,
since the first two numbers are presented correctly, in the first iteration we check the difference between the 2nd and the 3rd numbers and if its equal to the initial difference calculated or not:
20 60
if (numbers[i + 1] - numbers[i] != differenece)

And since the difference is not equal to the initial difference which is 10, then there are missing numbers.
We then calculate How many missing numbers are there?
Consider our example, between 20 and 60 there are 3 missing numbers. To figure how many of them we will apply the following equation:
numberOFmissingEelements = (numbers[i + 1] - numbers[i] - differenece) / differenece;

applying it to our example:
numberOFmissingEelements = (60 – 20 – 10) / 10 = (30) / 10 = 3

 another example: 70 130
numberOFmissingEelements = (130 – 70 – 10) / 10 = (50) / 10 = 5 

and so forth.


  • The last thing is to print those number. The first missing number will be the current number + the difference, then we go through a loop to print them all.

                    x = numbers[i] + differenece;
                    for (int j = 0; j < numberOFmissingEelements; j++)
                    {
                        Console.WriteLine("Number {0} is missing", x);
                        x = x + differenece; // each time add the differene to the value of x

                    }

output:



That's it. In the improved version of this program, we will:
• Figure out all the missing numbers and store them
• Pick the wrong elements in the series. For example: 1 3 4 9 10 15 -> the program must pick the wrong entered numbers

 See you soon :)

Wednesday, December 31, 2014

Tuesday, December 30, 2014

program to calculate stems and leafs

1:34 PM Posted by Unknown No comments


After you got an idea about stems and leafs lets program it. I'm gonna do something different in this tutorial. I'll post the entire code at once, then I'll explain it line by line.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter the number of stems:");
            int stems = int.Parse(Console.ReadLine());
            string[][] stemsAndLeafs = new string[stems][];

            for (int i = 0; i < stemsAndLeafs.Length; i++)
                stemsAndLeafs[i] = new string[2];

            for (int i = 0; i < stems; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    if (j == 0)
                        Console.WriteLine("Enter stem {0} value", i + 1);
                    if (j == 1)
                        Console.WriteLine("Enter leafs of stem {0} seperated by space", i + 1);
                    stemsAndLeafs[i][j] = Console.ReadLine();
                }
            }

            Console.WriteLine("-----------------------");
            Console.WriteLine("Stems\tLeafs");
            for (int i = 0; i < stems; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    if (j == 0)
                        Console.Write(stemsAndLeafs[i][j] + "\t");
                    else
                        Console.Write(stemsAndLeafs[i][j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine("-----------------------");

            int[] sumOneRowValues = new int[stems];
            ConvertToIntegers con = new ConvertToIntegers();
           
            for (int i = 0; i < stems; i++)
            {

                string[] stringNumbers = stemsAndLeafs[i][1].Split(' ');
                byte[] leafs = con.doConvert(stringNumbers);
                sumOneRowValues[i] = doSum(stemsAndLeafs[i][0], leafs);

            }

            Console.WriteLine("Sum of all stems\n------------------");
            for (int i = 0; i < stems; i++)
                Console.WriteLine("sum of stem {0} = {1}", stemsAndLeafs[i][0], sumOneRowValues[i]);

            Console.ReadLine();
        }

        private static int doSum(string stem, byte[] leafs)
        {
            int sum = 0;

            int stemValue = (Convert.ToChar(stem) - '0') * 10;

            for (int i = 0; i < leafs.Length; i++)
                sum = sum + stemValue + leafs[i];
            return sum;
        }
    }
}

Lets start analyzing the code: First lets recall the example we used in the theory tutorial:
stem
leafs
1
2 3 5 6 7
2
1 1 0
3
0
4
9 8 2

• As you can see, the table has 1 column for stems and the second for leafs. Therefore, we will have a matrix of n * 2. The variable n is the number of stems are there, so we start the program by asking the user to enter the number of stems, then we instantiate a matrix of (stems * 2). But what data type do we have to use? Notice that the leafs part consist of numbers and white-spaces, hence we will create a string matrix of (stems * 2) order.

Console.WriteLine("Enter the number of stems:");
            int stems = int.Parse(Console.ReadLine());
            string[][] stemsAndLeafs = new string[stems][];

            for (int i = 0; i < stemsAndLeafs.Length; i++)
                stemsAndLeafs[i] = new string[2];

• Then we ask the user to enter the stems and leafs. The leafs should be separated by white-space

for (int i = 0; i < stems; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    if (j == 0)
                        Console.WriteLine("Enter stem {0} value", i + 1);
                    if (j == 1)
                        Console.WriteLine("Enter leafs of stem {0} seperated by space", i + 1);
                    stemsAndLeafs[i][j] = Console.ReadLine();
                }
            }
I used a conditions here to just print the proper message to the user. When (j == 0) it means that we are at the beginning of new row first column so in that case the value will be the stem's and when (j == 1) it means we are in the leafs column.
 • Then we print the stems and leafs

Console.WriteLine("-----------------------");
            Console.WriteLine("Stems\tLeafs");
            for (int i = 0; i < stems; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    if (j == 0)
                        Console.Write(stemsAndLeafs[i][j] + "\t");
                    else
                        Console.Write(stemsAndLeafs[i][j]);
                }
                Console.WriteLine();
            }
            Console.WriteLine("-----------------------");

Up to here you're just fine. If you need to do more calculation to the stems and leafs then continue. In this tutorial we will add the values of each row (a stem and its leafs).

• The steps are:
 Create an array that will have the same size as the number of stems and in this array we will add the sum of one row (a stem and its leafs). We will create a method to do the sum part

 Create an object to the class ConvertToInteger ( see the improved version of converting whole numbers into integers)
            int[] sumOneRowValues = new int[stems];
            ConvertToIntegers con = new ConvertToIntegers();

• Then:
 Splite the leafs by whitespace using Split(' ') function
 The returning type of the splitting is array of strings, so, call the conversion method in the ConvertToInteger class
 We create a byte leaf array that will hold the values of the leafs after converting them to integers
 Call the sum method and pass two arguments: the stem, the leaf array

for (int i = 0; i < stems; i++)
            {

                string[] stringNumbers = stemsAndLeafs[i][1].Split(' ');
                byte[] leafs = con.doConvert(stringNumbers);
                sumOneRowValues[i] = doSum(stemsAndLeafs[i][0], leafs);

            }


• Now print the values:
            Console.WriteLine("Sum of all stems\n------------------");
            for (int i = 0; i < stems; i++)
                Console.WriteLine("sum of stem {0} = {1}", stemsAndLeafs[i][0], sumOneRowValues[i]);

The last thing to mention is the doSum() method.
 The method receives the stem as string and the leafs as array of bytes
 We calculate the stem value. Since the stems are in the Tens place, we multiply the stem by 10 (read the theory part)
 We add the stem value to the leaf
private static int doSum(string stem, byte[] leafs)
        {
            int sum = 0;

            int stemValue = (Convert.ToChar(stem) - '0') * 10;

            for (int i = 0; i < leafs.Length; i++)
                sum = sum + stemValue + leafs[i];
            return sum;
        }

output:

That's all for now. Hope you enjoyed it :) 

[theory] Stem and leaf

10:01 AM Posted by Unknown No comments


 Stem and leaf theory
Lets start with a definition to stem and leaf plot.
A Stem and Leaf Plot is a special table where each data value is split into a "stem" (the first digit or digits) and a "leaf" (usually the last digit) [1]
Lets take an example to make it more clear. If you have the following table to represent the stems and leafs:
stem
leafs
1
2 3 5 6 7
2
1 1 0
3
0
4
9 8 2

The way we would read this table is:
For the first row:
12  13  15  16  17
The second row
21  21  20
The third row
30
The fourth row
49  48  42

The red numbers are the stems and the blue ones are the leafs. The stems will be the TENS place value where the leafs will be the ONES place value. This piece of information is important because it will help us in the calculation of stems and leafs.

Now that you got an idea about the stems and leafs let go and make a program to calculate it.


[1]- https://www.mathsisfun.com/data/stem-leaf-plots.html

[improved] Convert a whole integer to an array of integers

9:50 AM Posted by Unknown No comments
the class takes string  and returns byte of integers

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

namespace TectConsole
{
   class ConvertToIntegers
    {
        private byte[] numbers { get; set; }

        public byte[] doConvert(string strNumber)
        {
            numbers = new byte[strNumber.Length];
            for (int i = 0; i < numbers.Length; i++)
                numbers[i] = (byte)(strNumber[i] - '0');

            return numbers;
        }
    }
}

Saturday, December 20, 2014

Convert a whole integer to an array of integers

2:08 PM Posted by Unknown 2 comments


Hello everyone,
In this tutorial, we will see how we can convert an integer into an array of integers. First, what does that mean? What we mean is that the program will accept an integer number such as "76342986" and will convert it into an array of integers
7
6
3
4
2
9
8
6

so you can deal with any digit individually.
Why is that even useful?
Converting a whole integer into an array of integers can be useful in many ways:
·         Stem-and-leaf calculation
·         To create the largest possible number from a given number
·         Working on place values
·         Finding significant figures
·         You can write an application to convert numbers to corresponding strings
·         You can check divisibility of a number
·         To be able to express a number in extended form

and there are plenty other applications (in particular, math applications) where you will need to deal with the digits  individually.

So, how do we do that?
Here are the steps we're going to follow:
1-      Accept the number as string
2-      Convert the string-number into an array of characters
3-      Declare an array of integers that have the same length as the array of characters
4-      Apply the equation:
Array_of_numbers[] = array_of_characters[] – '0';
Which will return the number and will be stored in the array of integers.
E.g.,
If the first number in the array of characters is 7, then
Array_of_numbers[0] = array_of_characters[0] – '0';
// Array_of_numbers[0] = '7' – '0';
// Array_of_numbers[0] = 7;
                       And so on.

A question may pop up: how it works? Actually when we subtract characters here, we basically subtract ASCII values. So the ASCII value of 5 is 53 and for 0 is 48, so 53 – 48 = 5, and this similar to the numbers from 0 to 9.

what if the user entered a negative number?
If the user entered a negative number say -12332, then this will be the array_of_characters[]
-
1
2
3
3
2

So how do we handle such situation?

  •        After converting the whole number to an array_of_characters[], we check the first location whether it has a negation sign or not
  •     If it has the negation sign, then re-initialize the size of the Array_of_numbers to be array_of_characters.Length -1. And this is because the additional one space that the negation sign takes
  •     We start converting the array_of_characters[] to Array_of_numbers[] from the second location of array_of_characters[]
  •     To here, the Array_of_numbers[] will be:
1
2
3
3
2
   


  •          Lastly, make the first number in the array negative:
          Array_of_numbers[0] = - Array_of_numbers[0];
To make sure that the code is correct, we add a sum variable to sum all the numbers and check the result whether it is correct or not.

Note: If you have a better way to solve the problem or to optimize the code, please feel free to comment it down. I will be happy to see your contribution.

Here is the full Csharp code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Enter a number");
            string stringNumber = Console.ReadLine();
            char[] charnumbers = stringNumber.ToCharArray();
            int[] theNumbers = new int[charnumbers.Length];
           
            bool negativeNumber = false;
            int sum = 0;

            if (charnumbers[0] == '-')
            {
                negativeNumber = true;
                theNumbers = new int[charnumbers.Length - 1];
            }

            for (int i = 0; i < theNumbers.Length; i++)
            {
                if (negativeNumber == true)
                    theNumbers[i] = charnumbers[i + 1] - '0';
                else
                    theNumbers[i] = charnumbers[i] - '0';
            }

            if (negativeNumber == true)
                theNumbers[0] = -theNumbers[0];

            Console.WriteLine("the number is {0} digits", theNumbers.Length);
            for (int i = 0; i < theNumbers.Length; i++)
            {
                Console.WriteLine("[{0}] => {1}", i, theNumbers[i]);
                sum += theNumbers[i];
            }
            Console.WriteLine("The sum is {0}", sum);
            Console.ReadLine();
        }
    }
}

Sunday, December 14, 2014

loop puzzle - 1

7:07 AM Posted by Unknown 9 comments
Hello everybody, So, do you love solving puzzles? If yes, then before reading the rest of this article give it a go and try to write a loop that will generate the following pattern:

2020202020202020202020202020202020202020 
_19191919191919191919191919191919191919 
__181818181818181818181818181818181818
 ___1717171717171717171717171717171717
 ____16161616161616161616161616161616 
_____151515151515151515151515151515
 ______1414141414141414141414141414
 _______13131313131313131313131313
 ________121212121212121212121212 
_________1111111111111111111111
 __________10101010101010101010
___________999999999 
____________88888888 
_____________7777777 
______________666666 
_______________55555 
________________4444 
_________________333 
__________________22 
___________________1 

Assuming you gave it a go, let us examine how you can solve this puzzle. After the first glance on the pattern, you will realize three things:

  1.  There are 20 rows, starting from 20 going down to 1 
  2.  In each row, the number is repeated as many times as its value( e.g., number 9 is repeated 9 times) 
  3.  From the second row we print an underscore once, then we increase the number of the printed underscores along the way to number 1 


lets kick off with the first point and actually, this is the easiest part. Since we have 20 rows then we will have a loop that will run 20 times.
(for int i = 20;  i >= 1; i—0)
{  
  Console.WriteLine(i);
}
This loop will print the numbers from 20 to 1 single time in each iteration. But what we want is to repeat the number according to its value. To do that, we will have an inner loop that will repeat the number i times.
(for int i = 20;  i >= 1; i—0)
{  
     for (int j = i; j >= 1; j--)
         Console.Write(i);
Console.WriteLine(); // just to print a new line character 
}
To here we achieved point 1 and 2. Lets do the third point which is tricky one. We want the printing of the underscore starts from the second iteration, so the simplest way is to check which iteration is this, if it is not the first iteration then print the underscore. So, our loop will be now like:
for (int i = 20; i >= 1; i--)
            {
                if (i < 20)
                {
                        Console.Write("_");
                }
                for (int j = i; j >= 1; j--)
                    Console.Write(i);
                Console.WriteLine();
            }
However, this will cause the loop to print the underscore one time in every single iteration. What we want is to increase the printing of the underscores. To get that we will apply the following:

  •  Declare two integers: x and counter = 1
  •  Inside the if statement put the following equation: x = i – counter 
  •  Create a third inner loop inside the if statement that will take care of printing the underscores.

for (int k = 1; k <= i- x; k++)
         Console.Write("_");
So the final loop will look like this:
for (int i = 20; i >= 1; i--)
            {
                if (i < 20)
                {
                    x = i - counter;
                    for (int k = 1; k <= i- x; k++)
                        Console.Write("_");
                    counter++;
                }
                for (int j = i; j >= 1; j--)
                    Console.Write(i);

                Console.WriteLine();
            }
Lets analyze the loop a couple of times to understand how it work:

 In the first iteration we will get the number 20 twenty times

 In the second iteration the if block gets executed as: x = 19 – 1; // so x will be 18
 for (int k = 1; k <= i- x; k++) // the condition here is k <= 19 – 18 = 1
 Console.Write("_");
And this will cause the underscore loop to be executed 1 time. Then we increment counter by 1.

In the third execution: x = 18 – 2 // so x will be 16
 for (int k = 1; k <= i- x; k++) // the condition here is k <= 18 – 16 = 2
 Console.Write("_");
And this will cause the underscore loop to be executed 2 times. Then we increment counter by 1.

In the fourth execution: X = 17 – 3 // so x will be 14 for (int k = 1; k <= i- x; k++) // the condition here is k <= 17 – 14 = 3 Console.Write("_"); And this will cause the underscore loop to be executed 3 times. Then we increment counter by 1.

And so on.
That's it. You got the puzzle solved :).
For more convenience, we will replace the 20 number by an N number taken from the user.

Here is the full C# code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {
            int n;
            int x = 0, counter = 1;
            Console.WriteLine("Enter the number of rows:");
            n = int.Parse(Console.ReadLine());
            for (int i = n; i >= 1; i--)
            {
                if (i < n)
                {
                    x = i - counter;
                    for (int k = 1; k <= i- x; k++)
                        Console.Write("_");
                    counter++;
                }
                for (int j = i; j >= 1; j--)
                    Console.Write(i);

                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

output:

Generate strong password

6:28 AM Posted by Unknown No comments


Hello everyone, In this tutorial, we will learn how to generate a password that is safe and hard to detect. The methodology that we will follow for generating a safe password is: we will run a loop and for every time the loop runs we will generate a character and then append it to a string variable. Here I'll generate a 13 characters password consisting of lowercase and uppercase characters, numbers, and special characters. The question is, in every iteration how do we make the decision of generating a character? We will do that with the help of a random variable. The random variable will generate a number and we will compare this number against if else statement block, and if it matches with one of the blocks then we generate the corresponding character RANDOMLY. We will start with declaring the variables we're going to need:
            int randomNumber = 0;
            string password = "";
the randomNumber will be the variable that will hold the decision number. And the password variable is the one that will hold the password. Then we will create a random object:
            Random rnd = new Random();
rnd will generate a number and assign it to randomNumber. After that we write the loop that will generate the password.
for (int i = 1; i <= 13; i++)
            {
                randomNumber = rnd.Next(1,5);
                if (randomNumber == 1)
                    password += rnd.Next(1, 10);
                else if (randomNumber == 2)
                    password += Convert.ToChar(rnd.Next(65, 92));
                else if (randomNumber == 3)
                    password += Convert.ToChar(rnd.Next(97, 123));
                else if (randomNumber == 4)
                    password += Convert.ToChar(rnd.Next(33, 46));
            }

  • randomNumber = rnd.Next(1, 5); will generate an integer number between 1 and 5 (5 is not included) and will assign it to randomNumber. 
  • Then we will check the value of randomNumber against if else block. If randomNumber ==1 then we will generate a number between 1 and 9
  • if randomNumber ==2 we will generate a number between 65 and 91 and as you know these numbers represent the corresponding ASCII values for uppercase alphabets A-Z then we will convert it to a character using Convert.ToChar() method
  • If randomNumber ==3 we will generate a lowercase character a-z and lastly if randomNumber ==4 will generate one of these special characters !"#$%'()*+/- 


here is the full code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {

            int randomNumber = 0;
            string password = "";
            Random rnd = new Random();
            for (int i = 1; i <= 13; i++)
            {
                randomNumber = rnd.Next(1,5);
                if (randomNumber == 1)
                    password += rnd.Next(1, 10);
                else if (randomNumber == 2)
                    password += Convert.ToChar(rnd.Next(65, 91));
                else if (randomNumber == 3)
                    password += Convert.ToChar(rnd.Next(97, 123));
                else if (randomNumber == 4)
                    password += Convert.ToChar(rnd.Next(33, 46));
            }

            Console.WriteLine("Your new password is {0}", password);
           
            Console.ReadLine();
        }
    }
}

output:

A typical procedure to change the user's password:
  1.  If the user demanded a new password using his email, first check if the email is exist in the database 
  2.  If the email is valid: 
  •  Generate a new password 
  •  Encrypt it by converting it to a hash digest 
  •  Replace the hash digest (of the new password) with the old one in the database 
  •  Send the new password to the user

Wednesday, December 10, 2014

Reversing array in-place

8:53 PM Posted by Unknown No comments


In this tutorial, we will do actual reversing of the array elements without using an extra array.  Many programmer when they're asked to reverse an array they either display the array in reverse order, or use another array and copy the contents of array 1 to array 2 starting from the last position or they may use built-in methods such as Array.Reverse(array_name).

But, what if we want to do actual reversing to the array elements without using a built-in method or using a second array?
The idea to do that is to have two pointers:
-  The first pointer will point to the first element in the array
-  The second pointer will point to the last element in the array
-  Each time the loop runs, shift the item in the first position with the item in the last position, then increment the first pointer and decrement the pointer of the last position.

Here an example on how it will work:
You'll enter the size of the array and lets say it is: 10
Then you'll enter 10 element, assume they are:
3,5,4,7,6,1,8,9,2,10

iteration
elements that have been shifted
1st
10,5,4,7,6,1,8,9,2,3
2nd
10,2,4,7,6,1,8,9,5,3
3rd
10,2,9,7,6,1,8,4,5,3
4th
10,2,9,8,6,1,7,4,5,3
5th
10,2,9,8,1,6,7,4,5,3

Before:
3,5,4,7,6,1,8,9,2,10
After:
10,2,9,8,1,6,7,4,5,3

One important thing to mention here is that the loop that will do the shifting should iterate up to size_of_array / 2 (and this is clear in the table). The reason is that we shift 2 items in one iteration, so as for the above example we have 10 elements and we shift 2 elements each time so we need to iterate 5 times.
Here is the full CSharp code:




using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TestConsole
{

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size of the array");
            int n = int.Parse(Console.ReadLine());
            int[] array = new int[n];
            int decrementPointer = n - 1;
            int temp;

            Console.WriteLine("Enter the array elements");
            for (int i = 0; i < n; i++)
                array[i] = int.Parse(Console.ReadLine());

            Console.WriteLine("The array before reversing");
            for (int i = 0; i < n; i++)
                Console.Write(array[i] + " ");

            for (int i = 0; i < n / 2; i++)
            {
                temp = array[i];
                array[i] = array[decrementPointer];
                array[decrementPointer] = temp;

                decrementPointer--;
            }
            
            Console.WriteLine("\nThe array after reversing");
            for (int i = 0; i < n; i++)
                Console.Write(array[i] + " ");

            Console.ReadLine();
        }
    }
}