Efficient I/O for BigIntegers : case Study UVa 1230 (Modex)

Hello People,its been long since my last blog post…I wanted to write about Faster I/O for BigIntegers….so here it is

Introduction :

java provides a powerful ‘BigInteger’ class. Competitive programmers may find it useful when they face problems with huge data range. Rather implementing a bigInt class in C++ ( which is cumbersome and time-consuming) ,its beffer to have a firm knowledge about the BigInteger  class…

Why Faster I/O methods :

haters say Java is slow ~_~ ..well that is because they use Naive I/O methods…

so,haters gonna hate. One must use faster I/O to avoid Time Limit Exceed( TLE) . other wise,its the coder who is making his code slow..

say java is slow -_-

say java is slow -_-

  • Integer Input :

naive way :

 int num;

 scanner sc =new Scanner(System.in);

 num = sc.nextInt();

Smart way :

InputStreamReader isr =new InputStreamReader(System.in);
BufferedReader br =new BufferedReader(isr);
int num = Integer.parseInt(br.readLine( ) );
  •  String.Split() vs StringTokenizer : it is always a must to use StringTokenizer to tokenize strings.then we can use those strings to create objects of other type
  • multiple inputs in a single line :

suppose one has to take three bigInteger inputs per line

naive way( leading to TLE) :

BigInteger x,y,n;
x= BigInteger.valueOf( sc.nextInt() );
y= BigInteger.valueOf( sc.nextInt() );
n= BigInteger.valueOf( sc.nextInt() );

smart way :

BigInteger x,y,n;
String input = br.readLine();
StringTokenizer st =new StringTokenizer(input);
x = new BigInteger(st.nextToken());
y = new BigInteger(st.nextToken());
n = new BigInteger(st.nextToken());

to Sum things up,lets see UVa problem 1230(Modex)

problem link : http://uva.onlinejudge.org/external/12/1230.html

problem description : its just a simple modular exponentiation problem.i am just trying to show two different approach to solve this problem.

approach 1 : bad Approach

for I/O : using

  • Scanner
  • Sc.nextInt() and Sc.nextBigInteger()


import java.math.BigInteger;
import java.util.Scanner;

 
public class Main
{
 
 public static void main(String[] args)  
 {
 
  Scanner sc = new Scanner(System.in);
  BigInteger x,y,res,n;
  int Tcase = sc.nextInt();
  while (Tcase-->0)
  {
	 
   
    x = (sc.nextBigInteger());
    y = (sc.nextBigInteger());
    n = (sc.nextBigInteger());

    res =x.modPow(y, n);
      
    System.out.println(res);
     
    
   }
  	int garbage = sc.nextInt();
  	
 }
 
}

now turning our attention on using faster input methods

Approach 2 : improvized approach

For I/O using :

  • BufferedReader with InputStreamReader
  • StringTokenizer() and br.readLine()
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
 
public class Main


{
 
 public static void main(String[] args) throws NumberFormatException, IOException 
 {
 
  InputStreamReader isr =new InputStreamReader(System.in);
  BufferedReader br =new BufferedReader(isr);
  BigInteger x,y,res,n;
  int Tcase = Integer.parseInt(br.readLine( ) );
  while (Tcase-->0)
  {
	 
    String input = br.readLine();
    StringTokenizer st =new StringTokenizer(input);
    x = new BigInteger(st.nextToken());
    y = new BigInteger(st.nextToken());
    n = new BigInteger(st.nextToken());
    res =x.modPow(y, n);
    String ans= res.toString();
       
    System.out.println(ans);
     
    
   }
  	int garbage = Integer.parseInt(br.readLine( ) );
  	
 }
 
}

UVa 374-Big Mod

A number theory problem.I solved it first using Java’s method “modPow” of the ‘BigInteger’ Class…so in this code ‘bigInteger’ is used.

Description

The java.math.BigInteger.modPow(BigInteger exponent, BigInteger m) returns a BigInteger whose value is (thisexponent mod m). Unlike pow, this method permits negative exponents.

Declaration

Following is the declaration for java.math.BigInteger.modPow() method

public BigInteger modPow(BigInteger exponent, BigInteger m)

Parameters

  • exponent – the exponent
  • m – the modulus

Return Value

This method returns a BigInteger object whose value is thisexponent mod m.


import java.math.BigInteger;
import java.util.Scanner;
public class Main374 {

	public static void main(String[] args) 
	{
		
		BigInteger b,r,m;
		int p;
		Scanner sc=new Scanner(System.in);
		while(sc.hasNext() )
		{
			b = sc.nextBigInteger();
			p = sc.nextInt();
			m = sc.nextBigInteger();
			
			r = b.modPow(BigInteger.valueOf(p),m);
			System.out.println(r);
		}		
	}

}

2nd method is the recursive method of Modular exponentiation. using ‘long’ data type. Not using BigInteger.
from number theory, (a*b*c)%m =((a%m)*(b%m)*(c%m))%m.

Capture


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class MainBigMod 
{
	 public static void main (String args[]) throws IOException
	 {
		  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		  String input;
		  StringBuffer sb=new StringBuffer();
		  
		  while((input=br.readLine())!=null)
		  {
			   if(input.trim().equals(""))
			    input=br.readLine();
			   long B=Long.parseLong(input.trim());
			   long P=Long.parseLong(br.readLine().trim());
			   long M=Long.parseLong(br.readLine().trim());
			   sb.append(bigmod(B,P,M)+"\n");
		   
		  }
		  System.out.print(sb);
	 }
	 public static long bigmod(long b,long p,long m) //recursive
	 {
	  if(p==0)
	   return 1;
	  else if(p%2==0)
	  {
	   long temp=bigmod(b,p/2,m);
	   return ((temp % m)*(temp % m)) % m;
	  }
	  else
	   return ((b % m)*(bigmod(b,p-1,m) % m)) % m;
	     
	 }
}

Programming Languages Humour

programming languages

If Programming Languages Were Women :

PHP is your teenage sweetheart, the girl you first awkwardly fumbled around with that one summer. Just don’t try and start a more serious relationship – this girl has serious issues.

Perl is PHP’s older sister. She might be a bit old for you, but she was pretty popular back in the 90s. In a long-term relationship with Larry Wall, so her standards have dropped, and she’s looking seriously fugly now. “I don’t care what y’all say, I still love her!”, he says. No-one else does.

Ruby is the cool kid of the scripting family. When you first saw her, she took your breath away with her beauty. She was fun, too. At the time she seemed a bit slow and ditzy – though she’s matured a lot in the last few years.

Python is Ruby’s more sensible sister. She’s elegant, classy, and sophisticated. She’s perhaps tooperfect. Most guys are like “dude, how can you not like Python!?”. Sure, you like Python. You just consider her the boring version of the edgy and romantic Ruby.

Java is a successful career woman. Some people who’ve worked with feel she owes her position less to ability and more to her knack for impressing the middle-management types. You might feel that she’s the sensible type you should settle down with. Just prepare for years of “NO THAT DOESNT GO THERE GOD YOU ALWAYS USE THE WRONG TYPE INTERFACE AND YOU MISSED A SEMICOLON” nagging.

C++ is Java’s cousin. Similar to Java in many ways, the main difference being she grew up in a more innocent time and doesn’t believe in using protection. By “protection”, I mean automatic memory management, of course. What did you think I meant?

C is C++’s mom. Mention her name to some old grey beard hackers and they’re sure to reminisce with a twinkle in their eye.

Objective C is another member of the C family. She joined that weird church a while back, and won’t date anyone outside of it.

Haskell, Clojure, Scheme and their friends are those hipster, artsy, intellectual girls you probably spent a blissful college summer with a few years ago. The first girls who really challenged you. Of course, it could never have become something more serious (you tell yourself). Though you’ll always be left asking “what if?”

You might be put off C# due to her family’s reputation. But they’ve gone legit, the last few years, they tell you. Once you’re one of us, you’re one of us, you hear? You need a database? Her brother MSSQL will hook you up. Need a place to stay? Heck, her daddy will even buy you your own mansion on Azure avenue. What’s that, you’re having second thoughts about all these overly friendly relatives? No, you can never leave. You’re part of the family, now, ya hear?

Javascript – hey, wasn’t that the girl you first kissed, way before even PHP came on the scene? I wonder what she’s doing now. I hear her career’s really taken off in the last few years. Would be cool to catch up some time, if only for old time’s sake… (You catch sight of her, dressed head to toe in designer jQuery)… wow, somebody grew into a beautiful swan…e else

If Programming Languages Were Weapons :

if programming languages were waepons

If Programming Languages Were Superheroes :

http://www.codingninja.co.uk/if-programming-languages-were-superheros/

If Programming Languages Were Vehicles :

http://crashworks.org/if_programming_languages_were_vehicles/

UVA 10701 : Pre,In,Post

Problem Description :

compute the post-order traversal of a binary tree given its in-order and pre-order traversals.

Problem LINK :

http://uva.onlinejudge.org/external/107/10701.html

/* a tree type structure, that has 3 parts : (i) Data Field(D),
                                             (ii) Left SubTree(left link == L),
                                             (iii) Right SubTree(right link == R)
PREorder( D --> L --> R)
INorder( L--> D --> R)
POSTorder( L --> R --> D)
*/
#include<iostream>
#include<string>
using namespace std;

struct node
{
    char data;
    node *left;
    node *right;
};

long long pre;

node* construct_tree(string preorder, string inorder,int inStart, int inFinal)
{
    if(inStart>inFinal)
    {
    return NULL;
    }
    long long i,inIndex;

    node *temp=new node;
    /* this is the root, always.
    because the first Entry of PreOrder Traversal is always the root of that tree
    and this root is the last Entry for PostOrder Traversal */

    temp->data=preorder[pre++];

    for(i=inStart;i<=inFinal;i++)
    {
        if(inorder[i]==temp->data)
         /** searching the position of the root in the INORDER tree.
        this will be used as the border in left & right child partition */
        {
        inIndex=i;
        }
    }
    temp->left=construct_tree(preorder,inorder,inStart,inIndex-1);
    temp->right=construct_tree(preorder,inorder,inIndex+1,inFinal);
    return temp;
}

void postorder_traversal(node *MyNewlyBuiltTree) //POSTorder( L --> R --> D)
{
    if(MyNewlyBuiltTree==NULL)
        return;

    postorder_traversal(MyNewlyBuiltTree->left);

    postorder_traversal(MyNewlyBuiltTree->right);

    cout<<MyNewlyBuiltTree->data;
}

int main()
{
    int Testcases;
    cin>>Testcases;
    int nodes;
    string preorder,inorder,postorder;

    for(int i=0;i<Testcases;i++)
    {
           //pt 1 input the Preorder & Inorder Traversal
        cin>>nodes>>preorder>>inorder;

        pre=0;
        node *MyTree;
        //pt2 constructing the tree
        MyTree=construct_tree(preorder,inorder,0,nodes-1);

        //pt 3 getting the preorder
        postorder_traversal(MyTree);
        cout<<endl;
    }

return 0;
}

BigInteger Vs BigDecimal

 
imagem_java

To achieve accuracy & precision and dealing with large numbers to work with such as factorials,googol numbers,huge financial data then it may be best to use BigDecimal and BigInteger instead of primitive types. Few other characteristics of BigDecimal and BigInteger are also:

  1. Both are from immutable objects.
  2. Both extend from Number class and implement comparable interface

 

But there are few Differences- both in performance & in data storage.


 

Using Instrumentation.getObjectSize(), we can easily know their respective sizes...

  • BigDecimal : 32 bytes.
  • BigInteger : 56 bytes.

also, comparing running time :

Data Type Used       time       rank

 

  •  BigDecimal :           1.552       849

 

  •  BigInteger :            1.335       663

 


 

a BigDecimal is essentially a wrapper around a BigInteger that “remembers where the decimal point is”.

Wrapping always causes performance and memory penalty.


 

So,maybe,BigInteger is “Big” compared to BigDecimal … in both performance & data preservation.

 

 

java-example3-300x200

UVa Problem 11448 : http://uva.onlinejudge.org/external/114/11448.html
BigDecimal code :

import java.math.BigDecimal;
import java.util.Scanner;

public class Main11448 
{

	public static void main(String[] args) 
	{
		int Tcase;
		Scanner sc = new Scanner(System.in);
		Tcase = sc.nextInt();
		
		int i;
		BigDecimal a,b,res;
		
		for( i=0; i<Tcase; i++ )
		{
			a = sc.nextBigDecimal();
			b = sc.nextBigDecimal();
			res = a.subtract(b);
			
			System.out.println(res);
		}

	}

}

BigInteger code :


import java.math.BigInteger;
import java.util.Scanner;

public class Main_11448 
{

	public static void main(String[] args) 
	{
		int Tcase;
		Scanner sc = new Scanner(System.in);
		Tcase = sc.nextInt();
		
		int i;
		BigInteger a,b,res;
		
		for( i=0; i<Tcase; i++ )
		{
			a = sc.nextBigInteger();
			b = sc.nextBigInteger();
			res = a.subtract(b);
			
			System.out.println(res);
		}

	}

}

The Efficient Data Structure For Unique Key-Value entries

MapClassHierarchy-600x354Java_map_implementation1

java.util package has the following data Structures to handle Hashing(  Key-Value  pair) :

1.HashMap :
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.A drawback indeed 😉

2.TreeMap:

public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface.This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

 this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

3..LinkedHashMap :  Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation & m.containsValue(v) would return true if there is respective key of that value present.)

public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>

4.Hashtable(dictionary):
public abstract class Dictionary<K,V>
extends Object

The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up. Any non-null object can be used as a key and as a value.As a rule, the equals method should be used by implementations of this class to decide if two keys are the same.

 

5.IdentityHashMap :

public class IdentityHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Serializable, Cloneable

This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).)

 

6.ConcurrentHashMap:

public class ConcurrentHashMap<K,V>
extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
………………….. Comparison of Efficeincy ………………..

But are they of same efficiency ?
How they Perform when Unique key-Value entries are to be dealt with?

i am sharing UVa 10282 as the case where i am experimenting with each of them. i used 5 different data structures & submitted to the OJ…


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class Main10282
{

    public static void main(String[] args) throws IOException 
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuffer sb = new StringBuffer(&quot;&quot;);
        String m=&quot;&quot;;
      
      IdentityHashMap&lt;String,String&gt;lhm =new  IdentityHashMap &lt;String,String&gt; ();
       
      while ((m=br.readLine())!=null) 
      {
            if(m.trim().equals(&quot;&quot;))
                break;
           
            String[]str=m.split(&quot; &quot;);
            lhm.put(str[1], str[0]);
        }
      /* input ends*/
        
      while ((m=br.readLine())!=null) 
      {
            m=m.trim();
            if(lhm.containsKey(m))
         // if(lhm.get(m)!=null) only for dictionary
            {
                sb.append(lhm.get(m)).append(&quot;\n&quot;);
            }
            
            else //not found in native language
            {
                sb.append(&quot;eh\n&quot;);
            }
        }
        System.out.print(sb);
    }
}

and my C++ code :

#include &lt;cstdio&gt;
#include &lt;iostream&gt;
#include &lt;map&gt;
#include &lt;sstream&gt;
using namespace std;
int main()
{
    string a,b,c,d;

    map &lt;string,string&gt;mymap;

    while( getline(cin,c),c.size() )
    {
        stringstream SS;
        SS &lt;&lt; c;
        SS &gt;&gt; a&gt;&gt; b;
        mymap[b]=a;
    }

    while(cin&gt;&gt;d)
    {
        cout &lt;&lt; (mymap.count(d) ? mymap[d] : &quot;eh&quot;) &lt;&lt; endl;
    }
return 0;

}

now analysis of Running Time is as follows :

Data Structure Used                 Time            Rank

  1. LinkedHashMap                     0.832           1266
  2. TreeMap                                1.085           2327
  3. Hashtable(dictionary)             0.792           1158
  4. IdentityHashMap                    0.789            1147 ( the  best)
  5. ConcurrentHashMap             0.865            1382
  6. C++ STL Map                        0.959            1765

Java_program_map_perf_compare  Java_program_map_perf_compare2

So, for unique key-value pairs….simple HashTable is not the best Data Structure 🙂

Even C++ STL map is also not the best Choise.

And JAVA Data Structures are sometimes more efficient than C++ Data Structures…as they are implemented in a low memory consuming way

7 good & 2 bad Ways of inputiing a single Char in java

First i would like to share the different Coding Styles.

    1. Using a Scanner :

              Scanner sc = new Scanner(System.in);

    1. Using a Buffered Reader :

            InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);

    1. Using a a DataInputStream :

            DataInputStream in=new DataInputStream(System.in);

Using Scanners :
# 1 : 
Scanner sc = new Scanner(System.in);
char c;
System.out.println("Enter a character : ");
c = sc.next().charAt(0);
System.out.println("you entered : "+ c);
This really is a good Compact way

# 2 : 

 Using a temporary String – a good straight-forward elaborate way

System.out.println(“Enter a character : “);
String tBuffer = sc.next();
c = tBuffer.charAt(0);
System.out.println(“you entered : “+ c);

# 3 :


This is another good  way. though not preferred

System.out.println(“Enter a character : “);
c = sc.next(“.”).charAt(0);
System.out.println(“you entered : “+ c);

# 4 :

NewBie Way 😀

System.out.println("Enter a character : ");
c =(sc.next()).charAt(0);
System.out.println(" "+ c);

Using BufferedReader :

the most Secured Way

System.out.println("Enter a character : ");
char ch=(char)br.read();
System.out.println("you entered : "+ ch);

Using DataInputStream :

has both advantage & dis-advantage- depends on how you use 😉

 how not to use :

1. the readChar() method  :

System.out.println("Enter a character : ");
char s=in.readChar();
System.out.println("you entered : "+ s);

2. the readByte() method :

System.out.println("Enter a character : ");
byte b = in.readByte();
c =(char)b;
System.out.println("you entered : "+ c);

how to use :

the read() method :
1.

System.out.println("Enter a character : ");
int tmp = System.in.read ();
c = (char) tmp;
System.out.println("you entered : "+ c);

2.

System.out.println("Enter a character : ");
c = (char)System.in.read();

System.out.println(“you entered : “+ c);

UVa 12347-Binary Search Tree

A binary search tree is a binary tree that satisfies the following properties:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

p12347
        Pre-order traversal (Root-Left-Right) prints out the node’s key by visiting the root node then traversing the left subtree and then traversing the right subtree. Post-order traversal (Left –Right-Root)  prints out the left subtree first and then right subtree and finally the root node. For example, the results of pre-order traversal and post-order traversal of the binary tree shown in Figure 1 are as follows:

Pre-order:       50 30 24 5 28 45 98 52 60

Post-order:     5 28 24 45 30 60 52 98 50

 Given the pre-order traversal of a binary search tree, you task is to find the post-order traversal of this tree

#include <cstdio>
using namespace std;

struct Tree
{
    int val = 0;
    Tree *L = NULL;
    Tree *R = NULL;
};

Tree * Pre_Order_Insert(Tree *H, int nodeValue)
 // inserts 'nodeValue' as a Pre-order node in the tree H
{
    Tree *N = new Tree;
    N->val = nodeValue;

    if (H == NULL)
        return N;

    Tree *Temp = H, *nxt = H;

    while (nxt != NULL)
    {
        Temp = nxt;
        if (node > nxt->val) // this is a larger value,so put it in right Subtree
            nxt = nxt->R;
        else // this is a smaller value, putting it in left Subtree
            nxt = nxt->L;
    }

    if (nodeValue> Temp->val)
           Temp->R = N;
    else
            T->L = N;
    return H;
}

void Post_Order(Tree *Root)
{
    if (Root == NULL)
        return;
    Post_Order(Root->L);
    Post_Order(Root->R);
    printf("%d\n", Root->val);
}

int main()
{
    Tree *MyBSTree = NULL;
    int node;
    while (scanf("%d", &node) != EOF)
    {
// pt 1 taking input the nodes and Inserting them to build a pre-order tree
         MyBSTree = Pre_Order_Insert(MyBSTree,node);
    }
    // tree is Built .
    
    //pt 2 - the Post order Traversal
    Post_Order(MyBSTree);
    return 0;
}

UVa 536 – Tree Recover

It was a fascinating problem for me…. There will be given A PreOrder & InOrder Traversal of a tree… you have to output the PostOrder Traversal of the tree
traversal1


/* a tree type structure, that has 3 parts : (i) Data Field(D),
                                             (ii) Left SubTree(left link == L),
                                             (iii) Right SubTree(right link == R)
PREorder( D --> L --> R)
INorder( L--> D --> R)
POSTorder( L --> R --> D)
*/
#include<iostream>
#include<string>
using namespace std;

struct node
{
    char data;
    node *left;
    node *right;
};

long long pre;

node* construct_tree(string preorder, string inorder,int inStart, int inFinal)
{
    if(inStart>inFinal)
    {
    return NULL;
    }
    long long i,inIndex;

    node *temp=new node;
    /* this is the root, always.
    because the first Entry of PreOrder Traversal is always the root of that tree
    and this root is the last Entry for PostOrder Traversal */

    temp->data=preorder[pre++];

    for(i=inStart;i<=inFinal;i++)
    {
        if(inorder[i]==temp->data)
         /* searching the position of the root in the INORDER tree.
        this will be used as the border in left & right child partition */
        {
        inIndex=i;
        }
    }
    temp->left=construct_tree(preorder,inorder,inStart,inIndex-1);
    temp->right=construct_tree(preorder,inorder,inIndex+1,inFinal);
    return temp;
}

void postorder_traversal(node *MyNewlyBuiltTree) //POSTorder( L --> R --> D)
{
    if(MyNewlyBuiltTree==NULL)
        return;

    postorder_traversal(MyNewlyBuiltTree->left);

    postorder_traversal(MyNewlyBuiltTree->right);

    cout<<MyNewlyBuiltTree->data;
}

int main()
{
    string preorder,inorder,postorder;
    //pt 1 input the Preorder & Inorder Traversal
    while(cin>>preorder>>inorder)
    {
        long long len_in=inorder.length();
        pre=0;
        node *MyTree;
        //pt2 constructing the tree
        MyTree=construct_tree(preorder,inorder,0,len_in-1);

        //pt 3 getting the preorder
        postorder_traversal(MyTree);
        cout<<endl;
    }

return 0;
}

Therap Java Fest 2014 . Mock Screening Test

So i took the mock Screening test of Therap Java Fest 2014…it was a great experience for me……something new…with my Passion Java 🙂

They had 4 questions. i got 3 correct 😐

The Actual Screening Test is scheduled to be held at 26th September .. Looking forward to it greatly 🙂

one example problem :


public class Main2 {
public static void main(String[] args) {
try {
badMethod();
System.out.print("A");
} catch (RuntimeException ex) {
System.out.print("B");
} catch (Exception ex1) {
System.out.print("C");
} finally {
System.out.print("D");
}
System.out.print("E");
}

public static void badMethod() {
throw new RuntimeException();
}
}

what will be the output of the code ?

i am expecting answers 🙂