Tuesday, December 18, 2012

Convert Seconds into HH:MM:SS in java?

Below are the methods to convert seconds into minute seconds format...


int day = (int)TimeUnit.SECONDS.toDays(seconds);      
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
 System.out.println("Random Element "+minute+":"+second);

OR 

public static void calculateTime(long seconds) {
   int day = (int) TimeUnit.SECONDS.toDays(seconds);
   long hours = TimeUnit.SECONDS.toHours(seconds) -
                TimeUnit.DAYS.toHours(day);
   long minute = TimeUnit.SECONDS.toMinutes(seconds) -
                 TimeUnit.DAYS.toMinutes(day) -
                 TimeUnit.HOURS.toMinutes(hours);
   long second = TimeUnit.SECONDS.toSeconds(seconds) -
                 TimeUnit.DAYS.toSeconds(day) -
                 TimeUnit.HOURS.toSeconds(hours) -
                 TimeUnit.MINUTES.toSeconds(minute);
   System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}

Monday, December 10, 2012

Android serialization of Objects ?


We can also see below links...
http://www.dreamincode.net/forums/topic/248522-serialization-in-android/

I'm going to go through the process of serializing and deserializing an object.

What this means is that we're going to convert an object into an array of bytes, which can easily be moved around or stored (for later use). And for deserialization we just take those bytes and convert them back into an Object.

The first one we have below is the serialization method, which just takes in a generic Object.


  public static byte[] serializeObject(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      ObjectOutput out = new ObjectOutputStream(bos);
      out.writeObject(o);
      out.close();

      // Get the bytes of the serialized object
      byte[] buf = bos.toByteArray();

      return buf;
    } catch(IOException ioe) {
      Log.e("serializeObject", "error", ioe);

      return null;
    }
  }

The second one is the deserialization method, which takes in an array of bytes;


  public static Object deserializeObject(byte[] b) {
    try {
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
      Object object = in.readObject();
      in.close();

      return object;
    } catch(ClassNotFoundException cnfe) {
      Log.e("deserializeObject", "class not found error", cnfe);

      return null;
    } catch(IOException ioe) {
      Log.e("deserializeObject", "io error", ioe);

      return null;
    }
  }

If you're wondering how to use these, well here is an example.


  public class Bla implements Serializable {
    public String blaDate;
    public String blaText;
  }
 
  Bla bla = new Bla();
 
  // assuming that both those serialize and deserialize methods are under the SerializerClass
  byte[] blaBytes = SerializerClass.serializeObject(bla);
 
  Bla deserializedBla = (Bla) SerializerClass.deserializeObject(blaBytes);

You've probably noticed that I implemented Serializable - you need this in order to serialize an object. Some of the built in objects already have this implemented - for example the ArrayList object.

When deserializing you need to cast it back to what the object was, since it's returning it as a generic Object - hence the (Bla).
Anyways, hope this helped someone, and if you noticed any mistakes, please let me know.

Thursday, November 22, 2012

Resource Folder Content ?


Check this link http://developer.android.com/training/multiscreen/index.html
http://developer.android.com/guide/practices/screens_support.html
http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html
http://jayxie.com/mirrors/android-sdk/resources/samples/MultiResolution/index.html
http://tools.android.com/recent/dealingwithdependenciesinandroidprojects
http://developer.android.com/about/dashboards/index.html

Taken from Here

In the /res folder you can have:

anim/ - XML files that define tween animations

color/ - XML files that define a state list of colors.

drawable/ - Bitmap files / Nine-Patches (re-sizable bitmaps) / State lists / Shapes / Animation drawables / Other drawables

layout/ - XML files that define a user interface layout.

menu/ - XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.

raw/ - Arbitrary files to save in their raw form.

values/ - XML files that contain simple values, such as strings, integers, and colors.

arrays.xml for resource arrays (typed arrays).
colors.xml for color values
dimens.xml for dimension values.
strings.xml for string values.
styles.xml for styles.
xml/ - Arbitrary XML files

Also see Accessing Alternative Resources for more specific device configurations (locale, dpi, size, aspect, orientation, etc



Also We can have value folder like : -

res/values-ldpi/dimens.xml
res/values-mdpi/dimens.xml
res/values-hdpi/dimens.xml
res/values-sw720dp/dimens.xml

Drawable folders can be of : -

xhdpi: 720x1280
large-hdpi: 640x960
hdpi: 480x640
mdpi: 320x480
ldpi: 240x320

res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)



The size ratios should match the nominal pixel densities as Android defines them:

ldpi - 120 pixels/inch; dpi scale = .75 (4 dpi = 3 pixels)
mdpi - 160 pixels/inch; dpi scale = 1 (1 dpi = 1 pixel)
hdpi - 240 pixels/inch; dpi scale = 1.5 (2 dpi = 3 pixels)
xhdpi - 320 pixels/inch; dpi scale = 2 (1 dpi = 2 pixels)

So if you make your xhdpi images twice the size (in pixels) of the mdpi resources, they will be the same dpi, meaning they will be the same physical size on their respective screens.








Thursday, November 1, 2012

How to show dialog yes/No before leaving the app via Back button ?



private boolean isLastActivity() {
   final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningTaskInfo> tasksInfo = am.getRunningTasks(1024);

    final String ourAppPackageName = getPackageName();
    RunningTaskInfo taskInfo;
    final int size = tasksInfo.size();
    for (int i = 0; i < size; i++) {
        taskInfo = tasksInfo.get(i);
        if (ourAppPackageName.equals(taskInfo.baseActivity.getPackageName())) {
            return taskInfo.numActivities == 1;
        }
    }

    return false;
}

You wil also require below permission in manifest....

<uses-permission android:name="android.permission.GET_TASKS" />

Thus in your Activty you can just use the following:

public void onBackPressed() {
    if (isLastActivity()) {
         showDialog(DIALOG_EXIT_CONFIRMATION_ID);
    } else {
         super.onBackPressed(); // this will actually finish the Activity
    }
}

Wednesday, October 17, 2012

List Chart API ?

How to view the android.jar source code in eclipse?



This plugin helps you to add source to android libraries in Eclipse.

In ADT >=8.0.0 you can add Android sources to Android container for all your project with installing the Android source feature using...

http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/

After downloading the com.android.ide.eclipse.source_16.0.0.201112171909.jar file in plugin folder, unzip it.We will get the below sources for the following API levels:

14 - Android 4.0.1
10 - Android 2.3.4
9 - Android 2.3
8 - Android 2.2
7 - Android 2.1
6 - Android 2.0.1
4 - Android 1.6
3 - Android 1.5

The plugin is about 240 MB size.

Each folder will contain the sources.zip file within it.Copy zip file from "10" folder and paste it into below path of corresponding version...

android-sdk-linux/platform/android-10/"paste here"

i.e sources.zip and android.jar both file will be in same folder.

Now restart you eclipse and browse to android.jar file,now you can view the source code....


How to restart service with AlarmManager ?

Supposed you are running the below service......We just need to register and unregister the alarm,in service lifecycle.



package com.example.differentlayout;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

class PersistentService extends Service {

private static final String TAG = "PersistentService";

// support persistent of Service
void registerRestartAlarm() {
Log.d(TAG, "registerRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 10 * 1000; // 10 seconds after the alarm event occurs
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,10 * 1000, sender);
}

void unregisterRestartAlarm() {
Log.d(TAG, "unregisterRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(sender);
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
unregisterRestartAlarm();
super.onCreate();
}

@Override
public void onDestroy() {
registerRestartAlarm();
super.onDestroy();
}

}



Write the receiver which wake ups our above service....


package com.example.differentlayout;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class RestartService extends BroadcastReceiver {
 public static final String ACTION_RESTART_PERSISTENTSERVICE = "ACTION.Restart.PersistentService";

@Override
 public void onReceive(Context context, Intent intent) {
   Log.d("RestartService", "RestartService called!@!@@@@@#$@$@#$@#$@#");
   if(intent.getAction().equals(ACTION_RESTART_PERSISTENTSERVICE)) {
     Intent i = new Intent(context, PersistentService.class);
     context.startService(i);
 }
}
}


In manifest file don't forgot to mention the RestartService as remote.....


<receiver android:name="RestartService" android:process=":remote">
       <intent-filter>
                       <action android:name="ACTION.Restart.PersistentService"></action>
        </intent-filter>
</receiver>


Commonly Utilized intents ?

Following are the list of intent call which is called mostly....


//Offset / Web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);

// Google Offset
Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = new Intent(Intent.Action_VIEW,uri);
startActivity(it);

// Google pathfinding offset
//http://maps.google.com/maps?f=d&saddr = source address & daddr = destination address & hl = en
Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=출발지주소&daddr=도착지주소&hl=ko");
Intent it = new Intent(Intent.ACTION_VIEW,URI);
startActivity(it);

// Dialing
Uri uri = Uri.parse("tel:xxxxxx");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);

Uri uri = Uri.parse("tel.xxxxxx");
Intent it = new Intent(Intent.ACTION_CALL,uri);
//  <uses-permission id="android.permission.CALL_PHONE" />

// SMS/MMS Sent
Intent it = new Intent(Intent.ACTION_VIEW);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);

// SMS Sent
Uri uri = Uri.parse("smsto:0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "The SMS text");
sms.putExtra("exit_on_sent", true);
startActivity(it);

// MMS Sent
Uri uri = Uri.parse("content://media/external/images/media/23");
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);

// Send an email
Uri uri = Uri.parse("mailto:xxx@abc.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it, "Choose Email Client"));

Intent it = new Intent(Intent.ACTION_SEND);
String[] tos = {"me@abc.com"};
String[] ccs = {"you@abc.com"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// extra Add
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// Play media files
Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/song.mp3");
it.setDataAndType(uri, "audio/mp3");
startActivity(it);

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

// Removing the installed application
Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);

// APK-To remove the file
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);

// APK Install files
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);

// Playing a music file
Uri playUri = Uri.parse("file:///sdcard/download/everything.mp3");
returnIt = new Intent(Intent.ACTION_VIEW, playUri);

//Add attachments to E-mail
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// Search application from the Market
Uri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
// The package name, you must enter the full package name of the application.

// Market Application Details screen
//market://details?id=application ID
Uri uri = Uri.parse("market://details?id=어플리케이션아이디");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
// ID of the publishing market if you look at the URL to the site of application after the selection.

// Google Search
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);

//Sending attachement through email Intent
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, "emailId");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.setType("text/*");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body Messgae"+ "\n\nPlease Find attached log File");
emailIntent.setType("text/*");
File path = new File("sdcard/filePath");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(path));
emailIntent.putExtra(Intent.EXTRA_TEXT,Html.fromHtml("\nStep Email Launch:"));
emailIntent.setType("text/*");
// emailIntent.setType("message/rfc822");
// emailIntent.setType("message/rfc822");
// emailIntent.setType("text/xml");
// emailIntent.setType("text/html");
// emailIntent.setType("text/plain");
emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(emailIntent);

How to manage Dynamic Height of SlidingDrawer in android ?

Create the custom layout into the main.xml....


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

    <ViewFlipper
        android:id="@+id/ImageFlipper"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ImageView
            android:id="@+id/imageView0"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />
    </ViewFlipper>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom"
        android:orientation="vertical" >

        <com.example.differentlayout.WrappingSlidingDrawer
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:content="@+id/content"
            android:handle="@+id/handle" >

            <!-- Sliding drawer handle -->

            <ImageView
                android:id="@+id/infoDrawerHandle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@+drawable/info_handle_closed" />

            <!--
        Sliding drawer content: a scroller containing a group of text views
        laid out in a LinearLayout
            -->

            <ScrollView
                android:id="@+id/infoDrawerContent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@+drawable/info_background"
                android:fillViewport="false" >

                <LinearLayout
                    android:id="@+id/infoDrawerContent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingRight="5dip" >

                    <TextView
                        android:id="@+id/infoTitle"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#ffffff"
                        android:textSize="16dip"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/infoCreator"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="10dip"
                        android:textColor="#ffffff"
                        android:textSize="14dip"
                        android:textStyle="italic" />

                    <TextView
                        android:id="@+id/infoDescription"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="10dip"
                        android:textColor="#ffffff"
                        android:textSize="14dip" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@+string/heading_pro_tip"
                        android:textColor="#ffcc00"
                        android:textSize="14dip"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/infoProTip"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#ffcc00"
                        android:textSize="14dip" />
                </LinearLayout>
            </ScrollView>
        </com.example.differentlayout.WrappingSlidingDrawer>
    </LinearLayout>

</FrameLayout>



Then create the class for WrappingSlidingDrawer.java......
It will manage the height of the drawer based on the number of elements binded in adapter........


package com.example.differentlayout;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SlidingDrawer;

public class WrappingSlidingDrawer extends SlidingDrawer {

    public WrappingSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
        mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
        mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
    }

    public WrappingSlidingDrawer(Context context, AttributeSet attrs) {
        super(context, attrs);

        int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
        mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
        mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize =  MeasureSpec.getSize(widthMeasureSpec);

        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize =  MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
            throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions");
        }

        final View handle = getHandle();
        final View content = getContent();
        measureChild(handle, widthMeasureSpec, heightMeasureSpec);

        if (mVertical) {
            int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset;
            content.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, heightSpecMode));
            heightSpecSize = handle.getMeasuredHeight() + mTopOffset + content.getMeasuredHeight();
            widthSpecSize = content.getMeasuredWidth();
            if (handle.getMeasuredWidth() > widthSpecSize) widthSpecSize = handle.getMeasuredWidth();
        }
        else {
            int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset;
            getContent().measure(MeasureSpec.makeMeasureSpec(width, widthSpecMode), heightMeasureSpec);
            widthSpecSize = handle.getMeasuredWidth() + mTopOffset + content.getMeasuredWidth();
            heightSpecSize = content.getMeasuredHeight();
            if (handle.getMeasuredHeight() > heightSpecSize) heightSpecSize = handle.getMeasuredHeight();
        }

        setMeasuredDimension(widthSpecSize, heightSpecSize);
    }

    private boolean mVertical;
    private int mTopOffset;
}

Saturday, September 1, 2012

Tower of Hanoi program in Java ?



The towers of hanoi is a popular problem. You have three poles and n disks which fit on the poles. All disks have different size. They are stacked on pole 1 in the orders of their size. The largest disk is on the bottom, the smallest is on the top.

The task is to move all disk from pole 1 to pole 3 under the following restrictions.

Only one disk can be moved

A larger disk can not be placed on a smaller disk.

The recursive algorithm works like the following: move n-1 disk from the starting pole to the pole which is neither start nor target (intermediate), move disk n to the target pole and then move n-1 disk from the intermediate pole to the target pole. The n-1 disks are moved recursively.


public class MinimumWindow {

public static void move(int n, int startPole, int endPole) {
if (n == 0) {
return;
}
int intermediatePole = 6 - startPole - endPole;
move(n - 1, startPole, intermediatePole);
System.out.println("Move " + n + " from " + startPole + " to "
+ endPole);
move(n - 1, intermediatePole, endPole);
}

public static void main(String[] args) {
move(5, 1, 3);
}

}


Below is the output...

Move 1 from 1 to 3
Move 2 from 1 to 2
Move 1 from 3 to 2
Move 3 from 1 to 3
Move 1 from 2 to 1
Move 2 from 2 to 3
Move 1 from 1 to 3

Prime Factorization in Java ?


import java.util.ArrayList;
import java.util.List;

public class PrimeFactorization {

public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}

public static void main(String[] args) {
for (Integer integer : primeFactors(44)) {
System.out.println(integer);
}

System.out.println("---------");

for (Integer integer : primeFactors(3)) {
System.out.println(integer);
}
}

}

Below is the Output....

2
2
11
---------
3

Determine Prime number with the sieve of Eratosthenes in Java in java ?


import java.util.ArrayList;
import java.util.List;

public class DeterminePrime{

public static List<Integer> calcPrimeNumbers(int n) {
boolean[] isPrimeNumber = new boolean[n + 1]; // boolean defaults to
// false
List<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i < n; i++) {
isPrimeNumber[i] = true;
}
for (int i = 2; i < n; i++) {
if (isPrimeNumber[i]) {
primes.add(i);
// Now mark the multiple of i as non-prime number
for (int j = i; j * i <= n; j++) {
isPrimeNumber[i * j] = false;
}
}

}

return primes;
}

public static void main(String[] args) {
List<Integer> calcPrimeNumbers = calcPrimeNumbers(21);
for (Integer integer : calcPrimeNumbers) {
System.out.println(integer);
}
System.out.println("Prime counting function (Pie(N)) : "
+ calcPrimeNumbers.size());
}

}


Below is the output...

2
3
5
7
11
13
17
19
Prime counting function (Pie(N)) : 8

Euclid's Greatest Common divisor alogorithmn ?


public class EuclidGCdAlgorithmn {

public static int gcd(int p, int q) {

if (q == 0) {
return p;
}

return gcd(q, p % q);
}

// Test enable assert check via -ea as a VM argument

public static void main(String[] args) {
System.out.print(" "+gcd(4, 16));

System.out.print(" "+gcd(16, 4));

System.out.print(" "+gcd(15, 60));
System.out.print(" "+gcd(15, 65));

System.out.print(" "+gcd(1052, 52));
}

}


Below is the output....

 4
 4
 15
 5
 4

Odd even Transposition algorithmn in Java ?



public class OddEvenTransposition {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10, 13 };

System.out.println(" Odd Even Transposition Sort\n\n");

System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

System.out.println();

odd_even_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

}

public static void odd_even_srt(int array[], int n) {
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j + 1 < n; j += 2)
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
for (int j = 1; j + 1 < array.length; j += 2)
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
}
}


Below is the output....

Values Before the sort:

12  9  4  99  120  1  3  10  13  

Values after the sort:

1  3  4  9  10  12  13  99  120  

Merge sort algorithmn in Java?


public class MergeSort {

public static void main(String a[]) {
int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}

System.out.println();

mergeSort_srt(array, 0, array.length - 1);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}

}

public static void mergeSort_srt(int array[], int lo, int n) {
int low = lo;
int high = n;
if (low >= high) {
return;
}

int middle = (low + high) / 2;
mergeSort_srt(array, low, middle);
mergeSort_srt(array, middle + 1, high);
int end_low = middle;
int start_high = middle + 1;
while ((lo <= end_low) && (start_high <= high)) {
if (array[low] < array[start_high]) {
low++;
} else {
int Temp = array[start_high];
for (int k = start_high - 1; k >= low; k--) {
array[k + 1] = array[k];
}
array[low] = Temp;
low++;
end_low++;
start_high++;
}
}
}
}


Below is the output...

Values Before the sort:

12  9  4  99  120  1  3  10

Values after the sort:

1  3  4  9  10  12  99  120

Friday, August 31, 2012

Insertion Sort Algorithmn in Java ?


public class InsertionSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}

System.out.println();

insertion_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}
}

public static void insertion_srt(int array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
int B = array[i];
while ((j > 0) && (array[j - 1] > B)) {
array[j] = array[j - 1];
j--;
}
array[j] = B;
}
}
}


Below is the output..

Values Before the sort:

12  9  4  99  120  1  3  10

Values after the sort:

1  3  4  9  10  12  99  120

Heap Sort algorithmn in Java ?


public class HeapSort {

public static void main(String a[]) {

int i;
int arr[] = { 1, 3, 4, 5, 2 };

for (i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}

for (i = arr.length; i > 1; i--) {
fnSortHeap(arr, i - 1);
}

System.out.println("\n  Sorted array\n---------------\n");

for (i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]);
}

}

public static void fnSortHeap(int array[], int arr_ubound) {
int i, o;
int lChild, rChild, mChild, root, temp;
root = (arr_ubound - 1) / 2;

for (o = root; o >= 0; o--) {
for (i = root; i >= 0; i--) {
lChild = (2 * i) + 1;
rChild = (2 * i) + 2;
if ((lChild <= arr_ubound) && (rChild <= arr_ubound)) {
if (array[rChild] >= array[lChild])
mChild = rChild;
else
mChild = lChild;
} else {
if (rChild > arr_ubound)
mChild = lChild;
else
mChild = rChild;
}

if (array[i] < array[mChild]) {
temp = array[i];
array[i] = array[mChild];
array[mChild] = temp;
}
}
}
temp = array[0];
array[0] = array[arr_ubound];
array[arr_ubound] = temp;
return;
}
}


Below is the output....

 1 3 4 5 2

Sorted array
---------------

 1 2 3 4 5

Bi-directional bubble sort Algorithmn in java ?


public class BidirectionalBubbleSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

System.out.println();

bidirectionalBubble_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

}

public static void bidirectionalBubble_srt(int array[], int n) {
int j;
int st = -1;
while (st < n) {
st++;
n--;
for (j = st; j < n; j++) {
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
for (j = n; --j >= st;) {
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
}
}
}


Values Before the sort:

12  9  4  99  120  1  3  10

Values after the sort:

1  3  4  9  10  12  99  120

BubbleSort Algorithmn in Java ?



public class BubbleSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}
System.out.println();

bubble_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++) {
System.out.print(array[i] + "  ");
}
}

public static void bubble_srt(int a[], int n) {
int i, j, t = 0;
for (i = 0; i < n; i++) {
for (j = 1; j < (n - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
}

Below is the output.....

Values Before the sort:

12  9  4  99  120  1  3  10  

Values after the sort:

1  3  4  9  10  12  99  120  

Generate array of random numbers with quickSort in Java?



import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class QuickSort {
/**
* Main method.
* @param args
*/
public static void main(String[] args) {

QuickSort app = new QuickSort();

//Generate an integer array of length 7
   List<Integer> input = app.generateRandomNumbers(7);

   //Before sort
   System.out.println(input);

   //After sort
   System.out.println(app.quicksort(input));

}

/**
* This method sort the input ArrayList using quick sort algorithm.
* @param input the ArrayList of integers.
* @return sorted ArrayList of integers.
*/
private List<Integer> quicksort(List<Integer> input){

if(input.size() <= 1){
return input;
}

int middle = (int) Math.ceil((double)input.size() / 2);
int pivot = input.get(middle);

List<Integer> less = new ArrayList<Integer>();
List<Integer> greater = new ArrayList<Integer>();

for (int i = 0; i < input.size(); i++) {
if(input.get(i) <= pivot){
if(i == middle){
continue;
}
less.add(input.get(i));
}
else{
greater.add(input.get(i));
}
}

return concatenate(quicksort(less), pivot, quicksort(greater));
}

/**
* Join the less array, pivot integer, and greater array
* to single array.
* @param less integer ArrayList with values less than pivot.
* @param pivot the pivot integer.
* @param greater integer ArrayList with values greater than pivot.
* @return the integer ArrayList after join.
*/
private List<Integer> concatenate(List<Integer> less, int pivot, List<Integer> greater){

List<Integer> list = new ArrayList<Integer>();

for (int i = 0; i < less.size(); i++) {
list.add(less.get(i));
}

list.add(pivot);

for (int i = 0; i < greater.size(); i++) {
list.add(greater.get(i));
}

return list;
}

/**
* This method generate a ArrayList with length n containing random integers .
* @param n the length of the ArrayList to generate.
* @return ArrayList of random integers with length n.
*/
private List<Integer> generateRandomNumbers(int n){

   List<Integer> list = new ArrayList<Integer>(n);
   Random random = new Random();

   for (int i = 0; i < n; i++) {
   list.add(random.nextInt(n * 10));
   }

   return list;
}
}

Below is the output....


[25, 58, 65, 19, 59, 8, 39]
[8, 19, 25, 39, 58, 59, 65]


QuickSort algorithm Java?



public class QuickSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10, 13 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}


quick_srt(array, 0, array.length - 1);
System.out.println("");
System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}
}

public static void quick_srt(int array[], int low, int n) {
int lo = low;
int hi = n;
if (lo >= n) {
return;
}
int mid = array[(lo + hi) / 2];
while (lo < hi) {
while (lo < hi && array[lo] < mid) {
lo++;
}
while (lo < hi && array[hi] > mid) {
hi--;
}
if (lo < hi) {
int T = array[lo];
array[lo] = array[hi];
array[hi] = T;
}
}
if (hi < lo) {
int T = hi;
hi = lo;
lo = T;
}
quick_srt(array, low, lo);
quick_srt(array, lo == low ? lo + 1 : lo, n);
}
}

Below is the output.....


Values Before the sort:

12  9  4  99  120  1  3  10  13

Values after the sort:

1  3  4  9  10  12  13  99  120


Dijkstra's (Shortest path) algorithm in Java?

Below is the example to find out the shortest path between edges......


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;

public class Dijkstra {
public static void computePaths(Vertex source) {
source.minDistance = 0.;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);

while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();

// Visit each edge exiting u
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double weight = e.weight;
double distanceThroughU = u.minDistance + weight;
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v);
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v);
}
}
}
}

public static List<Vertex> getShortestPathTo(Vertex target) {
List<Vertex> path = new ArrayList<Vertex>();
for (Vertex vertex = target; vertex != null; vertex = vertex.previous)
path.add(vertex);
Collections.reverse(path);
return path;
}

public static void main(String[] args) {
MinimumWindow a = new MinimumWindow();

Vertex v0 = a.new Vertex("Redvile");
Vertex v1 = a.new Vertex("Blueville");
Vertex v2 = a.new Vertex("Greenville");
Vertex v3 = a.new Vertex("Orangeville");
Vertex v4 = a.new Vertex("Purpleville");

v0.adjacencies = new Edge[] { a.new Edge(v1, 5), a.new Edge(v2, 10),a.new Edge(v3, 8) };
v1.adjacencies = new Edge[] { a.new Edge(v0, 5), a.new Edge(v2, 3),a.new Edge(v4, 7) };
v2.adjacencies = new Edge[] { a.new Edge(v0, 10), a.new Edge(v1, 3) };
v3.adjacencies = new Edge[] { a.new Edge(v0, 8), a.new Edge(v4, 2) };
v4.adjacencies = new Edge[] { a.new Edge(v1, 7), a.new Edge(v3, 2) };
Vertex[] vertices = { v0, v1, v2, v3, v4 };

computePaths(v0);

for (Vertex v : vertices) {
System.out.println("Distance to " + v + ": " + v.minDistance);
List<Vertex> path = getShortestPathTo(v);
System.out.println("Path: " + path);
}
}

public class Vertex implements Comparable<Vertex> {

public final String name;
public Edge[] adjacencies;
public double minDistance = Double.POSITIVE_INFINITY;
public Vertex previous;

public Vertex(String argName) {
name = argName;
}

public String toString() {
return name;
}

public int compareTo(Vertex other) {
return Double.compare(minDistance, other.minDistance);
}
}

class Edge {
public final Vertex target;
public final double weight;

public Edge(Vertex argTarget, double argWeight) {
target = argTarget;
weight = argWeight;
}
}
}



Below is the output...


Distance to Redvile: 0.0
Path: [Redvile]
Distance to Blueville: 5.0
Path: [Redvile, Blueville]
Distance to Greenville: 8.0
Path: [Redvile, Blueville, Greenville]
Distance to Orangeville: 8.0
Path: [Redvile, Orangeville]
Distance to Purpleville: 10.0
Path: [Redvile, Orangeville, Purpleville]