Triangular nos

July 9, 2009 by abhirama

Java:


public class TriangularNumbers {
  public int get(int no) {
	if (no == 1) {
	  return no;
	} else {
	  return no + get(no - 1);
	}
  }

  public static void main(String[] args) {
	TriangularNumbers triangularNumbers = new TriangularNumbers();
	System.out.println(triangularNumbers.get(4));
  }
}

Python:


def triangular_no(no)  :
	if no == 1:
		return no
	return no + triangular_no(no - 1)

print triangular_no(4)

Postfix evaluator

July 7, 2009 by abhirama

1. Code does not check for malformed expressions.
2. Operators recognised are +,-,*,/.
3. Unary positive and negative operators are not supported.

Java:


public class PostfixEvaluator {
  public int evaluate(String postfixExpression) {
	LinkedList<Integer> stack = new LinkedList<Integer>();

	char[] chars = postfixExpression.toCharArray();

	for (char chr : chars) {
	  if (isLetter(chr)) {
		stack.add(Integer.valueOf(String.valueOf(chr)));
	  } else {
		int no1 = stack.removeLast();
		int no2 = stack.removeLast();
		stack.add(perfromMathematicalOperation(no2, no1, chr));
	  }
	}

	return stack.removeLast();
  }

  public static boolean isLetter(char chr) {
	try {
	  Integer.parseInt(String.valueOf(chr));
	  return true;
	} catch (NumberFormatException nfe) {
	  return false;
	}
  }

  public int perfromMathematicalOperation(int a, int b, char operator) {
	switch (operator) {
	case '+':
	  return a + b;
	case '-':
	  return a - b;
	case '*':
	  return a * b;
	case '/':
	  return a / b;
	default:
	  throw new AssertionError("Invalid operator : " + operator);
	}
  }

  public static void main(String[] args) {
	PostfixEvaluator postfixEvaluator = new PostfixEvaluator();
	System.out.println(postfixEvaluator.evaluate("34-5+"));
  }

}

Python:


import operator

operator_functions = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.div
}

postfix_expression = "34-5+"

stack = []

for char in postfix_expression :
	if char in operator_functions:
		no1 = int(stack.pop())
		no2 = int(stack.pop())
		stack.append(operator_functions[char](no2, no1))
	else :
		stack.append(char)

print stack.pop()

Question I asked in stackoverflow regarding this code.

Infix to postfix convertor

July 7, 2009 by abhirama

1. Code does not check for malformed expressions.
2. Operators recognised are +,-,*,/.
3. Unary positive and negative operators are not supported.

Java:


public class InfixToPostfix {

  public String convert(String input) {
	char[] chars = input.toCharArray();

	StringBuffer postfixExpression = new StringBuffer(input.length());

	LinkedList<Character> stack = new LinkedList<Character>();

	for (char chr : chars) {
	  if (isLetter(chr)) {
		postfixExpression.append(chr);
	  } else if (chr == '(') {
		stack.add(chr);
	  } else if (chr == ')') {
		while (! stack.isEmpty()) {
		  char chr1 = stack.removeLast();
		  if (chr1 != '(') {
			postfixExpression.append(chr1);
		  }
		}
	  } else {
		if (stack.isEmpty()) {
		  stack.add(chr);
		} else {
		  while (! stack.isEmpty()) {
			if (stack.getLast() == '(') {
			  break;
			}

			if ((stack.getLast() == '+' || stack.getLast() == '-') && (chr == '*' || chr == '/')) {
			  break;
			} else {
			  postfixExpression.append(stack.removeLast());
			}
		  }
		  stack.add(chr);
		}
	  }
	}

	while (! stack.isEmpty()) {
	  postfixExpression.append(stack.removeLast());
	}

	return postfixExpression.toString();
  }

  public static boolean isLetter(char chr) {
	try {
	  Integer.parseInt(String.valueOf(chr));
	  return true;
	} catch (NumberFormatException nfe) {
	  return false;
	}
  }

  public static void main(String[] args) {
	InfixToPostfix postFixToInfix = new InfixToPostfix();
	System.out.println(postFixToInfix.convert("1*(2+3)-4/(5+6)"));
  }

}

Python:


infix_expression = "3+4*3"

postfix_expression = ""
stack = [];

for char in infix_expression :
	try :
		char = int(char);
		postfix_expression = postfix_expression + str(char)
	except :
		if char == "(" :
			stack.append(char);
		elif char == ")" :
			while len(stack) != 0 :
				char1 = stack.pop()
				if char1 != "(" :
					postfix_expression = postfix_expression + char1
		else :
			if len(stack) == 0 :
				stack.append(char)
			else :
				while len(stack) != 0 :
					if stack[len(stack) - 1] == "(" :
						break

					if (stack[len(stack) - 1] == "+" or stack[len(stack) - 1] == "-") and (char == "*" or char == "/") :
						break
					else :
						postfix_expression = postfix_expression + str(stack.pop())

				stack.append(char)

while len(stack) != 0 :
	postfix_expression = postfix_expression + str(stack.pop())

print postfix_expression

Insertion Sort

July 3, 2009 by abhirama

Java:


public class InsertionSort {
  private List<Integer> nos;

  public InsertionSort(List<Integer> nos) {
	this.nos = nos;
  }

  public void sort() {
	for (int count = 1; count < this.nos.size(); ++count) {
	  int markedValue = this.nos.get(count);
	  int i = count;
	  while (i > 0 && markedValue < this.nos.get(i - 1)) {
		this.nos.set(i, this.nos.get(i - 1));
		--i;
	  }

	  this.nos.set(i, markedValue);
	}
  }

  public static void main(String[] args) {
	List<Integer> nos = new ArrayList<Integer>(Arrays.asList(new Integer[] { 3, 6, 1, 5, 4, 2 }));
	InsertionSort insertionSort = new InsertionSort(nos);
	insertionSort.sort();

	System.out.println(nos);
  }

}

Python:


nos = [3, 6, 1, 5, 4, 2]

for marked_index in range(len(nos)) :
	marked_value = nos[marked_index]
	i = marked_index

	while i > 0 and nos[i - 1] > marked_value :
		nos[i] = nos[i - 1]
		i = i - 1

	nos[i] = marked_value

print nos

Selection Sort

July 3, 2009 by abhirama

Java:


public class SelectionSort {
  private List<Integer> nos;

  public SelectionSort(List<Integer> nos) {
	this.nos = nos;
  }

  public void sort() {
	if (this.nos == null || this.nos.size() == 0 || this.nos.size() == 1) {
	  return;
	}

	int count = 0;

	while (count < this.nos.size() - 1) {
	  int smallest = this.nos.get(count);
	  int smallestIdx = count;
	  for (int i = count; i < this.nos.size(); ++i) {
		if (this.nos.get(i) < smallest) {
		  smallest = this.nos.get(i);
		  smallestIdx = i;
		}
	  }

	  swap(count, smallestIdx);
	  ++count;
	}
  }

  protected void swap(int firstIdx, int secondIdx) {
	int temp = this.nos.get(secondIdx);
	this.nos.set(secondIdx, this.nos.get(firstIdx));
	this.nos.set(firstIdx, temp);
  }

  public static void main(String[] args) {
	List<Integer> nos = new ArrayList<Integer>(Arrays.asList(new Integer[] {3, 6, 1, 5, 4, 2}));
	SelectionSort selectionSort = new SelectionSort(nos);
	selectionSort.sort();

	System.out.println(nos);
  }

}

Python:


nos = [3, 6, 1, 5, 4, 2]

count = 0;
while count < len(nos) - 1 :
	smallest = nos[count]
	smallest_idx = count

	for x in range(count, len(nos)) :
		if nos[x] < smallest :
			smallest = nos[x]
			smallest_idx = nos.index(smallest)

	nos[count], nos[smallest_idx] = nos[smallest_idx], nos[count]
	count = count + 1

print nos

Bubble Sort

July 3, 2009 by abhirama

Java:


public class BubbleSort {
  private List<Integer> nos;

  public BubbleSort(List<Integer> nos) {
	this.nos = nos;
  }

  public void sort() {
	if (this.nos == null || this.nos.size() == 0 || this.nos.size() == 1) {
	  return;
	}

	int count = this.nos.size();

	while (--count >= 1) {
	  for (int i = 0; i < count; ++i) {
		int first = this.nos.get(i);
		int second = this.nos.get(i + 1);

		if (first > second) {
		  this.nos.set(i, second);
		  this.nos.set(i + 1, first);
		}

	  }
	}
  }

  public static void main(String[] args) {
	List<Integer> nos = new ArrayList<Integer>(Arrays.asList(new Integer[] {3, 6, 1, 5, 4, 2}));
	BubbleSort bubbleSort = new BubbleSort(nos);
	bubbleSort.sort();
	System.out.println(nos);
  }
}

Python:


nos = [3, 6, 1, 5, 4, 2]

count = len(nos) - 1

while count >= 1 :
	for i in range(count) :
		first = nos[i]
		second = nos[i + 1]

		if first > second :
			nos[i], nos[i + 1] = second, first

	count = count - 1

print nos

GVIM and clipboard

June 15, 2009 by abhirama

I love GVIM as an editor but my only gripe with it was, I was not able to figure out how to copy to clipboard and how to paste from clipboard. Finally after lots of poking around I did figure it out.

Copying from clipboard:
In insert mode press <shift> + <insert>

Copying to clipboard:
Once you visually select the content to copy, press *y

Java code to generate word combinations

June 9, 2009 by abhirama

Say you have a list of words like “foo bar moo”. You want to generate all combinations of this list.

foo
bar
moo
foo bar
bar moo
foo moo
foo bar moo

Below is the piece of java code to do this. I got this idea from one of the threads in perl monks.


public class Combinations<T> {
  private List<T> originalList;

  public Combinations(List<T> originalList) {
	this.originalList = originalList;
  }

  public List<List<T>> getCombinations() {
	List<List<T>> combinations = new LinkedList<List<T>>();

	int size = this.originalList.size();

	int threshold = Double.valueOf(Math.pow(2, size)).intValue() - 1; 

	for (int i = 1; i <= threshold; ++i) {
	  LinkedList<T> individualCombinationList = new LinkedList<T>();
	  int count = size - 1;

	  int clonedI = i;
	  while (count >= 0) {
		if ((clonedI & 1) != 0) {
		  individualCombinationList.addFirst(this.originalList.get(count));
		}

		clonedI = clonedI >>> 1;
		--count;
	  }

	  combinations.add(individualCombinationList);

	}

	return combinations;
  }
}

Basic idea here is to map your combinations to binary digits. For the above list it would be

000 ->empty list
001 ->moo
010->bar
011->bar, moo
100->foo
101->foo,moo
110->foo,bar
111->foo,bar,moo

So, all you have to do is

1. Iterate from 1 to 2 ^ list size – 1.
2. Right shift each of the formed digits and if the right most digit is one pick the object from the appropriate position in the list.

Open layers and resolution

May 7, 2009 by abhirama

Being new to GIS and Open layers I spent a long time trying to make sense of what resolution is. Finally I think I have a fair idea of what resolution means in open layers world.

Resolution is nothing but a way of saying how much your map units vary as you move on the computer screen.

Say, you want to represent a map bounded by ( -180,-90,180,90) in a window of dimension 256×256. Now how do you calculate the resolution?
Since the map extends from -180 to +180, you have to fit a total of 360 degrees in a screen of size 256. That is, your resolution is 360/256=1.40625.

Source code in wordpress blogs

May 5, 2009 by abhirama

http://support.wordpress.com/code/

I had been looking around for this since ages and today I found it.