Tuesday, March 28, 2017

Fibonacci number using Dynamic Programming (JAVA)

Recursion is most famous solution for the Fibonacci number. But it's complexity is higher.  It is 2^n. Is what can be better optimal solution. And Answer is Dynamic Programming. We can solve the problem in o(n). But for this we need to use space complexity. We will be saving our previous record to the memory. Let's see..

Initialize our array with certain length

========================================
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
========================================
We will manually assign 1 and 1 to the position 0 and 1 of array. Because we know in Fibonacci Series 1st and 2nd index is 1. 

========================================
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
========================================

now we will iterate through 2 to n and add (n-1) + (n-2) and save it to memory. Which we do is our recursive solution as well. So our array looks like this. 

=========================================
| 1 | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
=========================================

we continue iterating it.

=========================================
| 1 | 1 | 2 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
=========================================
                                    :
                                   \/
finally it looks like this

==========================================================
| 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 | 89 | 144 | 233 | 377 | 610 | 987 | 1597 |
==========================================================

Below is Java code: 

 public static void main(String[] args) {

       Scanner in = new Scanner(System.in); // Taking input from console
       int q = in.nextInt();

       int[] arr = new int[q]; // Initializing array

       arr[0]= arr[1] = 1; // Setting 0 and 1st pos to 1

       System.out.print(arr[0]+" "+arr[1]+" "); printing 0th and 1st pos

       for(int i = 2; i<q;i++){  //iterating from 2nd to size

           arr[i] = arr[i-1]+arr[i-2]; // adding last two values

           System.out.print(arr[i]+" "); //Printing value

       }
    }

Wednesday, April 15, 2015

Performing UI Related task from Worker Thread using Handler

This Example shows How to do UI related task from Worker Thread using Handler. Main Thread contains Handler object. Which ever thread creates Handler object receives message from other thread (Handler Handles the Message).


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class Testing extends Activity {

// Handler Basically does Two task 1) Handle Message in current thread 2)
// Send to other Thread for proccessing
Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// UI thread creates object of Handler.  
mHandler = new Handler();

new Thread(new Runnable() { // Worker Thread
// Sending Runnable to Handler MessageQueue which will handled in UI Thread
@Override
public void run() {
mHandler.post(new Runnable() { 
@Override
public void run() {
// Showing Toast Message
Toast.makeText(getApplicationContext(), "I am from Worker Thread", Toast.LENGTH_LONG).show();
}
});
}
}).start();  // Starting Thread
}
}
 

Sending message from one worker thread to other worker thread using Handler and Looper (Android)

Below code snippet explains how to send message from one worker thread to another worker thread using Handler, Looper and Message. First worker thread receive message from second thread.



import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public class Testing extends Activity {

//Handler Basically does Two task 1) Handle Message in current thread 2) Send to other Thread for proccessing
Handler mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

new Thread(new Runnable() {   // First worker Thread
@Override
public void run() {
                                // Prepare a Massage Queue for Handler so one by one can be processed
Looper.prepare(); 
mHandler = new Handler() { // Handler is associated with current thread
 // Handling Received Messages
                                       @Override
public void handleMessage(Message msg) {  
super.handleMessage(msg);
System.out.println("Recived By " + Thread.currentThread().getName() + " And Msg is: " + msg.arg1);

}
};
Looper.loop();

}
}).start();

new Thread(new Runnable() {   // Second  Worker Thread
@Override
public void run() {
int i = 0;
while (i < 100) {
/*Obtain a Message from Message Pool. It's good practice not to create Message Object but get from System itself. Saves memory.*/
Message msg = Message.obtain();
System.out.println("Sending MSg via: " + Thread.currentThread().getName() + "Data: " + i);
msg.arg1 += i;
mHandler.sendMessage(msg); // Sending Message to 1st worker thread
i++;
}
}
}).start();
}
}

Tuesday, April 14, 2015

Producer Consumer Problem Using Shared Variable

Hi folks, Below JAVA implementation of Producer Consumer using sheared Variable.Producer Produces and Consumer Consumes.

import java.util.Random;

public class ProducerConsumer {

static int food = 0;
static boolean flag = true; // To ensure producer produces first and for toggle
static Thread producer;
static Thread consumer;

public static void main(String... args) {


// Consumer Thread
consumer = new Thread(new Runnable() {
public void run() {
synchronized (producer) {  // locking producer
while (true) {
if (flag == false) {
try {
Thread.sleep(1000); // Delay so it consumes per second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I am consuming: "+food);
flag = true;
producer.notify(); // notifying producer
}
}
}
}
});
consumer.start(); // Starting consumer thread

// Producer Thread
producer = new Thread(new Runnable() {
public void run() {
synchronized (consumer) { // locking consumer
while (true) {
if (flag == true) {
try {
Thread.sleep(1000); // Delay so It produces every second
} catch (InterruptedException e) {
e.printStackTrace();
}
food = new Random().nextInt(100); // producing a random number
System.out.println("I am producing: "+food);
flag = false;
consumer.notify(); // Notifying consumer
}
}
}
}
});
producer.start(); // starting Producer Thread

}

}

Saturday, November 29, 2014

CCAvanue payment Integration For Android (With Sample Project)

Hi there!
It's been days that I have posted anything here! But this made me write this post
I was going through Payment Integration in India for mobile apps, specially for android. There are some famous Integration method available such as Paypal, Google Wallet. But These two have problems in India since they are not versatile payment method for every Bank and Indian currency.

At last I found CCAvanue which seems to me a better payment getway option in India. They have cool dashboard and a very effective customer service which is avail 24*7.

CCAvanue has two type of integration for android application, one is seemless and other one is non-seemless. Seemless provides you option to save card information to your database but this requires special PCI Certificate or SAQ based on no hits.

On Request from CCAvanue they provide you the mobile integration kit which carry Android and iOS Project with  two JSP file (One is getRSA.jsp and other one is ccavResponseHandler.jsp) which needs to be host on your register (register with CCAvanue ) website(You don't have to change anything in JSP file).  After hosting these two files you have two url which you will be needing in app.

Since they provide Seemless Integration which is also avail Here. I decided to provide the non-seemless Integration kit which is having three activity  first will take input from user second one will open the webView where user will do the transaction and last one which will show the status whether transaction was successful or failure. Non-seemless Integration kit is available Here, You can download (This is basically reduced code ). You have to change the merchant ID and three URL (Cancel URL, Redirect URL and RSA Url) and you are done. I have commented on code where you need to change things. So,  app flow will be like this

Enter Information ==> Click on Pay Button ==> Open the webView ==> Enter info ==> pay ==> StatusActivity

If Any further query you have, please comment.
Thanks




Thursday, April 18, 2013

Passing an object as parameter to a method

Passing an object as parameter is always a confusing concept. here is a java code given below which might help you understand this concept .

/*========================================*/

public class HelloWorld{
     public static void main(String []args){
       myroom obj = new myroom();
       dadsroom obj1 = new dadsroom();
       obj1.love(obj);
     }
}
 class myroom{
public int x;
    public int y =3;
}
class dadsroom{
 void love(myroom o){
       System.out.println(o.x +"and"+ o.y);
   }
}
/*========================================*/

SHOULD I CALL IT EXPLANATION ? :
 I've created three class in above code, one is HelloWorld which combines the main method, next is myroom, and last one is dadsroom. In main method, I've created an object of myroom "obj" and another object of dadsroom "obj1". dadsroom is having a method love which is receiving object of myroom and then printing instance variable using object of myroom. In main, I've called love method using object of class dadsroom and passing object of myroom  as parameter..

Let's have a formal EXPLANATION:
what i am trying to do is, i am having a template of myroom and also a template of dadsroom through their objects, now I am adding a room which is same as myroom(every thing is same as myroom cause it is instance of myroom) into dadsroom, now a room which is same as myroom is attached with dadsroom, I can access every feature (which was having myroom) through dadsroom. An object of myroom is attached with dadsroom by passing object of myroom.

Sunday, April 14, 2013

More about Activity Life Cycle with an example.

Hey there, Here is an example of Activity life cycle, This will illustrate more about how onCreate(), onStart(), onResume, onPause(), onStop() call in activity Life Cycle, I have Created two activity and given toast in each method, when you navigate the application Toast will pop on the screen as per Activity Life cycle.

<!-- ================First layout (main.xml)=====================-->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

<!-- ===================End of main.xml====================== -->


/*=========ActivityLifeCycleActivity (Corrosponding code to main.xml) ========*/
package com.hellboys.act;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ActivityLifeCycleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "1 onCreate()",Toast.LENGTH_LONG).show();
       
        Button b1;
        b1 = (Button) findViewById(R.id.but);
        b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent(ActivityLifeCycleActivity.this,abhi.class);
startActivity(intent);
}
});
    }
   
    public void onStart(){
    super.onStart();
    Toast.makeText(getBaseContext(), "1 onStart()",Toast.LENGTH_LONG).show();
    }
   
    public void onResume(){
    super.onResume();
    Toast.makeText(getBaseContext(), "1 onResume()",Toast.LENGTH_LONG).show();
    }
   
    public void onPause(){
    super.onPause();
    Toast.makeText(getBaseContext(), "1 onPause()",Toast.LENGTH_LONG).show();
    }
   
    public void onStop(){
    super.onStop();
    Toast.makeText(getBaseContext(), "1 onStop()",Toast.LENGTH_LONG).show();
    }
}
/*=============End of ActivityLifeCycleActivity=================*/

<!-- ================Second layout (abhi.xml)==================-->

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>
<!-- =====================End of abhi.xml======================= -->


/*=========Second Activity(Java code corresponding to abhi.xml) ========= */
package com.hellboys.act;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class abhi extends Activity{
@Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.abhi);
Toast.makeText(getBaseContext(), "2 onCreate()", Toast.LENGTH_LONG).show();
}

public void onStart(){
super.onStart();
Toast.makeText(getBaseContext(), "2 start()", Toast.LENGTH_LONG).show();
}
public void onResume(){
super.onResume();
Toast.makeText(getBaseContext(), "2 onResume()", Toast.LENGTH_LONG).show();
}
public void onPause(){
super.onPause();
Toast.makeText(getBaseContext(), "2 onPause()", Toast.LENGTH_LONG).show();
}
public void onStop(){
super.onStop();
Toast.makeText(getBaseContext(), "2 onstop()", Toast.LENGTH_LONG).show();
}
}
/*=================End of abhi============================*/


/*==========================Do +1 if like ....... ========================*/