Coding Stories

Just a simple stories about coding

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.

Development Workflow: usual steps


……

Do you have established dev’s process ? How do you use it ? Do you like it ? What is the benefit from it ? And others

These questions are usual in programmers’ area (at least for me), so I decided to write short note about process and how it established in company where I am working.

Short and simple Rules:

Firstly – all have to use it, if some one decided to stop it will work rule of broken window.
Secondly – each team’s player has to understand all aspects of process, if something not clear will work first rule.
Thirdly – all points and rules have to be short, simple and understandable, because there is high probability that will work first two points described above.

Before start development you should set up some Source Control System, for me is better to use DVCS but you can choose what is the better for you.

So, My usual workflow of new feature:

  • Start new branch with name that clear describing new feature
  • Create some high level interfaces (API)
  • Create tests
  • Implement logic, if I need I can change API and test on this stage
  • Submit code to review tool.
  • Create event for review and assign as minimum to 2 diff developers (if developers from diff teams will be great)
  • Wait review, and fix review issues.
  • After receiving acceptance from reviewers, Run all tests, unit integration, high load and so on, wait for result.
  • If tests passed I can submit code to repository and merge to master branch, if no, process will start from writing code and will go through most steps.

Yes, has to be some “Code Conventions” for project and this convention should be described in project documents, even if you are using general CC.

Yes, has to be installed all infrastructure, with servers for code repository, review tool, testing, checking, issue tracking and desirable all these tools can be integrated to each other and as result to your IDE.

And Yes, you will spend more time than “just for development”, but as result, code will be as production of a few developers not just your thinking and bugs :) and more readable and clear for the next developers and changes.

Linux Bash get IP address


Today I’ve tried to prepare auto configuration of my application and one of the main point was create correct cluster with real IP addresses . For example you have some config files where you want to put real IP of installed machine. In real Linux world it should be configured manually after installation but I want to emulate auto configuration, so, I’ve prepared bash script for auto config all parameters for my app, but one point was interesting and I’ve decided to describe it in a few words.

So, How to get real IP address ? Each of us know that there are ifconfig util and we can get all information about interfaces and addresses, I’ve used this for prepared short script to get real IP v4 address

ifconfig eth0  $1 | grep “inet addr” | awk -F: ‘{print $2}’ | awk ‘{print $1}’

Use it in your scripts if you want to do tasks as I had.

Thanks.

How to install Yakuake on Cenros 6.3


I’ve started to use Centos server and tried to find good terminal emulator. Previously I’ve used guake for Ubuntu and some port of this emulator for Mac OS X. I’ve started to find repository of yakuake and found that there are no :( , So, I’ve prepared short instruction how to compile Yakuake for Centos 6.3.

Firstly you have to install kde dependencies, run your gnome terminal and execute next commands:

  1. su - go to root rights
  2. yum install gcc gcc-c++ make cmake kdebase kdelibs-devel

After this download Yakuake sources from this link, I use Yakuake 2.9.8 (KDE 4; Stable). Go to terminal and execute next commands

  1. cd  to download folder
  2. tar xaf yakuake-2.9.8.tar.bz2
  3. cd yakuake-2.9.8
  4. mkdir build
  5. cd build
  6. cmake -DCMAKE_INSTALL_PREFIX=$HOME/bin/yakuake/ ../
  7. make
  8. make install

And not mandatory step, but I did it, set yakuake to start automatically: System -> Preferences -> Startup Applications

And That’s all.

Cheers! :)

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!

30 years


Yep, this day is arrived, yesterday I looked to my stackoverflow’s profile and was 29 years, today morning 30, I’ve moved to next step :)  to the next decade of my life :)

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!

Follow

Get every new post delivered to your Inbox.