Pages

Monday, 19 September 2016

Permutation of String in JavaScript

A simple algorithm to find the permutation of a string in JavaScript.
/**
 * Find the permutations of the given string.
 * @param s The input string
 *
 * Algorithm:
 * 1. If the length of the string is 1, return the string as permutation of 'a' is 'a'
 * 2. Else for the given string find the last character char and the substring by stripping the last char
 *    2.1 Recurse with the substring
 * 3. For each permutation from step 2 add the char to each position of the substring and return
 */
function permute(s) {
    var len = s.length, char, i = 0, j = 0, p = [], elem, pArr = [], plen = 0;
    
    if (len == 1) return s;
    
    char = s.charAt(len-1);
    pArr = permute(s.substring(0, len-1));
    plen = pArr.length;

    for (i = 0; i < plen; i++) {
        for (j = 0; j < len; j++) {
            elem = pArr[i].split("");
            elem.splice(j, 0, char);
            p.push(elem.join(""));
        }
    }
    return [...new Set(p)];
}
permute("abc"); // [ 'cba', 'bca', 'bac', 'cab', 'acb', 'abc' ]
Download from github. Adapted from python version by GodComplex2.

Sunday, 18 September 2016

Make a Copy of an Array in JavaScript

If you want to make a copy of an array in JavaScript, you can use Array#slice method. This way we will get a copy of the array. If we are simply assigning the array to another variable, it is not making a copy. So performing splice() operation on the array will affect the value stored in both variables.
var a = [1,2,3],
    b = a;
a.splice(1,1); // => a is [1,3] and b is also [1,3]
var a = [1,2,3],
    b = a.slice(0);
a.splice(1,1); // => a is [1,3] and b is [1,2,3]

Saturday, 3 September 2016

Override Properties File Using Classpath

Say you have a config.properties file containing various configuration details. This file is placed under the resources folder and loaded using classpath. Then you can override the file during runtime by specifying a different file to the classpath command line argument. Let's say that the main class is Main.java inside com.example.test package and the test.jar is our program. Use the following command to override the config.properties file.
java -classpath .;test.jar;config.properties; com.example.test.Main