Back to Square 1 – IEEEXtreme 8.0

The game “Back to Square 1” is played on a board that has n squares in a row and n-1 probabilities. Players take turns playing. On their first turn, a player advances to square 1.After the first turn, if a player is on square i , the player advances to square i + 1 with probability p(i) , and returns to square 1 with probability 1-p(i) .The player is finished upon reaching square n .

Task


Write a program that determines the expected number of turns needed for a player to reach the final square.For example, consider the board below with n = 3 and p(1) = 0.5 and p(2) = 0.25. A player moves to square 1 on their first turn. With probability p(1) , they move to square 2 on their second turn, but with probability 1- p(1) , they remain on square 1. If they were lucky and made it to square 2 on their second turn, they advance to square 3 on their third turn with probability p(2) , but they would go back to square 1 with probability 1- p(2) . Thus, a really lucky player could finish is 3 turns. However, on average, it would take 13 turns for a player to make it to square 3.

IMAGE 1

Continue reading “Back to Square 1 – IEEEXtreme 8.0”

Configuring Network for Solaris 11 in Virtual Box

Hi all, recently I tried Solaris for some tasks at work. Installing Solaris on VirtualBox was not so difficult and there were quite a few resources in the internet. I used the following. http://thegeekdiary.com/installing-oracle-solaris-11-in-virtualbox/

However for configuring the network it was not the same. So here I will note down a few things which I believe might be useful when configuring network for Solaris 11 in Virtual Box.

In Solaris 11 configuring network is not editing few files, unlike in most other operating systems. There are a set of commands we can to create those configurations for us.

We will go through configuring NAT, HostOnly and Bridged Adaptors. First we have to go to Setting for the Solaris VM in VirtualBox and from there to the Network Tab.
Even though eventually we will add three network adaptors, I suggest we start by enabling only one adaptor as it might be hard to figure out which is which inside Solaris one we enable several network adaptors at once and try to configure them inside Solaris.

Continue reading “Configuring Network for Solaris 11 in Virtual Box”

Implementing an Embedded ElasticSearch Server

Hi all, recently I added an embedded ElasticSearch server for the upcoming release of  AdroitLogic UltraESB. Embedded ES Server will be useful when a large ES cluster is not required and also for ES integration tests. Let’s have a look at the code.

import org.adroitlogic.logging.api.Logger;
import org.adroitlogic.logging.api.LoggerFactory;
import org.adroitlogic.ultraesb.api.monitoring.StatisticsServer;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;

import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

/**
 * @author rajind
 * Implementation of embedded elasticsearch server.
 *
 */

public class ElasticSearchStatisticsServer implements StatisticsServer {

    private Node node;
    private static final Logger logger= LoggerFactory.getLogger(ElasticSearchStatisticsServer.class);

    private static final String ES_PROPERTY_PATH_HOME = "path.home";
    private static final String ES_PROPERTY_PATH_CONF = "path.conf";

    /**
     * Create an elasticsearch embedded node with provided default configuration.
     */
    @SuppressWarnings("UnusedDeclaration")
    public ElasticSearchStatisticsServer() {
    }

    @Override
    public void init(String confDir, String homeDir) {
        try {
            logger.info("Embedded Elasticsearch server is initializing");
            Settings elasticsearchSetting = Settings.settingsBuilder()
                    .put(ES_PROPERTY_PATH_HOME, homeDir)
                    .put(ES_PROPERTY_PATH_CONF, confDir)
                    .build();
            node = nodeBuilder().settings(elasticsearchSetting).build().start();
        } catch (Exception e) {
            logger.warn("Could not init embedded elasticsearch node", e);
        }
    }

    public Client getClient() {
        if (node != null) {
            return node.client();
        } else {
            return null;
        }
    }

    @Override
    public void destroy() {
        try {
            logger.info("Stopping embedded elasticsearch server");
            node.close();
        } catch(Exception e) {
            logger.warn("Could not stop embedded elasticsearch node due to {}", e.getMessage());
        }
    }
}

It’s actually very simple. “path.conf” will contain the elasticsearch configuration yaml file “elasticsearch.yml“. Please remember that “path.home” will always have to be set as elasticsearch looks for that by default.

Cheers! 🙂

~Rajind Ruparathna

IntelliJ IDEA Find & Replace using Regex

Recently I had to convert some documents which was on HTML format to Asciidoc format. An awesome tool called Pandoc saved me a lot of work. So after using that tool I was left to do a bit of final touches which included a lot of find and replace kind of work. I had actually set this up as a maven project with AsciiDoctor in IntelliJ IDEA so that is where I got to use this cool feature, find and replace with regex.

Here I’ll show a few examples as some of those are not that well documented.

Say  this here, “image:/download/attachments/983129/address-state-chart.png?version=3&modificationDate=1318249062000&api=v2[image,title=”sometitle”]”
is the string that I want to manipulate.

Continue reading “IntelliJ IDEA Find & Replace using Regex”

Shell Script to Continuously Monitor CPU Usage and Memory Usage of a Process and write output to CSV file

Hi all, recently I had to do some performance tests at work at AdroitLogic and I wanted to monitor CPU usage and memory usage of a process continuously and get that output to a file so that I can use them to analyze more later with graphs and stuff.

So I came up with two shell scripts which use Linux top and free commands to undertake this task for me.

In these scripts I run the top command in a loop and use grep command to only filter out the rest and get the line I need and then do some text processing using cut and tr. After that result of appended to a file using tee command. Here I am monitoring influxd, a time series database process. You can monitor any process you require by simply replacing the relevant name here “grep -w influxd”. Note that the filter string you use should properly filter out others and only leave a single line.

Hope these will be useful. Cheers!

#!/bin/bash
PRG="$0"
PRGDIR=`dirname "$PRG"`
[ -z "$LT_HOME" ] && LT_HOME=`cd "$PRGDIR/.." ; pwd`
cd $LT_HOME

rm -rf data/cpu*
> data/cpu.csv
echo "writing to cpu.csv"
echo "TIME_STAMP, Usage%" | tee -a data/cpu.csv
while :
do
DATE=`date +"%H:%M:%S:%s%:z"`
echo -n "$DATE, " | tee -a data/cpu.csv
top -b -n 1| grep -w influxd | tr -s ' ' | cut -d ' ' -f 10 | tee -a data/cpu.csv
sleep 1
done
#!/bin/bash
#run with sudo because python script requires sudo permission
PRG="$0"
PRGDIR=`dirname "$PRG"`
[ -z "$LT_HOME" ] && LT_HOME=`cd "$PRGDIR/.." ; pwd`
cd $LT_HOME

rm -rf data/mem*
> data/mem.csv
echo "writing to mem.csv"
echo "TIME_STAMP,Memory Usage (MB)" | tee -a data/mem.csv
total="$(free -m | grep Mem | tr -s ' ' | cut -d ' ' -f 2)"
#echo $total

while :
do
DATE=`date +"%H:%M:%S:%s%:z"`
echo -n "$DATE, " | tee -a data/mem.csv
var="$(top -b -n 1| grep -w influxd | tr -s ' ' | cut -d ' ' -f 11)"
echo "scale=3; ($var*$total/100)" | bc | tee -a data/mem.csv
sleep 1
done

~Rajind Ruparathna

The Maximum-Subarray Problem

What is meant by the maximum sub-array problem is that we want to find the non-empty, contiguous sub-array of an array whose values have the largest sum. Following is a divide & conquer solution implemented for it using Java language.

/**
 *
 * @author Rajind
 */
public class MaximumSubarrayProblem {
    public static int[] maxSubArray(int[] A) {
        int newsum = A[0];
        int max = A[0];

        int low = 0;
        int high = 0;

        for(int i=1;i<A.length;i++){ 
            if(newsum+A[i] > A[i]){
                high++;
            }else{
                low = i;
                high = i;
            }

            newsum = Math.max(newsum+A[i],A[i]);
            max= Math.max(max, newsum);
        }

        int[] arr = new int[3];
        arr[0] = max;
        arr[1] = low;
        arr[2] = high;
        return arr;
    }

    public static void main(String args[]){
        int[] arr = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
        int []array = maxSubArray(arr);
        System.out.println("max: "+array[0]);
        System.out.println("low: "+array[1]);
        System.out.println("high: "+array[2]);
    }
}

~Rajind Ruparathna

Reverse Words in a String

Reversing words in a string is a popular coding interview question. Here what is meant by reversing words in a string is something like this.

Input string:     “My name is rajind and i am a believer”
Output string:  “believer a am i and rajind is name My”

Doing this in-place without use additional space to store the string is the trick. Following is the java code to do that.

/**
 *
 * @author Rajind
 */
public class ReverseWordsString {

    public static char[] stringReverse(char[] arr, int start, int end){
        while(start < end){
            arr[start] = (char) (arr[start]^arr[end]);
            arr[end] = (char) (arr[start]^arr[end]);
            arr[start] = (char) (arr[start]^arr[end]);
            start++;
            end--;
        }
        return arr;
    }

    public static void main(String Args[]){
        /*char a = 'A';
        char b = 'B';
        a = (char) (a^b);
        b = (char) (a^b);
        a = (char) (a^b);

        System.out.println(a + "   "+ b);
        */

        char[] str = "My name is rajind and i am a believer".toCharArray();
        str = stringReverse(str, 0, str.length -1);

        int start = 0;
        for(int i=0; i < str.length; i++){
            if(str[i] == ' '){
                str = stringReverse(str, start, i-1);
                start = i + 1;
            }
        }

        str = stringReverse(str, start, str.length-1);
        System.out.println(str);
    }
}

~Rajind Ruparathna