Tuesday, April 2, 2013

Recursion

A life-saver funda which can really relieve the pain in the ass which iteration would other wise be.
Recursive function is one which calls itself again and again till a specified condition is reached.
It solves a problem by calling a copy of itself to process on a smaller problem. It is important though that the recursion would end at some condition. Otherwise, it is bound to throw stack overflow exception.
So i will be posting the recursion algos for the following scenarios where recursion is a saviour from the long long iterative algo.


  • Fibonacci and factorial
  • Merge sort and Quick sort
  • Binary Search
  • Tree traversal and Inorder, Preorder, Post Order
  • Graph Traversals: DFS and BFS
  • Dynamic Programming
  • Divide and Conquer Algo
  • Tower of Hanoi
  • Backtracking algos

So for the starters here goes the recursion algo for Factorial:

int fact(n)
{
  if(n>1){
     int j = fact(n-1)
     return n*j                        //we can combine these two statements as "return n* fact(n-1)"
  }
  else if(n==1)
  {
       return 1
  }
  else
       return 1
  }
}


Tuesday, March 26, 2013

Numbers in a digital form

So this code does a digital-i-sation of the number which you input.
Here's the expected output:


Try and play:

LedDisplayer.java


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class LedDisplayer {

public static void main(String args[]) {
ArrayList<Integer> digit = new ArrayList();
int n = 0;
boolean neg=false;
int i_min=Integer.MIN_VALUE;
int i_max=Integer.MAX_VALUE;
// char c='\u00AF'; //for upper score use this
try {
if (args.length != 0) {
n = Integer.parseInt(args[0]);
} else
n = 123456789;
} catch (NumberFormatException e) {
System.out.println("Not a valid number. Input an integer in the range "+i_min+" to "+i_max);
}
if(n<0){
neg=true;
}
HashMap l0=new HashMap();
l0.put(1, "   ");
l0.put(2, " _ ");
l0.put(3, " _ ");
l0.put(4, "   ");
l0.put(5, " _ ");
l0.put(6, " _ ");
l0.put(7, " _ ");
l0.put(8, " _ ");
l0.put(9, " _ ");
l0.put(0, " _ ");

HashMap l1=new HashMap();
l1.put(1, "  |");
l1.put(2, " _|");
l1.put(3, " _|");
l1.put(4, "|_|");
l1.put(5, "|_ ");
l1.put(6, "|_ ");
l1.put(7, "  |");
l1.put(8, "|_|");
l1.put(9, "|_|");
l1.put(0, "| |");

HashMap l2=new HashMap();
l2.put(1, "  |");
l2.put(2, "|_ ");
l2.put(3, " _|");
l2.put(4, "  |");
l2.put(5, " _|");
l2.put(6, "|_|");
l2.put(7, "  |");
l2.put(8, "|_|");
l2.put(9, " _|");
l2.put(0, "|_|");

int j = 0;
do {
int dig = n % 10;
digit.add(dig);
n = n / 10;
j++;
} while (n > 0);

for (int x = digit.size() - 1; x >= 0; x--) {
int digi=digit.get(x);
System.out.print(l0.get(digi));
}
System.out.println("");
for (int x = digit.size() - 1; x >= 0; x--) {
int digi=digit.get(x);
System.out.print(l1.get(digi));
}
System.out.println("");
for (int x = digit.size() - 1; x >= 0; x--) {
int digi=digit.get(x);
System.out.print(l2.get(digi));
}
}
}

Characters in Pyramid Form Problem

Thought i would enter this world with a bang.. But for now i would begin posting some simple java codes. Maybe will help someone some time. Feel free to post if  you have a better approach.

So here's the code for printing a string array of  characters where you need to print each character in the pyramid form.
You are given the number of lines and the characters. Say if you have to print and array of chars:
A,B,C,D,E,F in the pyramid form in an 8 lined pyramid, it should look like this:

Here's what i have written:

Pyramid.java

 public class Pyramid {
StringBuffer buf;

public static void main(String args[]){

Pyramid p=new Pyramid();
int numberOfLines=8;
String[] input={"A","B","C","D","E","F"};
String output=p.output(numberOfLines, input).toString();
System.out.println("Result:\n" + output);
}
private StringBuffer output(int numberOfLines, String[] input){
buf=new StringBuffer();
for(int currentLine=1;currentLine<=numberOfLines;currentLine++){

int arrayIndex=0;  //this will keep track of the letter being print.

//to leave initial gaps
for(int k=0;k<numberOfLines-currentLine;k++)
buf.append(" ");

//to start printing letter in the line
for(int j=0;j<currentLine;j++){

//check if still chars available in the array
if(arrayIndex<input.length){
buf.append(input[arrayIndex]).append(" ");
arrayIndex++;
}
//else reset to first location
else{
arrayIndex=0;
buf.append(input[arrayIndex]).append(" ");
arrayIndex++;
}
}
buf.append("\n");
}
return buf;
}
}


So there you go.
Plus only a small mod is required if you want to print the chars all in succession. without beginning from A in ever line. Something like this:

All you need to do is move the 
                              int arrayIndex=0; 
outside the for loop so that the arrayindex is not initialised to 0 for everyline.

Cheers and good luck. :)