Everyone Is An Achiever
To have what few have, do what few do.
Wednesday, December 31, 2014
Tuesday, December 30, 2014
program to calculate stems and leafs
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
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
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
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:
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
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:
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.
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:
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:
- There are 20 rows, starting from 20 going down to 1
- In each row, the number is repeated as many times as its value( e.g., number 9 is repeated 9 times)
- 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
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:
- If the user demanded a new password using his email, first check if the email is exist in the database
- 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
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(); } } }
Hello everyone
Hello everybody,
This is the first post in my blog and here I want to welcome you all. I'm happy that you made it to here and I hope that you find the content of my blog useful.
What I'm going to share with you guys is primarily my knowledge in software engineering more specifically problem solving and coding. I love to program and I want to share what I learnt so far with you. I will also be happy t get your advice and to learn from you, so feel free to contact me and share your thoughts with me.
I will also share with you general topics that I find interesting and worth reading.
Hope you enjoy your time here.
Maher Nabil
software engineer