You are browsing the archive for Hazem Saleh.

[JavaScript Quiz] Number Text Representation

May 11, 2015 in JavaScript

Today’s JavaScript quiz is about creating a Number to String utility. Assume that we have the following numbers as an input to our utility:

23
1999
199999
1000000999

Our JavaScript utility should output the following results:

twenty three
one thousand nine hundreds ninety nine
one hundred ninety nine thousand nine hundred ninety nine
one billion nine hundred ninety nine

.
.
.
.
.
.
.
.
.
.
.
.
.
In order to develop this utility, it is important to break-down this problem into small sub-problems and then solve each of them individually. For example, if we wish to print numbers from 0 to 9, this is an easy Job, just create an array that contains the numbers from 0 to 9 and call it digits as follows.

digits = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];

If we want to print numbers from 10 to 19, we can create another array that represents teens as follows:

teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];

Then if we want to print numbers from 20 up to 99, we can create another array that represents tys as follows.

tys = ["twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"];

But for numbers from 20 to 99, how can we utilize the previous array for printing their values, if we think little about it, we will find that a number like 39 is about 30 + 9 which will produce at the end "thirty nine". But how to divide a number like 39 to 30 + 9 and get its corresponding text representation, simply this can be done by performing three steps:

  1. Dividing 39 (or generally numbers from 20 to 99) by 10 (Integer Division), and then subtract 2 from the result number in order to pick its text representation "thirty" from its corresponding array (tys array).
  2. Having the mod of 39 (or generally numbers from 20 to 99) and 10 which will give us 9, and then we can get simply pick its text representation "nine" from its corresponding array (digits array).
  3. Finally, augment the two text representations to get the final number text representation which is “thirty nine”.

For numbers from 100 up to 999, For example: 205, we can divide it 205 by 100 to know how many hundred units does it has (2 hundreds) and then have the reminder of this number 205 with 100 which is 5 and “five” representation can be got simply using the previous mentioned procedures. Let’s look into the code which can get the text representation of numbers from 0 to 999.

NumberReader.prototype.readThreeDigitNumber = function(number) { /* 0 ... 999 */
    if (number == 0) {
        return "zero";
    }
    
    var output = "", result, reminder;
    
    if (number > 99) {
        result  = Math.floor(number / 100);
        number = number % 100;
        
        output += this.digits[result] + " hundred";
        
        if (number == 0) {
            return output;
        }
    }
    
    if (number < 10) {
        output = NumberReader.appendToOutput(output, this.digits[number]);    
    } else if (number < 20) {
        output = NumberReader.appendToOutput(output, this.teens[number - 10]);                
    } else {
        result = Math.floor(number / 10);
        reminder = number % 10;
        
        output = NumberReader.appendToOutput(output, this.tys[result - 2]);
        
        if (reminder > 0) {
            output = NumberReader.appendToOutput(output, this.digits[reminder]);
        }
    }
    
    return output;
}

We can apply the same concept with thousands by diving them by 1000 to know the thousands units and having mod with 1000 which can be resolved using the previous procedure. Thankfully, we can apply the same concept with millions and billions as shown below.

NumberReader.prototype.readNumber = function (number) {
    var output = "", result, reminder;
    
    if (number >= 1e9) {
        result = Math.floor(number / 1000000000);
        reminder = number % 1000000000;
        
        output += this.readNumber(result) + " billion " + ((reminder > 0) ? this.readNumber(reminder) : "");
    } else if (number >= 1e6 && number < 1e9) {
        result = Math.floor(number / 1000000);
        reminder = number % 1000000;
        
        output += this.readNumber(result) + " million " + ((reminder > 0) ? this.readNumber(reminder) : "");
    } else if (number >= 1000 && number < 1e6) {
        result = Math.floor(number / 1000);
        reminder = number % 1000;
        
        output += this.readNumber(result) + " thousand " + ((reminder > 0) ? this.readNumber(reminder) : "");
    } else {
        output += this.readThreeDigitNumber(number);
    }
    
    return output;
}

The complete quiz code is shown below.

var NumberReader = function() {
    this.digits = ["zero", "one", "two", "three", "four", "five",
        "six", "seven", "eight", "nine"];

    this.teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
    
    this.tys = ["twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"];    
}

NumberReader.prototype.readThreeDigitNumber = function(number) { /* 0 ... 999 */
    if (number == 0) {
        return "zero";
    }
    
    var output = "", result, reminder;
    
    if (number > 99) {
        result  = Math.floor(number / 100);
        number = number % 100;
        
        output += this.digits[result] + " hundred";
        
        if (number == 0) {
            return output;
        }
    }
    
    if (number < 10) {
        output = NumberReader.appendToOutput(output, this.digits[number]);    
    } else if (number < 20) {
        output = NumberReader.appendToOutput(output, this.teens[number - 10]);                
    } else {
        result = Math.floor(number / 10);
        reminder = number % 10;
        
        output = NumberReader.appendToOutput(output, this.tys[result - 2]);
        
        if (reminder > 0) {
            output = NumberReader.appendToOutput(output, this.digits[reminder]);
        }
    }
    
    return output;
}

NumberReader.prototype.readNumber = function (number) {
    var output = "", result, reminder;
    
    if (number >= 1e9) {
        result = Math.floor(number / 1000000000);
        reminder = number % 1000000000;
        
        output += this.readNumber(result) + " billion " + ((reminder > 0) ? this.readNumber(reminder) : "");
    } else if (number >= 1e6 && number < 1e9) {
        result = Math.floor(number / 1000000);
        reminder = number % 1000000;
        
        output += this.readNumber(result) + " million " + ((reminder > 0) ? this.readNumber(reminder) : "");
    } else if (number >= 1000 && number < 1e6) {
        result = Math.floor(number / 1000);
        reminder = number % 1000;
        
        output += this.readNumber(result) + " thousand " + ((reminder > 0) ? this.readNumber(reminder) : "");
    } else {
        output += this.readThreeDigitNumber(number);
    }
    
    return output;
}

NumberReader.appendToOutput = function (output, parameter) {
    if (output == "") {
        output += parameter;
    } else {
        output += " " + parameter;
    }
    
    return output;
}

And this is a test code for NumberReader.

// Test our API ...
var numberReader = new NumberReader();

console.log(numberReader.readNumber(1999999999));
console.log(numberReader.readNumber(1000000999));    
console.log(numberReader.readNumber(100000999));        
console.log(numberReader.readNumber(1000999));
console.log(numberReader.readNumber(199999));
console.log(numberReader.readNumber(100000));
console.log(numberReader.readNumber(1999));    
console.log(numberReader.readNumber(9));        
console.log(numberReader.readNumber(999));        
console.log(numberReader.readNumber(193));
console.log(numberReader.readNumber(23));        
console.log(numberReader.readNumber(333));

The output will be:

one million nine hundred ninety nine
one hundred ninety nine thousand nine hundred ninety nine
one hundred thousand 
one thousand nine hundred ninety nine
nine
nine hundred ninety nine
one hundred ninety three
twenty three
three hundred thirty three

[JavaScript Quiz] Finding longest common substring of strings

April 25, 2015 in JavaScript

Finding the longest common substring of strings is one of the interesting problems. Assume that we have two JavaScript strings like “ababccd” and “abccw”, Can we write a JavaScript utility function that can find the common substrings of these two strings which is “abcc” in this case.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
One of the possible solutions to this problem is to create a 2D comparison array (of size [First string length][Second string length]) which will hold the comparisons between every character in the first and the second strings. If the character of the first string does not match the second string character then set the array cell to 0.
If we find the first string current character matches the second string current character then set the corresponding array cell to 1 but take care if the upper left diagonal cell of the current cell in the comparison array is greater than 0 then you need set the current cell value to the upper left diagonal cell value + 1 (Upper left diagonal cell refers to the previous character of both strings).

Coding this is very simple and the complexity of this code is O(length of the first string * length of the second string) as follows.

var StringUtils = function() {
}

StringUtils.findLongestCommonSubstring = function(string1, string2) {
	var comparsions = []; //2D array for the char comparsions ...
	var maxSubStrLength = 0;
	var lastMaxSubStrIndex = -1, i, j, char1, char2, startIndex;

	for (i = 0; i < string1.length; ++i) {
		comparsions[i] = new Array();

		for (j = 0; j < string2.length; ++j) {
			char1 = string1.charAt(i);
			char2 = string2.charAt(j);

			if (char1 === char2) {
				if (i > 0 && j > 0) {
					comparsions[i][j] = comparsions[i - 1][j - 1] + 1;
				} else {
					comparsions[i][j] = 1;
				}
			} else {
				comparsions[i][j] = 0;
			}

			if (comparsions[i][j] > maxSubStrLength) {
				maxSubStrLength = comparsions[i][j];
				lastMaxSubStrIndex = i;
			}
		}
	}

	if (maxSubStrLength > 0) {
		startIndex = lastMaxSubStrIndex - maxSubStrLength + 1;

		return string1.substr(startIndex, maxSubStrLength);
	}

	return null;
}

// Test code
console.log(StringUtils.findLongestCommonSubstring("ababccd", "abccx"));
console.log(StringUtils.findLongestCommonSubstring("ababccd", "ccxaba"));
console.log(StringUtils.findLongestCommonSubstring("becooltopeople", "topeoplebecool"));    
console.log(StringUtils.findLongestCommonSubstring("ababccd", "zzzz")); 

As shown in the implementation, we store two main items, the maximum common substring length and its last index and thankfully using JavaScript substr function, we can get the desired common substring string. The output will be as follows.

abcc
aba
topeople
null

Finally, note that if you have two longest substrings then this code will get the first of them.

Back from ApacheCon North America 2015

April 24, 2015 in Apache Cordova, Conference, JavaScript

I just get back from ApacheCon North America that was be held from 13 April to 16 April @Austin, Texas, USA. The conference organization was really great and there were a lot of attendees in the conference sessions.
IMG_8838

I had the chance to present “Apache Cordova In Action” in 13 April, the session had many attendees and I was really amazed by the energy, enthusiasm, and responsiveness of the attendees during the session.
Feedback

The session went great and I was glad to give a free copy of my JavaScript Mobile Application Development book to one of the attendees who answered a JavaScript quiz at the end of my session.
Books

I uploaded my session below:

Finally, I would like to thank all the organizers of ApacheCon conference for making the conference looks so great.
Main

Back from JavaLand Germany 2015

March 30, 2015 in Apache Cordova, Bluemix, Conference

JavaLand2015Main

I just get back from JavaLand that was be held from 24 March to 26 March @Brühl, Germany. The conference organization was more than fantastic and there were a lot of attendees in the conference sessions.

I had the chance to present “Developing Mobile Applications using JavaScript” in 25 March, the session had many attendees and I was really amazed by the energy, enthusiasm, and responsiveness of the attendees during the session.
screenshot

The session went great and I was glad to give a free copy of my JavaScript Mobile Application Development book to one of the attendees who answered a JavaScript quiz at the end of my session.
Books

I uploaded my session below:

In the conference, I really had the pleasure to work in the IBM Bluemix booth, it was really a very exciting experience for me.
IMG_8443

javaland5
IMG_8419

Finally, I would like to thank all the organizers of JavaLand conference for making the conference looks so great.
IMG_8429_2
IMG_8444
IMG_8372_2

Speaking in ApacheCon North America 2015

March 21, 2015 in Apache Cordova, Conference, JavaScript

Screen Shot 2015-03-21 at 1.15.10 AM
@Monday, April 13 10:45 AM, I will be speaking in ApacheCon North America conference (that will be held from 13 April to 17 April @Austin, USA) about Apache Cordova under the session title “Apache Cordova In Action”. My session will be a practical one, it will discuss why there is a need for Hybrid mobile development, the current challenges of mobile development, and how using Apache Cordova can help in overcoming many of these technical challenges. It also highlights the best practices of using Apache Cordova with jQuery mobile. then, it demonstrates a real Cordova mobile app that works on three mobile platforms (Android, iOS, and Windows Phone 8.1).

Finally, I hope it will be an interesting session for all the mobile development passionate :):
https://apacheconna2015.sched.org/speaker/hazems

Personally, it is my first time to visit Austin, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome :)?

I really wish to see all of you there in ApacheCon North America 2015!

Book Review #3 “Very good introduction into Apache Cordova”

March 5, 2015 in Apache Cordova, Book, Reviews

Attached below the review of Werner Punz (a Web and Mobile Development Expert) about the “JavaScript Mobile Application Development” book:

JavaScript Mobile Application Development Book

JavaScript Mobile Application Development Book

Very good introduction into Apache Cordova

“This book is a very good introduction into Apache Cordova. It basically guides you from the basics to the API integration, then to the most common APIs. After that you get an overview on how to unit test the application and how to write your own plugins and in the end you will get a guide to the implementation of a complex Cordova app.
The only thing I personally found missing was in the IDE section a description on how to integrated Cordova in the Android Studio instead of Eclipse, since Eclipse is on its way out in the Android area of programming.”


Reference:

http://www.amazon.com/review/R19ORB0DCN16PA/

The book in Amazon:

http://www.amazon.com/JavaScript-Mobile-Application-Development-Hazem/dp/1783554177/

[JavaScript] Getting All Possible Permutations

March 3, 2015 in JavaScript

One of the most interesting mathematical stuff is Permutation. A permutation is the act of re-arranging all the members of a set into some sequence or order, such that the order of selection always matters (unlike combination).

Assume that we have 3 balls (Red, Green and Blue). If we want all the possible permutation then we will have the following 6 possible permutation:

  • Red, Green, Blue.
  • Red, Blue, Green.
  • Green, Blue, Red.
  • Green, Red, Blue.
  • Blue, Red, Green.
  • Blue, Green, Red.

Mathematically, the number of permutations of n distinct objects is n factorial usually written as n!. Now, let’s write a simple function in JavaScript that gets the unique permutation for a set of objects.

var Util = function() {
};

Util.getPermuts = function(array, start, output) {
	if (start >= array.length) {
		var arr = array.slice(0); //clone the array		
		output.push(arr);
	} else {
		var i;
		
		for (i = start; i < array.length; ++i) {
			Util.swap(array, start, i);	
			Util.getPermuts(array, start + 1, output);	
			Util.swap(array, start, i);	
		}
	}
}

Util.getAllPossiblePermuts = function(array, output) {
	Util.getPermuts(array, 0, output);
}

Util.swap = function(array, from, to) {
	var tmp = array[from];
	array[from] = array[to];
	array[to] = tmp;
}

// Test API ...
var array = ['R', 'G', 'B'];
var output = [];

Util.getAllPossiblePermuts(array, output);
console.log(output);

As shown in Util.getPermuts, it takes three parameters as follows:
1. array parameter represents the array of objects that we have.
2. start parameter represents the current start index.
3. output parameter represents the array that holds all the possible arrays of permutations.

Util.getPermuts recursively swaps the array elements in order to get all the possible permutations of the input array.

The previous code covers permutation without repetition which means that we use every element that we have only once in every possible permutation.

What about if we want to get all the possible permutations with repetition. Assume that we have 4 blank papers and we would like to paint them with all the possible ways using Red, Green and Blue colors.

Can you write a JavaScript function that can get all the possible 4 papers’ paintings?

According to Permutation with repetition, all the possible 4 papers’ paintings with 3 colors can be calculated as (3 power 4) which equal to 81. The formula is very simple: n P(with repetition) r = n ^ k.

Now, let’s use recursion in order to get all the possible permutation with repetition.

var Util = function() {
};

Util.getRPermuts = function(array, size, initialStuff, output) {
	if (initialStuff.length >= size) {
		output.push(initialStuff);
	} else {
		var i;
		
		for (i = 0; i < array.length; ++i) {	
			Util.getRPermuts(array, size, initialStuff.concat(array[i]), output);
		}
	}
}

Util.getAllPossibleRPermuts = function(array, size, output) {
	Util.getRPermuts(array, size, [], output);
}

As shown in Util.getRPermuts, it takes four parameters as follows:
1. array parameter represents the array of objects (colors in our case) that we have.
2. size parameter represents the size of every permutation item.
3. initialStuff parameter represents a temp array that holds every possible permutation with repetition.
4. output parameter represents the array that holds all the possible arrays of permutation with repetition.

In order to know all the possible 4 papers’ paintings using the available 3 colors, you can call the permutation with repetition API simply as follows:

// Create the array of the possible 3 colors ...
var possibleColors = ['R', 'G', 'B'];
var output = [];
var papersNo = 4;

// get all the possible painting for the 4 papers that we have.
Util.getAllPossibleRPermuts(possibleColors, papersNo, output);
console.log(output);

In the console, you will find all the possible 81 permutation with repetition as follows:

[["R", "R", "R", "R"], ["R", "R", "R", "G"], ["R", "R", "R", "B"], ["R", "R", "G", "R"], ["R", "R", "G", "G"], ["R", "R", "G", "B"], ["R", "R", "B", "R"], ["R", "R", "B", "G"], ["R", "R", "B", "B"], ["R", "G", "R", "R"], ["R", "G", "R", "G"], ["R", "G", "R", "B"], ["R", "G", "G", "R"], ["R", "G", "G", "G"], ["R", "G", "G", "B"], ["R", "G", "B", "R"], ["R", "G", "B", "G"], ["R", "G", "B", "B"], ["R", "B", "R", "R"], ["R", "B", "R", "G"], ["R", "B", "R", "B"], ["R", "B", "G", "R"], ["R", "B", "G", "G"], ["R", "B", "G", "B"], ["R", "B", "B", "R"], ["R", "B", "B", "G"], ["R", "B", "B", "B"], ["G", "R", "R", "R"], ["G", "R", "R", "G"], ["G", "R", "R", "B"], ["G", "R", "G", "R"], ["G", "R", "G", "G"], ["G", "R", "G", "B"], ["G", "R", "B", "R"], ["G", "R", "B", "G"], ["G", "R", "B", "B"], ["G", "G", "R", "R"], ["G", "G", "R", "G"], ["G", "G", "R", "B"], ["G", "G", "G", "R"], ["G", "G", "G", "G"], ["G", "G", "G", "B"], ["G", "G", "B", "R"], ["G", "G", "B", "G"], ["G", "G", "B", "B"], ["G", "B", "R", "R"], ["G", "B", "R", "G"], ["G", "B", "R", "B"], ["G", "B", "G", "R"], ["G", "B", "G", "G"], ["G", "B", "G", "B"], ["G", "B", "B", "R"], ["G", "B", "B", "G"], ["G", "B", "B", "B"], ["B", "R", "R", "R"], ["B", "R", "R", "G"], ["B", "R", "R", "B"], ["B", "R", "G", "R"], ["B", "R", "G", "G"], ["B", "R", "G", "B"], ["B", "R", "B", "R"], ["B", "R", "B", "G"], ["B", "R", "B", "B"], ["B", "G", "R", "R"], ["B", "G", "R", "G"], ["B", "G", "R", "B"], ["B", "G", "G", "R"], ["B", "G", "G", "G"], ["B", "G", "G", "B"], ["B", "G", "B", "R"], ["B", "G", "B", "G"], ["B", "G", "B", "B"], ["B", "B", "R", "R"], ["B", "B", "R", "G"], ["B", "B", "R", "B"], ["B", "B", "G", "R"], ["B", "B", "G", "G"], ["B", "B", "G", "B"], ["B", "B", "B", "R"], ["B", "B", "B", "G"], ["B", "B", "B", "B"]]

Speaking in JavaLand Germany 2015

February 20, 2015 in JavaScript

Speaker in JavaLand 2015

Speaker in JavaLand 2015

@Wednesday, March 25 04:00 PM, I will be speaking in JavaLand Germany conference (that will be held from 24 March to 26 March @Brühl, Germany) about “Developing Mobile Applications using JavaScript”. My session will be a practical one, I will discuss mobile apps development using JavaScript and Apache Cordova. My session will also include Apache Cordova Integration tips with jQuery mobile on the three popular mobile platforms (Android, iOS and Windows Phone 8).

There is a JavaScript quiz at the end of my session, the one who will be able to answer it correctly will have a free copy of my new JavaScript book:
Books

I hope it will be an interesting session for all the mobile development passionate :):
https://www.doag.org/konferenz/konferenzplaner/konferenzplaner_details.php?locS=0&id=483801&vid=491546

Personally, it is my first time to visit Brühl, Germany, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome :D?

I really wish to see all of you there in JavaLand Germany 2015!

[JavaScript] Getting All Possible Combinations

February 16, 2015 in JavaScript

One of the most interesting mathematical stuff is Combination. A combination is a way of selecting members from a grouping, such that the order of selection does not matter (unlike permutation).

For example, assume that we have 6 balls (numbered from 1 to 6), and a person can select only 4 balls at a time.

Can you write a JavaScript function that can get all the possible 4 ball selections from the available 6 balls?

According to Combination, all the possible 4 ball selections from the 6 balls are (6 Choose 4) which equal to 15. The formula is very simple: n C r = n! / r! n-r!.

Now, let’s use recursion in order to get all the possible combinations.

var Util = function() {
};

Util.getCombinations = function(array, size, start, initialStuff, output) {
    if (initialStuff.length >= size) {
        output.push(initialStuff);
    } else {
        var i;
		
        for (i = start; i < array.length; ++i) {	
	    Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), output);
        }
    }
}

Util.getAllPossibleCombinations = function(array, size, output) {
    Util.getCombinations(array, size, 0, [], output);
}

As shown in Util.getAllPossibleCombinations, it takes five parameters as follows:
1. array parameter represents the array of objects that we have.
2. size parameter represents the size of every selection from the array.
3. start parameter represents the current start index.
4. initialStuff parameter represents a temp array that holds every possible combination.
5. output parameter represents the array that holds all the possible arrays of combinations.

In order to know all the possible 4 balls selections from the available 6 balls, you can call the API simply as follows:

// Create an array that holds numbers from 1 ... 6.
var array = [];

for (var i = 1; i <= 6; ++i) {
    array[i - 1] = i;
}

var output = [];

// Select only 4 balls out of the 6 balls at a time ...
Util.getAllPossibleCombinations(array, 4, output);
console.log(output);

In the console, you will find all the possible 15 combinations as follows:

[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 5, 6], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 5, 6], [1, 4, 5, 6], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 5, 6], [2, 4, 5, 6], [3, 4, 5, 6]]
Skip to toolbar