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