Coding Stories

Just a simple stories about coding

Category: Java

Reverse LinkedList {Recursion implementation}


Recently I’ve read IT topic about interview questions and was surprised, Programmers discussed about “hard” interview question “Reversing of Linked List”. Judging to that topic the task was hard for most candidates and I decided to write short note about Reversing Linked List.

  • Firstly this task was for Singly Linked List;
  • Secondly time for creating algorithm was about 5 mins;

So, I’ve used Java for realization but you can write the same code using C,C++ and other languages.

Ok, Lets go…

I’ve created new structure for Singly linked list :

package com.codingstories.list;

/**
 * @author szagriichuk
 */
public class Node {
    private int value;
    private Node next;

    public Node(int value) {
        this.value = value;
    }

    public static Node createLinkedListFromArray(int... data) {
        Node root = null;
        if (data != null && data.length > 0) {
            Node node = new Node(data[0]);
            root = node;
            for (int i = 1; i < data.length; i++) {
                node.setNext(new Node(data[i]));
                node = node.getNext();
            }
        }
        return root;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public int getValue() {
        return value;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        Node root = this;
        while (root != null) {
            stringBuilder.append(root.getValue()).append(",");
            root = root.getNext();
        }
        return stringBuilder.toString();
    }
}

Also, I’ve decided to create a few implementations and this structure will be used for all of them.

I’ve extracted common interface called Reverser with simple API for algorithm implementations:

package com.codingstories.list.reverse;

import com.codingstories.list.Node;

/**
 * @author szagriichuk
 */
public interface Reverser {
    Node reverse (Node node);
}

After it, I’ve started to create first implementation.

So, First implementation is Recursion.

Steps of algorithm:

Go through all nodes and reverse them :)
Ok, seriously

  • Check if input Node is not null, if null return it {first rule to stop recursion}
  • Check if next Node is not null, if null return input node {second rule to stop recursion}
  • Get and save next Node
  • Set null as next value for input node
  • Call recursion method with next node and save result to reversed Node root
  • Set input Node as next to next Node :)
  • Return reversed Node root

Code:

package com.codingstories.list.reverse;

import com.codingstories.list.Node;

/**
 * @author szagriichuk
 */
public class RecursionReverser implements Reverser {
    @Override
    public Node reverse(Node node) {
        if( node == null)
            return node;
        Node next = node.getNext();
        if(next == null)
            return node;
        node.setNext(null);
        Node reverseList = reverse(next);
        next.setNext(node);
        return reverseList;
    }
}

Pros:

  • Simple to implement
  • You can see all process of reversing
  • You can understand recursion :)

Cons:

  • Usage of Stack Memory
  • As result can be thrown StackOverflowError

It’s first implementation of reverse functionality for LinkedList, I am going to add a few other ways of implementation in next posts.

Thanks.

Amazing story about crashing JVM


Hi All,

A few days ago I’ve investigated API of one over price external library. One note this library is native, written using C++ and provides ports to other language in particular for Java using JNI.

So, I’ve started to run provided example all is OK, and I’ve decided to use this application to write my API using OSGI and Spring. Native example implements 5 interfaces and provides a lot of methods that I do not need to implement and I’ve used just a 3. Implemented methods of these interfaces and try to run tests, so, I was very surprised JVM was crashed!

I’ve started to investigate this problem, check all implementation of methods, all input parameters to the external library, tests but did not find any problems that can crache JVM. After it I’ve downloaded decompiler for java and C++ codes and start to investigate external library. And what was my astonishment when I found that JVM will be crashed if class (MY CLASS)/MY API does not implement one of the interface from external library(I did’t do it).

It is a hard story about API architecture and in what places JVM can be crashed …

Thanks.

Maven: Set up java.library.path


I’ve tried to set up java.library.path as next example

     <plugin>
       <groupId>org.apache.maven.plugins</groupId>
       <artifactId>maven-surefire-plugin</artifactId>
       <configuration>
          <systemProperties>
            <property>
              <name>java.library.path</name>
              <value>target/lib/</value>
           </property>
       </systemProperties>
    </configuration>
</plugin>

but there were problems in testing, one test with JNI was passed but others were failed. I’ve spent about 4 hours for investigation and found that in last part of documentation there are special properties, so I’ve tried it and it is working!!!

Simple example of working plugin configuration

<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
         <forkMode>once</forkMode>
         <workingDirectory>target</workingDirectory>
        <argLine>-Djava.library.path=${basedir}/lib</argLine>
    </configuration>
</plugin>

Cheers!

Algorithms: Customization binary search


I had some interviews into big companies like Google, Amazon and so on, and there were tasks related to the algorithms. So, Here I’ll describe one of the tasks and publish code for this algorithm. Note, during interview you can chose algorithm by your self and time for implementation (runtime implementation) about 30 mins. So,

Predefined: There is dictionary of words with unspecified size, we just know that all words in dictionary are sorted (for example by alphabet). Also we have just a one method

String getWord(int index) throws IndexOutOfBoundsException

Needs: Need to develop algorithm to find some input word in dictionary using java. For this we should implement method

public boolean isWordInTheDictionary(String word)

Limitations: We cannot change the internal structure of dictionary, we have no access to internal structure, we do not know counts of elements in dictionary.

Issues: I have developed modified-binary search, But you can try to implement interpolation search or modification interpolation + binary :)  .

So, my code :

/** * @author Sergii Zagriichuk */

public class Dictionary {
    private static final int BIGGEST_TOP_MASK = 0xF00000;
    private static final int LESS_TOP_MASK = 0x0F0000;
    private static final int FULL_MASK = 0xFFFFFF;
    private String[] data;
    private static final int STEP = 100; // for real test step should be Integer.MAX_VALUE
    private int shiftIndex = -1;
    private static final int LESS_MASK = 0x0000FF;
    private static final int BIG_MASK = 0x00FF00;

    public Dictionary() {
        data = getData();
    }

    String getWord(int index) throws IndexOutOfBoundsException {
        return data[index];
    }

    public String[] getData() {
        return new String[]{"a", "aaaa", "asss", "az", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "test", "u", "v", "w", "x", "y", "z"};
    }

    public boolean isWordInTheDictionary(String word) {
        boolean isFound = false;
        int constantIndex = STEP; // predefined step
        int flag = 0;
        int i = 0;
        while (true) {
            i++;
            if (flag == FULL_MASK) {
                System.out.println("Word is not found ... Steps " + i);
                break;
            }
            try {
                String data = getWord(constantIndex);
                if (null != data) {
                    int compareResult = word.compareTo(data);
                    if (compareResult > 0) {
                        if ((flag & LESS_MASK) == LESS_MASK) {
                            constantIndex = prepareIndex(false, constantIndex);
                            if (shiftIndex == 1)
                                flag |= BIGGEST_TOP_MASK;
                        } else {
                            constantIndex = constantIndex * 2;
                        }
                        flag |= BIG_MASK;

                    } else if (compareResult < 0) {
                        if ((flag & BIG_MASK) == BIG_MASK) {
                            constantIndex = prepareIndex(true, constantIndex);
                            if (shiftIndex == 1)
                                flag |= LESS_TOP_MASK;
                        } else {
                            constantIndex = constantIndex / 2;
                        }
                        flag |= LESS_MASK;
                    } else {
                       // YES!!! We found word.
                        isFound = true;
                        System.out.println("Steps " + i);
                        break;
                    }
                }
            } catch (IndexOutOfBoundsException e) {
                if (flag > 0) {
                    constantIndex = prepareIndex(true, constantIndex);
                    flag |= LESS_MASK;
                } else constantIndex = constantIndex / 2;
            }
        }
        return isFound;
    }

    private int prepareIndex(boolean isBiggest, int constantIndex) {
        shiftIndex = (int) Math.ceil(getIndex(shiftIndex == -1 ? constantIndex : shiftIndex));
        if (isBiggest)
            constantIndex = constantIndex - shiftIndex;
        else
            constantIndex = constantIndex + shiftIndex;
        return constantIndex;
    }

    private double getIndex(double constantIndex) {
        if (constantIndex <= 1)
            return 1;
        return constantIndex / 2;
    }
}

I hope this post will help some one to pass interview into bigest companies :)

Cheers!

PlayFramework: Run and Debug Using IDE


Introduction

I think each of us looking for the best IDE and best way of development. I think the best code editor is IntellJ IDEA and I am using it for 6 years. A few month ago I’ve started to use PlayFramework and were surprized that there is no way to debug application using IDE just browser and console logs and messages. After short investigation I’ve found solution …

Solution

This step-by-step solution for IntellJ IDEA but I think you can use it for other IDEs.

Step1
Go to  Run/Debug Configurations and add Application configuration

Step 2
Put  main class

play.server.Server

Step 3
Add VM Options

-Dapplication.path=<Path to your application>

-Djavaagent=<Path to play framework>/play-1.2.3.jar

And that is all…

Cheers!!!

Android: Formatting Strings


Introduction
If you are java developer you can use String.format for adding some parameters into your string. Core Java provides us mechanism to manage it using symbols like %s or {1}, but how to use this mechanism in Android resource strings?

Resource Strings
Android provides us good mechanism to format strings in application too. Just try to add %1$s  or %1$d into your resource strings. The last symbols mean

  • s –  for string formatting
  • d – for decimal formatting

So, simple example:

<string name=“my_name”>My name is %1$s.</string>
<string name=“my_age”>I am %1$d years old.</string>

Here is we can see two types of using, the first is string formatting the second is number. In java code you have to add just simple String.format like in Core Java.

Resources res = getResources();
String myNameString = String.format(res.getString(R.string.my_name)“Tom”);
String myAgeString = String.format(res.getString(R.string.my_age)25);

And that is all …

P.S. If you want to use more parameters in string just increase a number  %1$d ,%2$d ,%3$d

Cheers!

Android: Localization


Introduction
The next step in development Android application will be localization. I’ve read documentation from official site and from 
http://www.icanlocalize.com/
 and decided to describe it.

Sequence of resources lookup
How does android lookup the resources from applications?
The example of lookup steps below:

  1. ‘res/values-en-rUS/strings.xml’
  2. ‘res/values-en/strings.xml’
  3. ‘res/values/strings.xml’

Firsltly Android looks for resources in en-rUS folder if not found, looks in -en folder and just after it in default. If resource has been found then  the search stops.

Dismantle folders structure
The next question that worried me : What does it mean -rUS why is not just en?
The answer is, There are countries with two or more official languages for example Switzerland but there is no Swiss language just French or/and German. The fisrt -<symbol>- (in our example -en-) means language-r means region and after -r name of region. For instance for French language in Switzerland will be
       res/values-fr-rCH
This rules works for other resources like pictures and so on.

Conclusion
If you want to localize your application just:

  • create folders for all localized resources using above convention
  • put localized files into folders
  • start your application

P.S. And yes you must not to use strings in code just from resource files.

And that is all …

Cheers!

Android: Amazing story about sending SMS messages from the code.


Hi,
I’ve found amazing case of sending sms messages from the code.

Task
I need to send SMS message from my test method and test behavior of parsing it. Just for this post we are interesting in first part: Sending SMS message from code.
I’ve written next simple code:

final SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(“5554″null“Test”nullnull);

and tried to test it. Just put this code in simple test method and run Android Unit Test. The result is … nothing!!! Why?!! I did not understand …

Solution
After hours of investigation and reading documentation and blogs I decided to try the same manipulation, BUT, just on two emulators. I have started two emulators on 5554 and 5556 and tried start test project on 5554 but send message to 5556. Simple changes in code below:

final SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(“5556″null“Test”nullnull);

And … and … I was surprised, I can see message “Test” on 5556 emulator and it is perfectly!
Cheers!

Android:Unit Test issues


Hi,
I’ve created project for testing my Android Application and tried to start it.
After starting I have received next error:

Test run failed: Unable to find instrumentation info for:
ComponentInfo {<my package>/android.test.InstrumentationTestRunner}

After few hours of investigation I have found solution for this situation.

Problem
So, Problem is name of package in the manifest files.  The package in “real” manifest file and test manifest file are equal. For instance, look at the package com.blogspot.jugvn in both manifests

Test manifest:

<?xml version=“1.0″ encoding=“utf-8″?>
<manifest  xmlns:android=http://schemas.android.com/apk/res/android&#8221;
 package=“com.blogspot.jugvn”  android:versionCode=“1″ android:versionName=“1.0″>
<uses-sdk android:minSdkVersion=“7″/>
<instrumentation android:targetPackage=“com.blogspot.jugvn”  android:name=“android.test.InstrumentationTestRunner” />
<application android:icon=“@drawable/icon” android:label=“@string/app_name”>
<uses-library android:name=“android.test.runner” />
</application>
<!–  Add permissions for send sms messages–>
<uses-permission android:name=“android.permission.SEND_SMS” />
<uses-permission android:name=“android.permission.WRITE_SMS”/>
</manifest>

Project manifest:

<?xml version=“1.0″ encoding=“utf-8″?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android&#8221;
 package=“com.blogspot.jugvn” android:versionCode=“1″ android:versionName=“1.0″>
<application android:label=“@string/app_name” android:icon=“@drawable/visa” android:debuggable=“true”>
<activity android:name=“.AccountList” android:label=“@string/app_name”>
<intent-filter>
<action android:name=“android.intent.action.MAIN” />
<category android:name=“android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion=“7″ android:targetSdkVersion=“7″ />
<!– Allows an application to read SMS messages. –>
<uses-permission android:name=“android.permission.READ_SMS”/>
</manifest>

Solution
Change package in test project to something else, I have used next convention: put test instead of first part of package like this :

test.blogspot.jugvn 

And result manifest file should be like this

<manifest xmlns:android=http://schemas.android.com/apk/res/android&#8221;
 package=“test.blogspot.jugvn ” android:versionCode=“1″ android:versionName=“1.0″>
<uses-sdk android:minSdkVersion=“7″/>
<instrumentation android:targetPackage=“test.blogspot.jugvn ” android:name=“android.test.InstrumentationTestRunner” />
<application android:icon=“@drawable/icon” android:label=“@string/app_name”>
<uses-library android:name=“android.test.runner”/>
</application>
<!– Add permissions for send sms messages–>
<uses-permission android:name=“android.permission.SEND_SMS”/>
<uses-permission android:name=“android.permission.WRITE_SMS” />
</manifest>

That is all manipulation for fixing this problem.

Cheers!

Follow

Get every new post delivered to your Inbox.