Everyone Is An Achiever

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 =

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 :)