In this post, I will introduce a new and simple syntax highlighting approach for functional languages. On the other hand, I will briefly mention the famous parameter of Java main method “(String[ ] args)”.

In functional languages like Lisp and Scheme (I don’t know if there is any other:) ), there are full of parenthesis and it is hard to follow. Thus I wrote a little piece of code in parallel to my understanding of the code written in these languages. It is kind of a Stack implementation in my mind, each opening parenthesis corresponds to a closing one and I think, most of the people understand the code in the way I did. So I tried to colorize the code in that manner, rather than colorizing the keywords (because almost every word is a keyword in these languages). Codes in the same depth have the same color. In the example below there are limited number of colors but it is enough to add new colors to the constant array at the beginning to see the colors in the code generated. Let’s see Java code for colorizing:

import java.io.File;
import java.util.Scanner;
public class ColorizeScheme{
	public static String[] COLORS = {"#000099", "#990000", "#009900", "#000000"};
	public static int colorCounter = 0;
	public static void main(String[] args){
		File file = new File(args[0]);
		try{
			Scanner scan = new Scanner(file);
			String string ="";
			String output ="";
			while(scan.hasNextLine()){
				//read input file, line by line.
				string = scan.nextLine();
				for(int i = 0; i < string.length(); i++){
					/**
					 * If next char is an opening parenthesis add a font color code to the beginning
					 * if a closing parenthesis, close font code
					 * if a tab character change with html indentation
					 * if there exists more than one blank following each other, put &nbsp; (blank character)
					 * else simply put the character.
					 */
					if ((char)string.charAt(i) == '(' || (char)string.charAt(i) == '['){
						output += "<font color=" + COLORS[colorCounter] + ">" + (char)string.charAt(i);
						increaseCounter();
					}
					else if((char)string.charAt(i) == ')' || (char)string.charAt(i) == ']'){
						output += (char)string.charAt(i) + "</font>";
						decreaseCounter();
					}
					else if((char)string.charAt(i) == '\t'){
						output += "&nbsp;&nbsp;&nbsp;&nbsp;";
					}
					/** What am I doing in the following line after && ?
					 * I prevent an exception so called "ArrayIndexOutOfBoundsException"
					 * If i is representing the last char in the string
					 * I do not check i+1'st char which does not exist
					 */
					else if((char)string.charAt(i) == ' ' && ((i+1)!=string.length())?(char)string.charAt(i+1) == ' ':false){
						output += "&nbsp;";
					}
					else
						output += (char)string.charAt(i);
				}
				//put html end of line <br>
				output += "<br>\n";
			}
			//print the output
			System.out.println(output);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void decreaseCounter(){
		if(colorCounter == 0)
			colorCounter = COLORS.length-1;
		else
			colorCounter--;
	}
	public static void increaseCounter(){
		if(colorCounter == COLORS.length-1)
			colorCounter = 0;
		else
			colorCounter++;
	}
}

Now, (String[ ] args). Why do we need to give parameters to main method while it is automatically called and how do we pass parameters?

Actually main method is called with the parameters given in the command line. If you have ever used command line on Linux or simply cmd.exe in Windows, you should have used arguments with the application called in the command line. I did not add a simple user interface to this code to talk about these arguments.
You can compile the file above using javac command (java compiler:)). Go to the folder where you put this file and write the following command:

javac ColorizeScheme.java

Now, you will see a file named ColorizeScheme.class in the same folder which is ready to be executed. In the following line, you see how to run this file:

java ColorizeScheme my-scheme.scheme

This will print the colorized HTML code based on the file named as my-scheme.scheme. How did we access my-scheme.scheme argument and become able to read the file named like that?. The answer is by taking first argument passed to the main method: args[0]. Number of arguments can be more than one, of course. But here in this example, only one argument is used.
Lastly, the output is printed to the command line but we want to see the result in the browser. You need to add the file name with a “>” in the front:

java ColorizeScheme my-scheme.scheme > my-scheme.htm

Now the output is written to the file “my-scheme.htm”. You can see the result by double clicking my-scheme.htm.
I tried my code with the scheme code in this page. And the result is this.

In this post, I will share implementation of newton-raphson method in python. I have already shared Java-implementation and I wrote the following code for Python practice. Older Java implementation can be found here. It is better to look at that, since I did not put enough comment on the Python code. I kept the variable names the same as in the older post.

I also want to mention documentation string of Python. Documentation string is the first string in function or class definition. It is the first line of the function if the string is written in double quote ” ” or single quote ‘ ‘. If you write the string in multiple lines to be concatenated, it will not happen. In order to have a multiple-line documentation string use triple quote ”’ ”’ which allows multiple-line strings in Python. Documentation string can be accessed using function_name.__doc__, Following code shows a multiple-line usage.
Python code:

def newton(k, a):
	'''This function computes the n-th root of
k, where k is the first and n is the second parameter'''
	sensitivity = 1000	#higher sensitivity gives better results
	x = 85
	for i in range(sensitivity):
		function = 1.0
		for j in range(a):
			function *= x
		x = x - ( function - k ) / ((a * function) / x)
	if int(x) == x:return int(x) 	#return integer if it has an integer value
	else: return x			#else return double value
print
print 'Documention for the function', newton.__name__, ':\n', newton.__doc__
print
print 'newton(27,3) returns', newton(27,3)
print 'newton(9,2) returns', newton(9,2)
print 'newton(65535,16) returns', newton(65535, 16)
print 'newton(64,3) returns', newton(64,3)
print

And the output:

Documention for the function newton :
This function computes the n-th root of
k, where k is the first and n is the second parameter

newton(27,3) returns 3
newton(9,2) returns 3
newton(65535,16) returns 1.99999809264
newton(64,3) returns 4

December 26th, 2009Goto-programming with Java

Assume that you have an algorithm written in goto-programming style and you do not want to do any changes in algorithm. You can implement such an algorithm using Java in two ways, without dealing with the efficiency.
First way is to define a function for each step and call the functions within the other.
The other way is to write steps into a swith-case and put them into a loop.

I implemented a meaningless algorithm in both ways and realized that switch-case is 2.5x to 4x faster than function-based implementation. Of course, as the algorithm changes, the ratio will change, but because of the function-call overhead, function-based implementation will be slower. Silly algorithm is:

		counter is 0
step1:	increment counter by 1
		goto step2
step2:	goto step3
step3:	if counter is less than 500
			then goto step1
		else
			goto step4
step4:	increment counter by 1
		print counter

And Java code:

public class GoTo{
	static int i = 0;
	public static void main(String[] args){
		//time calculation of function call based implementation
		long time = System.nanoTime();
		step1();
		time = System.nanoTime() - time;
		System.out.println(time);

		//swicth-case implementation
		int step = 1;
		int j = 0;
		long time2 = System.nanoTime();
		while(j < 501){
			switch(step){
				case(1):{
					j++;
					step = 2;
				}break;
				case(2):{
					step = 3;
				}break;
				case(3):{
					if(j < 500)
						step = 1;
					else
						step = 4;
				}break;
				case(4):{
					j++;
					System.out.println("j is " + j);
				}break;
			}
		}
		time2 = System.nanoTime() - time2;
		System.out.println(time2);

		//calculate ratio of implementation times
		Integer intT2 = new Integer((int)time2);
		Integer intT = new Integer((int)time);
		double ratio = intT.doubleValue() / intT2.doubleValue() - 1;

		//print the result
		System.out.println("Switch-case is " + ratio + " times faster than function call based goto programming");
	}

	//functions of function based implementation
	public static void step1(){
		i++;
		step2();
	}
	public static void step2(){
		step3();
	}
	public static void step3(){
		if(i < 500)
			step1();
		else
			step4();
	}
	public static void step4(){
		i++;
		System.out.println("i is " + i);
	}
}

Output:

i is 501
589740
j is 501
133886
Switch-case is 3.4047921365938185 times faster than function call based goto programming

November 26th, 2009Zip File Creation in Java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
/**
 * @author:		Mustafa Zengin
 * @date:		April 18, 2008
 * @desc:		Adds files whose paths are given by a String ArrayList to a zip file
 *				with a name which is given as a parameter as well and returns proper messages.
 * @version:	1.00
 */

/**
 * Usage: 	Create a new String ArrayList which holds the paths of files
 *			that are desired to be zipped. Give a name for your zip file
 *			without ".zip" and call the static generateZipFile method
 *			of this class with params ( zipFileName, filesArrayList )
 *
 *			If you want to create the zip file in a specific folder
 *			write the path and the name of zip file as param zipFileName.
 */

 /**
  * Modified:	May 5, 2008 by Mustafa Zengin
  *				Before mod. : Only files in the class directory was acceptable
  *				After mod.  : All files are acceptable.
  */

public class ZipGenerator
{
	public static String generateZipFile ( String zipFileName, ArrayList<String> filePaths)
	{
		// if no file path is given, print an appropriate message.
		if ( filePaths.size() == 0)
			return "You haven't given a file to be zipped!";

		// In order not to create files with their filePaths in the zip file
		// We create File objects ( we will use getName() method of File class later)
		ArrayList<File> files = new ArrayList<File>();
		for (int i = 0; i < filePaths.size(); i++)
			files.add( new File (filePaths.get( i)));

		byte[] buffer = new byte[1024]; // will be used while writing the zip file
		String msg = ""; 				// will be used for returned messages

		try
		{
			// output zipFile is generated with given name as param.
			ZipOutputStream output = new ZipOutputStream( new FileOutputStream( zipFileName + ".zip"));

			for ( int i = 0; i < files.size(); i++)
			{
				FileInputStream input;
				try
				{
					input = new FileInputStream( files.get( i).getName());

					// create a new entry in zip file with given file path
					output.putNextEntry( new ZipEntry( files.get( i).getName()));

					// this process adds the bytes from the original file to new Zip entry.
					// for details check Java API.
					int len;
					while ( ( len = input.read( buffer)) > 0)
					{
						output.write( buffer, 0, len);
					}

					// close output and input to move on the next input-output if exists.
					output.closeEntry();
					input.close();
				}
				catch ( FileNotFoundException fnfe)
				{
					/** I added a message for "Invalid Paths"
					 * In order not to face with an IndexOutOfBounds Exception
					 * when I removed an element from ArrayList, I decremented
					 * "i" of 'for loop' by 1
					 */
					msg += "Invalid Path: " + files.get( i) + "\n";
					files.remove( i);
					i--;
				}
			}

			/** All bytes are added to zip file and I closed the output completely.
			 * It is not the same as closing entry. Entries are files within the zip file*/
			output.close();
		}
		catch ( IOException ioe)
		{
			return "Encountered with an IOException! Zip File couldn't be created.\nWhat you can do is checking file paths you entered.";
		}

		// A proper message for the added files.
		msg += "-----------\nAdded Files\n-----------\n";
		for ( int i = 0; i < files.size(); i++)
		{
			msg += files.get( i) + "\n";
		}
		msg += "-----------";

		// return the whole message.
		return msg;
	}
}

Following java code is calculating the roots of a number using Newton-Raphson method. You can find the details as comments inside the code, and you can see the mathematical background of the method here or in your calculus books.

import java.util.Scanner;
import java.text.DecimalFormat;
/**
* computing a-th degree root via newton-raphson method
*
*		formula is this:
*					   f (x  )
*	x	    =  x    _  _____n
*	  (n+1)     (n)    f'(x  )
*				     	    n
*
* Our function in this program is
*		f(x) = x^a - k = 0
* when k is the number whose a-th degree root we want to compute.
*
* @author  Mustafa ZENGiN
* @version 1.00, 2007/11/14
*/
public class Newton
{

	public static void main( String[] args)
	{
		Scanner scan = new Scanner( System.in);

		// CONSTANTS
		final int SENTIVITY = 15; //The bigger number is, the closer result you can get		

		// VARIABLES
		double x = 1, k, a;	//Variable names come from the function on line 13

		// PROGRAM CODE
		//1. Ask for and get a number that user wonders its a-th degree root (and degree also)
		System.out.print("Please enter a number whose a-th root you wonder: ");
		k = scan.nextDouble();

		System.out.print("Degree (a): ");
		a = scan.nextDouble();		

		//2. Apply Newton - Raphson method SENSIVITY number of times
		for (int i = 0; i < SENTIVITY; i++)
		{
			double function = 1; //is defined in the loop because we have to apply x^a function to all changed x
			for ( double p =1 ; p <= a; p++ )
			{
				function *= x; //function computes x^a
			}
			x = x - ( function - k ) / ((a * function) / x);
		}

		//3. Print the result. DecimalFormat class is used for just formatting the results
		DecimalFormat formatO = new DecimalFormat ( "#.############");
		String numeral = formatO.format(x);

		System.out.println(numeral);
	}

} // end of class Newton

In most of the cases, recursive algorithms are very small in term of lines of codes. But since this algorithm deals with a char array, it becomes very long for a recursive algorithm. This question was asked in our CS201 midterm last year, and very few number of people answered correctly. This question did not want us to check repeating letters in the char array, so it would be more complicated if it was asked. Now the code:

#include <iostream>
using namespace std;
void generateWords2( char *str, int strSize, char* firstChars, int sizeFirst){
	if ( strSize == 0){
		for( int i = 0; i < sizeFirst; i++)
			cout << firstChars[i];
		cout << endl;
	}
	else{
		for (int i = 0; i < strSize; i++){
			char* tmp = new char[strSize-1];
			for(int j = 0; j < i; j++)
				tmp[j] = str[j];
			for(int j = i; j< strSize-1; j++)
				tmp[j] = str[j+1];
			char* tmp2 = new char[sizeFirst + 1];
			for(int j = 0; j< sizeFirst; j++)
				tmp2[j] = firstChars[j];
			tmp2[sizeFirst] = str[i];
			generateWords2( tmp, strSize-1, tmp2, sizeFirst+1);
		}
	}
}

void generateWords( char* str, int strSize){
	if(strSize != 0)
		for (int i = 0; i < strSize; i++){
			char* tmp = new char[strSize-1];
			for(int j = 0; j < i; j++)
				tmp[j] = str[j];
			for(int j = i; j < strSize-1; j++)
				tmp[j] = str[j+1];
			char* tmp2 = new char[1];
			tmp2[0] = str[i];
			generateWords2( tmp, strSize-1, tmp2, 1);
		}
}
int main(){
	char* a = new char[9];
	a[0] = 'a';
	a[1] = 'b';
	a[2] = 'c';
	a[3] = 'd';
	a[4] = 'e';
	a[5] = 'f';
	a[6] = 'g';
	a[7] = 'h';
	a[8] = 'i';
	generateWords(a,9);
}

This piece of code helps me to change language in each page where the pages are named as the following.

If the page is in English: about.html

If the page is in Turkish: about2.html

and here is the code:

function changeLanguage(){
	var url = location.href;
	if(url.indexOf("2") < 0)
		url = url.replace(".html", "2.html");
	else
		url = url.replace("2.html", ".html");
	window.location = url;
}

The code is simply changing “.html” with “2.html” if the page is in English and desired to be in Turkish and vice versa. You can see it in action at www.mustafazengin.info


© 2007 Mustafa Zengin's Blog | iKon Wordpress Theme by Windows Vista Administration | Powered by Wordpress