aNIRUDDHA

Friday, May 8, 2015

Solution to Reverse Words

This is one solution to "Reverse Words" problem in google codejam hosted at https://code.google.com/codejam/contest/351101/dashboard#s=p1

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * @author: Aniruddha Dutta Chowdhury (adchowdhury@gmail.com)
 * @since: May 8, 2015
 */

public class ReverseWords {

    public static void main(String[] args) {
        String filePath = "input.txt";
       
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String sCurrentLine;
            StringBuffer sb = new StringBuffer();
            int insertIndex = 0;
            char currentChar = '\b';
            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine);
                for(int iCharCounter = 0; iCharCounter < sCurrentLine.length(); iCharCounter++) {
                    currentChar = sCurrentLine.charAt(iCharCounter);
                    if(currentChar == ' ') {
                        insertIndex = 0;
                        sb.insert(insertIndex, currentChar);
                    }else {
                        sb.insert(insertIndex++, currentChar);
                    }
                }
                System.out.println(sb);
                sb = new StringBuffer();
                insertIndex = 0;
            }
        } catch (Throwable a_th) {
            a_th.printStackTrace();
        }
    }
}

Thursday, April 2, 2015

Hack to KUKU-KUBE

Hi

Its long since my last blog. Was caught up into many things and also was looking for something interesting to post.

This is hack to the game available in below link as of the date of publishing this blog. The idea is borrowed from "Imitation Game" & "Independence Day" movie.

http://www.kuku-kube.com/


Steps to make the game simpler are as follows:
1) Open the link in browser
2) Use firebug or other javascript debug tool. That can be invoked by pressing F12 on windows machines.
3) Copy the below whole code
4) Paste in the console area and execute
5) Now play the game. All tiles should be black & white. Which gives probability of scoring around 70 per minute.

function getScript(url, success) { 
 var script = document.createElement('script');
 script.src = url;
  
 var head = document.getElementsByTagName('head')[0],
 done = false;
  
 // Attach handlers for all browsers
 script.onload = script.onreadystatechange = function() {
  
   if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'){    
    // callback function provided as param
    success();    
    script.onload = script.onreadystatechange = null;
    head.removeChild(script);    
   };  
  };
}

getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',function(){
console.log(jQuery("span").size())
});
setInterval(changeColor, 100);
function changeColor(){
var previousColor = null;
jQuery("#box").find("span").each(function(index, element){
  if(index == 0){
    previousColor = null;
  }
 // console.log(index + " : " + previousColor + " : " + jQuery(this).css("background-color"))
  if(previousColor == null){
    previousColor = jQuery(this).css("background-color");
    jQuery(this).css("background-color", 'black')    
  }else  if(jQuery(this).css("background-color") == previousColor){
    jQuery(this).css("background-color", 'black')
  }else{
    jQuery(this).css("background-color", 'white')
  }
})
}

Tuesday, August 5, 2014

Recursively get all fields for a hierarchical class tree

Hi friends, it took quite a long time to again post something worthy. Normally when we play with reflection, we get metadata only about the targeted class, not anything inherited. This will try to resolve that part. We will get targeted class & it's inherited fields as well.

Any feedback is always welcome. Please do not hesitate in case you have any.


public class testReflection {
    public static void main(String[] args) {
        try {
            C c = new C();
            Class klass = c.getClass();
            Field[] fields = getAllFields(klass);
            for (Field field : fields) {
                System.out.println(field.getName());
            }
        catch (Throwable a_th) {
            a_th.printStackTrace();
        }
    }

    public static Field[] getAllFields(Class klass) {
        List fields = new ArrayList();
        fields.addAll(Arrays.asList(klass.getDeclaredFields()));
        if (klass.getSuperclass() != null) {
            fields.addAll(Arrays.asList(getAllFields(klass.getSuperclass())));
        }
        return fields.toArray(new Field[] {});
    }
}

class {
    public String    nameA    = "";
}

class extends {
    public String    nameB    = "";
    public String    nameB1    = "";
    public String    nameB2    = "";
}

class extends {
    public String    nameC    = "";
}

Friday, June 28, 2013

Solution to Store Credit

This is a probable solution to CODE JAM's Store Credit.


import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;


public class StoreCredit {
   
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(ReverseWords.class.getClassLoader().getResourceAsStream("A-large-practice.in"));
            int problemCount = Integer.parseInt(scanner.nextLine());
            int caseCounter = 1;
            for(int iProblemCounter = 0; iProblemCounter < problemCount; iProblemCounter++) {
                Set completedIndexes = new HashSet();
               
                int creditAmount = Integer.parseInt(scanner.nextLine());
                int numberOfItems = Integer.parseInt(scanner.nextLine());
                String itemsLine = scanner.nextLine();
                String[] intArray = itemsLine.split(" ");
                String output = "";
                itemLoop:{
                    for (int iArrayCounter = 0; iArrayCounter < numberOfItems; iArrayCounter++) {
                        completedIndexes.add(iArrayCounter);
                        for (int iArrayInnerCounter = 0; iArrayInnerCounter < numberOfItems; iArrayInnerCounter++) {
                            if(completedIndexes.contains(iArrayInnerCounter)) {
                                continue;
                            }
                            int sum = (Integer.parseInt(intArray[iArrayCounter]) + Integer.parseInt(intArray[iArrayInnerCounter]));
                            output = (iArrayCounter + 1) + " " + (iArrayInnerCounter + 1);
                            if(sum == creditAmount) {
                                break itemLoop;
                            }
                        }
                    }
                }
                System.out.println("Case #" + (caseCounter++) + ": " + output);
            }
        } catch (Throwable a_th) {
            a_th.printStackTrace();
        }
    }
}
See you later friends.

Thursday, March 14, 2013

Windows Service Monitor and starting

Hi friends,

It's been long since my last post. Again I am here with some solution. Specifically for windows. The problem statement was, few windows service was getting stopped all of a sudden due to some error. What we needed is one small utility which monitors the specific service and start that if that is stopped.

There was many suggestion and solution, many monitoring softwares. But I liked the solution mentioned below. Took quite some time to collect all the information and build it.

First copy paste the below code in a file named as "serviceMonitor.vbs" or you can choose any other name as well.


Set sh = CreateObject("Shell.Application")
set shellLogger = CreateObject("WScript.Shell")

If sh.IsServiceRunning("SERVICE_TO_MONITOR") Then
    shellLogger.LogEvent 4, "
SERVICE_TO_MONITOR is running"
Else
    shellLogger.LogEvent 4, "
SERVICE_TO_MONITOR is not running"
    if sh.ServiceStart("
SERVICE_TO_MONITOR", true) Then
        shellLogger.LogEvent 4, "
SERVICE_TO_MONITOR automatically started"
    Else
        shellLogger.LogEvent 4, "
SERVICE_TO_MONITOR could not be started"
    End If
End If   

Replace the word SERVICE_TO_MONITOR with name of your service.
Then open scheduler and create a task. Choose the trigger you want, I kept it at every 1 min.

wolla...  your windows service will never be down. If it is down, It will be up within next one min. :)

Saturday, June 23, 2012

DiamondPattern

Hi friends,

This is a simple program which generates a diamond kind of pattern with the passed character which is 'e' in this case.




public class DiamondPattern {
    public static void main(String[] args) {
        printPattern('e');
    }
   
    private static final int BASE_CHAR = (int)'a';
   
    private static void printPattern(char a_endChar) {
        int charCounter = BASE_CHAR;
        boolean isIncreasing = true;
        do {
            System.out.print(getPadding(a_endChar - charCounter + 1));
           
            for(int iHCounter = BASE_CHAR; iHCounter < charCounter; iHCounter++) {
                System.out.print((char)iHCounter);
            }
           
            for(int iHCounter = charCounter - 2; iHCounter >= BASE_CHAR; iHCounter--) {
                System.out.print((char)iHCounter);
            }
           
            if(isIncreasing) {
                charCounter++;
            }else {
                charCounter--;
            }
           
            if(charCounter > a_endChar) {
                isIncreasing = false;
            }
            System.out.println();
        }while(charCounter >= BASE_CHAR);
    }
   
    public static String getPadding(int a_padCount) {
        StringBuffer strPadding = new StringBuffer();
        for (int iCounter = 0; iCounter < a_padCount; iCounter++) {
            strPadding.append(' ');
        }
        return strPadding.toString();
    }
}

Thursday, March 8, 2012

Number Formatter in JAVASCRIPT

Hi friends,

When we want to format, type cast and convert numbers in JAVASCRIPT with multilingual support, there are none. So came out with this.

This supports European & English both kind of number formatting. While using this, just set the basic 3 variables.

Save the code with any name, say NumberFormatter.js then call like this with jQuery

jQuery.getScript(
{
  url: 'NumberFormatter.js',
  dataType: "script",
  success: function(){
NumberFormatter._tSep = '<get the data from user profile with server side code&gt>';
               NumberFormatter._dSep = '<get the data from user profile with server side code>';
               NumberFormatter.DEFAULT_PRECISION = <get the data from user profile with server side code>; 
}
}
);



 The code for Javascript file starts from here....

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };

function NumberFormatter(){}

NumberFormatter._tSep = ',';
NumberFormatter._dSep = '.';
NumberFormatter.DEFAULT_PRECISION = 2;
NumberFormatter.IS_STRICT_THOUSAND_SEPARATOR_VALIDATION = false;

NumberFormatter.setThousandSeparator = function(tSep){
    NumberFormatter._tSep = tSep;
}

NumberFormatter.setDecimalSeparator = function(dSep){
    NumberFormatter._dSep = dSep;
}

NumberFormatter.getInteger = function(num2Get){
    return NumberFormatter.parseNumber(num2Get, true);
}

NumberFormatter.getDecimal = function(num2Get, decimalPrecision){
    return NumberFormatter.parseNumber(num2Get, false, decimalPrecision);
}

/**
 * this function is to be used before sending
 * to server side.
 */
NumberFormatter.parseNumber = function(num2Get, isNumberOnly, a_decimalPrecision){
    if(num2Get == ""){
        return "";
    }
    var tSep = NumberFormatter._tSep;
    var dSep = NumberFormatter._dSep;
    var parts = (num2Get + "").split(dSep);
    var firstPart = parts[0];
    var decPrec = (typeof(a_decimalPrecision) != "undefined"  && !isNaN(a_decimalPrecision) && a_decimalPrecision >= 0) ? a_decimalPrecision : NumberFormatter.DEFAULT_PRECISION;
    var secondPart = parts.length > 1 ? parts[1] : "00";  
    if(secondPart.trim() == ""){
        secondPart = "00";
    }
  
    var tSepIndex = firstPart.indexOf(tSep);
    while(tSepIndex >= 0){
        firstPart = firstPart.replace(tSep, "");
        tSepIndex = firstPart.indexOf(tSep, tSepIndex);
    }
    if(isNumberOnly){
        return parseInt(firstPart);
    }else{
        if(isNaN(firstPart) || isNaN(secondPart))
        {
            return NaN;
        }  
        //alert(Math.round(parseFloat(firstPart + "." + secondPart)*Math.pow(10,decPrec))/Math.pow(10,decPrec));
        return Math.round(parseFloat(firstPart + "." + secondPart)*Math.pow(10, decPrec)) / Math.pow(10, decPrec);
    }
}

function roundVal(val, decPrec){
    var result = Math.round(val * Math.pow(10, decPrec)) / Math.pow(10, decPrec);
    return result;
}

/**
 * please do not use this, use the formatDecimal instead
 *
 * @deprecated
 */
NumberFormatter.formatNumber = function(num2Format){
    return NumberFormatter.formatDecimal(num2Format, true);
}

NumberFormatter.formatDecimal = function(num2Format, isNumberOnly, a_decimalPrecision){
    if(isNaN(num2Format)){
        return num2Format;
    }
  
    if(!isFinite(num2Format)){
        return num2Format;
    }
  
    if(typeof(num2Format) == 'number'){
        num2Format = num2Format.toString();
    }
  
    if(num2Format == ""){
        return "";
    }
  
    var tSep = NumberFormatter._tSep;
    var dSep = NumberFormatter._dSep;
    var decPrec = (typeof(a_decimalPrecision) != "undefined" && !isNaN(a_decimalPrecision) && a_decimalPrecision >= 0) ? a_decimalPrecision : NumberFormatter.DEFAULT_PRECISION;
    var formattedNum = parseFloat(num2Format).toFixed(decPrec);
    var isMinus = formattedNum < 0;
    var parts = String(Math.abs(formattedNum)).split('.');
    var firstPart = parts[0];
    var secondPart = parts.length > 1 ? parts[1] + NumberFormatter.getLeading0s(decPrec - parts[1].length) : NumberFormatter.getLeading0s(decPrec);
    if(firstPart.length <= 3){      
        if(isMinus){
            firstPart = "-" + firstPart;
        }
      
        if(decPrec > 0 && !isNumberOnly) {
            return (firstPart + dSep + secondPart);
        }
      
        return firstPart;                  
    }
  
    var newStr = "";
    for(var i = firstPart.length - 1; i >= 0; i--){
        newStr = firstPart.charAt(i) + newStr ;
        if(i == firstPart.length - 1){
            continue;
        }
        if(i == 0){
            continue;
        }
        var d = (firstPart.length - i) / 3;
        if(Math.ceil(d) == Math.floor(d)){
            newStr = tSep + newStr;
        }
    }
    if(isMinus){
        newStr = "-" + newStr;
    }
    if(isNumberOnly){
        return newStr;
    }
    return newStr + (decPrec > 0 ? (dSep + secondPart) : "");
}

NumberFormatter.validateInput = function(inputText, isNumberOnly, isToAllowNegetive, isMandatory, a_decimalPrecision){
    if(typeof(inputText) == 'number'){
        inputText = inputText.toString();
    }
  
    var returnObject = new Object();
    var decPrec = (typeof(a_decimalPrecision) != "undefined"  && !isNaN(a_decimalPrecision) && a_decimalPrecision >= 0) ? a_decimalPrecision : NumberFormatter.DEFAULT_PRECISION;
  
    //lets test blank input
    if(isMandatory && String(inputText).trim().length <= 0){
        returnObject.message = "BLANK_INPUT";
        returnObject.isValid = false;
        return returnObject;
    }
  
    //no white space is allowed
    if(inputText.indexOf(" ") >= 0){
        returnObject.message = "WHITE_SPACE_IN_INPUT";
        returnObject.isValid = false;
        return returnObject;
    }
  
    //check valid chars
    var ln = inputText.length;
    for(var iCounter = 0; iCounter < ln; iCounter++){
        var currentChar = inputText.charAt(iCounter);
        //if the first char is minus then let it go
        if(isToAllowNegetive && iCounter == 0 && currentChar == '-'){
            continue;
        }
        if(isValidChar(currentChar) == false){
            returnObject.message = "INVALID_CHARACTER_IN_INPUT";
            returnObject.isValid = false;
            return returnObject;
        }
    }
  
    if(isNumberOnly && inputText.indexOf(NumberFormatter._dSep) >= 0){
        returnObject.message = "DECIMAL_NOT_ALLOWED";
        returnObject.isValid = false;
        return returnObject;
    }
  
    var firstChar = inputText.charAt(0);
    var lnToTest = inputText.split(NumberFormatter._tSep).join("").length;
    if(firstChar == '-'){
        lnToTest = lnToTest - 1;
    }
    if(lnToTest > 15){
        returnObject.message = "TOO_LONG_INPUT";
        returnObject.isValid = false;
        return returnObject;
    }
  
    //check single decimal separator
    var parts = inputText.split(NumberFormatter._dSep);              
    if(parts.length > 2){
        returnObject.message = "MULTIPLE_DECIMAL_SEPARATOR";
        returnObject.isValid = false;
        return returnObject;
    }
  
    var firstPart = parts[0];
    var secondPart = parts[1];
  
    //in the decimal part there can not be thousand separator
    if(secondPart!= null && secondPart.length > 0 && secondPart.indexOf(NumberFormatter._tSep) >= 0){
        returnObject.message = "THOUSAND_SEPARATOR_IN_DECIMAL_PART";
        returnObject.isValid = false;
        return returnObject;
    }
  
    if(NumberFormatter.IS_STRICT_THOUSAND_SEPARATOR_VALIDATION){
        var thousandParts = firstPart.split(NumberFormatter._tSep);
        for(var iCounter = thousandParts.length - 1; iCounter > 0; iCounter--){
            if(thousandParts[iCounter].length != 3){
                returnObject.message = "INVALID_POSITIONING_OF_THOUSAND_SEPARATOR";
                returnObject.isValid = false;
                return returnObject;
            }
        }
    }
  
    /*if(secondPart.length > decPrec){
        returnObject.message = "TOO_LONG_DECIMAL_PART";
        returnObject.isValid = false;
        return returnObject;
    }*/
  
    returnObject.message = "VALID_NUMBER";
    returnObject.isValid = true;
    return returnObject;
}

NumberFormatter.formatCurrency = function(num2Format){
    return NumberFormatter.formatDecimal(num2Format);
}

NumberFormatter.getLeading0s = function(decPrec) {
    var s0s=[];
    for(var i = 0; i < decPrec; i++) {
        s0s.push('0');
    }
    return s0s.join('');
}

function isValidChar(charToTest){
    switch(charToTest){
        case '0':
            return true;
        case '1':
            return true;
        case '2':
            return true;
        case '3':
            return true;
        case '4':
            return true;
        case '5':
            return true;
        case '6':
            return true;
        case '7':
            return true;
        case '8':
            return true;
        case '9':
            return true;
        case '.':
            return true;
        case ',':
            return true;
        default:
            return false;
    }  
}



Hope this will help you all. So long till next time...