Friday, May 29, 2009

Swapping 2 Integers

I believe many of us out there came across, at least once in their lifetime, the problem to swap two numbers. Here are the three sample solutions that I could think to swap two numbers.
Solution A:

temp = a;
a = b;
b = temp;
Solution A introduces an additional auxiliary variable called "temp" in the code to hold one of the values (either a or b) which increases the footprint of the compiled class.
Solution B:

a = a ^ b;
b = b ^ a;
a = a ^ b;
Solution B on the other side swaps two numbers using bitwise operation. The XOR (Exclusive OR) is introduced in this code.
Solution C:

a = a + b;
b = a - b;
a = a - b;
Last but not least, Solution C swaps two numbers using arithmetic operations, both addition and subtraction.
Conclusion: In terms of speed, I would personally rank Solution B being the fastest, Solution C the second fastest and Solution A the slowest. (B -> C -> A)

Thursday, May 28, 2009

Translating XML with XSL in Java

I do not consider the codes in this blog entry as intensive as other entries. This is just merely an example to show you how to translate a XML document with a XSL stylesheet in a Java class. It could be a very handy tool for some Java developers out there that want to translate a given XML content into another completely different XML content on the fly.
Do not forget to set the encoding of your Java codes to UTF-8 if you are manipulating non-English XML content - for example, Traditional Chinese, Simplified Chinese, Russian, Korean or Japanese - if you would want to see the output in your Eclipse IDE, which is my current IDE to write Java codes.

The usefulness of this approach is that you do not need to include a reference of a XSL file in the XML, say for example,

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="myXMLstylesheet.xsl"?>
<catalog/>

Hope you have fun trying this out! :)

Sunday, May 24, 2009

Indexes of indexOf

Have you ever come across a situation in which you want to gather a list of indexes of the one particular substring in a string but you are limited to using only indexOf() method? I did and I wrote this method to ease my work in the future in the event that I need to get the list of indexes of the given substring. The code is as follow.

public static ArrayList indices(String inputString, String sampleString){
int length = inputString.length();
int inputStringIndex = -1;
StringBuffer newString = new StringBuffer();
int index = 0;
int check = 0;
ArrayList compile = new ArrayList();
while (index < length) {
try {
if (inputString.charAt(index) == sampleString.charAt(check)) {
newString.append(inputString.charAt(index));
check++;
if (newString.toString().equals(sampleString)) {
inputStringIndex = (index - check) + 1 ;
compile.add(inputStringIndex);
newString.setLength(0);
}
}
if (check == (sampleString.length())) {
check = 0;
}
} catch (Exception ex){}
index++;
}
if (compile.size() == 0) {
compile.add(inputStringIndex);
}
return compile;
}
The usage of this static method is very simple and trivial. Given a string "Nicholas Key Key Key Nicholas Key" and a sample substring "Key", you will get the result of [9, 13, 17, 30].

Thursday, May 21, 2009

Converting decimals into different base numbers

I have this function that might be useful and interesting for you. Probably some of us are thinking how to convert a decimal number into hexadecimal, octal and binary. To those readers that never heard of these four words, decimal is a base 10 number, hexadecimal is a base 16 number, octal is a base 8 number and binary is a base 2 number. I wrote this function simply because I wanted to learn what happens behind the API methods in the Java SDK that help you to convert a given decimal into the three different base numbers.

The methods that are available for us the developers in the Java 1.5 SDK are:
Integer.toBinaryString(input);
Integer.toOctalString(input);
Integer.toHexString(input);


public static class DecimalConverter{
static StringBuffer result = new StringBuffer();
static int divisorBIN = 2;
static int divisorOCT = 8;
static int divisorHEX = 16;
static char[] code = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

public static String converterHelper(int number, int divisor) {
if (number == 0) {
return "";
}
else {
converterHelper(number/divisor, divisor);
result.append(code[number%divisor]);
}
return result.toString();
}

public static String toHex(int number) {
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorHEX);
}

public static String toOct(int number) {
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorOCT);
}

public static String toBin(int number){
//reset StringBuffer result
result.setLength(0);
return converterHelper(number, divisorBIN);
}
}
From the method as shown, we have 16 characters in the array "code". This is because we want to accommodate all the valid the characters in base 16 numbers (hexadecimals). This method is quite a recursive method to convert the base 10 numbers (decimals) into 3 different bases of numbers. I hope you find these method useful. :) We can make use of this method by calling these static methods in the DecimalConverter class. Static methods are especially easy and useful when we want to call or make use of them from other classes. This is how the method is demonstrated.

public static void main(String[] args) {
System.out.println(DecimalConverter.toOct(207));
System.out.println(DecimalConverter.toBin(207));
System.out.println(DecimalConverter.toHex(207));
}
The recursion takes place in this statement converterHelper(number/divisor, divisor);. converterHelper method calls itself as long as the number is not 0 and then it looks into the array and find the matching character according to the index from the modulo operation. You may try out this method and use the numbers in the conversion table to determine if this helper class is useful for you. Click here to view the conversion table.

Wednesday, May 20, 2009

The one missing number

This question sounds rather intimidating but when you analyze it deep enough, you will be amazed about the way this problem is solved - "Given an array of size n, containing every element from 1 to n+1, except one. Find the missing element." Many of us might have quickly jumped into the solution in which many fancy data structures are being used. But actually there is a much easier way to solve this problem. The suggested code is as follow. I think the complexity of this suggested algorithm is O(n). It is a linear operation as you can see in the implementation.

public static int missingNumber(int input[]){
int arrSize = input.length;
int totalLength = arrSize + 1;
int missingNumber = 0;
for (int count=1; count <= totalLength; count++) {
missingNumber = missingNumber + count;
if ((count-1) < arrSize) {
missingNumber = missingNumber - input[(count-1)];
}
}
return missingNumber;
}

Tuesday, May 19, 2009

Index of a sample string in a string

I am sure many of us who write codes in Java use the method indexOf() to get the index of a string in a given string. I use this method quite frequently too and I thought of writing a method that replicates the functionality of indexOf() that is readily available in the Java SDK. In addition to that, I thought this could be an exciting thing to do - dissecting and reverse engineering Java API methods.

Well, I wrote this code and would like to share with the readers of this blog. I hope you find it useful. Please feel free to drop a line if you have a better way to solve this problem. The code is quite self explanatory. It mainly reads through the original string and while reading it, the sample string is being compared.
 
// To get the index of the first occurrence of a matching substring
public static int indexOf(String inputString, String sampleString){
// set the length of input string
int length = inputString.length();
int inputStringIndex = -1;
StringBuffer newString = new StringBuffer();
// to keep track of current index of character of input string
int index = 0;
// to keep track of current index of character of sample string
int check = 0;
while (index < length) {
try {
if (inputString.charAt(index) == sampleString.charAt(check)) {
newString.append(inputString.charAt(index));
check++;
if (newString.toString().equals(sampleString)) {
/**
* set the index of the first occurrence of the
* matching substring
*/
inputStringIndex = (index - check) + 1 ;
break;
}
}
} catch (Exception ex){}
index++;
}
return inputStringIndex;
}

Monday, May 11, 2009

CoffeeCup HTML Editor

This is a HTML Editor that you may want to give it a try. I love to use this application because, first of all, it is absolutely free. You can get it right here for free without any cost! Here is a screenshot of how their website looks like.

Most of the time, free stuffs are not actually free. Some companies will insist to get at least your email address in order to download their "free" software. For those of you that might be wondering why some companies tempt you to give them your email address or phone number, the reason being that your contact information will be harvested by spammers or so called business affiliates. Do not fall into that trap. Privacy is becoming more and more invaded these days. CoffeeCup does not ask for your email address nor telephone number. You will just need to download this HTML Editor from their website and the application is up and running. No strings attached!

I have tested this application and it is loaded with many interesting features including syntax highlighting. It also allows you to preview your HTML design in the same window. Since I have started to tinker with PHP at my playground, the editor is able to highlight the PHP statements nicely. The most important feature, for me personally, to use this application, is the FTP which is used to perform file uploads and downloads. No more paying a hefty sum of money to buy FrontPage or Dreamweaver - IDEs that helps you most of the frontend but leave you clueless about the underlying HTML codes.

Other than that, the interface is very intuitive. Everything that I wanted to do is within my estimation, which means that I know intuitively what buttons to point and click or which drop down menu to look at, the first time I was using this application. This is true when I configured the FTP settings.

But hey, since CoffeeCup HTML Editor is free, you should not expect that it is very feature-packed just like those off-the-shelf HTML editors. I have mentioned the pros earlier so here are some of the disadvantages. I have only came across one - CoffeeCup HTML Editor is only available for Windows and that is sad.

Anyway, this is the link again to download CoffeeCup HTML Editor. Have fun trying it!

DISCLAIMER: I am recommending CoffeeCup HTML Editor as a software developer that has tried its features and I think it is useful for other web developer and I do not receive any endorsement fee from CoffeeCup to write this article :)

Friday, May 8, 2009

The syntax highlighter

I believe some of my readers might be thinking to themselves how does Nicholas wraps around the codes that he demonstrates in his blog entries in a text area filled with interleaving colors. It also comes with the copying feature and viewing the codes in plain texts. Many thanks to Alex Gorbatchev for this wonderful Javascript library that allows us to read codes more easily in blogs or online journals. This is his website if you would want to take a look at his work. Or you can actually go to Google Code website to download the package. There are several steps for you to follow if you want to get your codes display nicely in the encapsulated and decorated text area.

[1] Go to the syntaxhighlighter website at Google Code to download the latest version of the Javascript library.


[2] Download the compressed file and unzip it in your remote hosting. I may suggest Google Apps to host the uncompressed files. You will have to use WinRAR to unzip the contents. I rename the folder called "dp.SyntaxHighlighter" to "SyntaxHighlighter". There are 2 folders that I make use in the uncompressed file namely "Styles" and "Scripts".

[3] Edit your blog template to insert these lines of codes, preferably at the footer part of the template that reads "<!-- end outer-wrapper --> ".

[4] The next step is to try inserting your code snippets into this textarea
<textarea name="code" class="javascript" cols="60" rows="10">
  code...
  code...
  code...
</textarea>

Hope you have fun trying this out! :)

Thursday, May 7, 2009

Nicholas is salohciN

I have been thinking a lot about solving a problem optimally and efficiently. Let us take a look at a seemingly easy computer science problem but might take some of us quite a bit of time to come up with an elegant solution. It is the problem about reversing a string - be it by letters or by words. Below is my solution to reverse a string by letters.

public static String reverseCharacters(String text){
StringBuffer reversed = new StringBuffer();
int len = text.length()-1;
for (int i=len; i>=0; i--) {
reversed.append(text.charAt(i));
}
return reversed.toString();
}
It is observed that I am decrementing the counter in the for-loop. Why is that? It is simply because I want to start to look at the given string in a backward manner. A StringBuffer is used to append the letters because append() operation is not as costly as we would have used a string and concatenate the letters. Simple isn't it? Many of us might thought that we could have used the reverse() method instead, rather than coding this unnecessarily. I would say this suggested solution is very reliable if we are looking at solving this problem more discretely.

Next we will explore how to reverse a string by words. Once again I am suggesting the cheapest way to solve it. Some of us might thought that we have to first split the strings by a whitespace and then push the words into a stack, which we will then pop every single item out from the stack. Here is my approach in solving it using very little copying and no temporary variables.

public static String reverseWords(String text) {
StringBuffer reverse = new StringBuffer();
String[] textArray= text.split("[\\s*]");
int len = textArray.length-1;
for (int i=len; i>=0; i--) {
reverse.append(textArray[i]).append(" ");
}
return reverse.toString();
}
I am looking backwards again. This time it is the array of split texts. I am splitting the text using the split() method and provide a regular expression statement [\s*]. The StringBuffer is used instead of String because it is less costly to append strings using the append() method. The method reverseWords() returns "sky blue clear very" if the given string is "very clear blue sky".

Wednesday, May 6, 2009

Deduplication

Here is a Java static method that removes recurring characters in a string. Given an input string "[Nicholas N I cho L[A]s!]", this method returns a string that reads "[Nicholas ILA]!"

public static String removeDuplicates(String text){
StringBuffer uniq = new StringBuffer();
int len = text.length();
for (int i=0; i<len; i++) {
if (uniq.indexOf(Character.toString(text.charAt(i))) < 0) {
uniq.append(text.charAt(i));
}
}
return uniq.toString();
}
Initially I thought of using a set to compile a group of unique characters but that would be adding extra code executions. I figured that I can solve this rather easily by going back to the basics. You may see that as I am constructing a new string "uniq", I am using the indexOf() method to look up for a particular character in that string. A value less than 0 means that the character that we are looking for does not exist at that moment. So we are appending it to "uniq". Another problem solved :)
Update: The code is also available in Python in this entry

Tuesday, May 5, 2009

Palindrome

A palindrome is a word or phrase that reads the same forward as it does backward. Some of the simple examples are "kayak", "Hannah" and "refer" if we would like to know how do palindromic words look like. There are also palindrome-like phrases such as "Dennis and Edna sinned" and "Draw pupil's lip upward".

It would not be too difficult to determine algorithmically if a word or sentence is a palindrome. There are many ways to solve it but we also need to consider if our solution is not computationally expensive.

I have thought of a simple and yet an efficient solution to our discussion. This is a static method that strips off the punctuations and also white character spacings. The method returns a boolean value true if the input string is a palindrome otherwise it returns false.

public static boolean isPalindrome(String text){
//Sets an index at the far left of the word or phrase
int leftIndex = 0;

//Converts input text into lower case and remove
//any single non-alphanumeric and underscore
text = text.toLowerCase().replaceAll("[\\W\\_*]", "");

//Sets an index at the far right of the word or phrase
int rightIndex = text.length()-1;
while (leftIndex < rightIndex) {
if (!(text.charAt(leftIndex) == text.charAt(rightIndex))) {
//returns a false and get out from the while loop
return false;
}

//gets the indexes from both sides closer
leftIndex++;
rightIndex--;
}
//returns a true if all the characters mirrors to each other
return true;
}

Friday, May 1, 2009

Truncating a sentence

Here is something that we often ask ourselves how do we truncate a sentence and then append it with a trailing "...". We see this in articles, newspapers, texts in television advertisements. I am suggesting a method that might be useful for front-end developers to truncate the sentences pulled out from the database.

public static String truncate(String text, int length) {
return (text.length() <= length) ? text : text.substring(0, length) + " ...";
}
Simple isn't it? The use of this static method allows you to set a maximum length of the sentence to be truncated and then append it with the trailing "...".
Update: The code is also available in Python in this entry