Code of the Day: Sentence Scrambler


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Task:
There was a study going out a few years ago that said people can read words that are scrambled if the first and last character are left in place. So to help me practice Test Driven Development, I decided program it.
Example:
Correct: “Create attractive offers to reach the right customers”
Scrambled: “Cterae aacrtvitte offres to recah the rghit couemtrss”

For more information about the study visit: Cambridge Word Scramble Study: It’s Fake Already!

Code:

/**
* @author: Larry Battle
* @date: January 2, 2012
* @purpose: Scrambler - to scramble the alphabetical letters in word in such a way to make it still readable and understandable.
* @note: This can be accomplished by have perversing the word order but mixing up every letter in the word except for the first.
*/
var scrambler = {
	scrambleStr : function( str ){
		if( typeof str !== 'string' ){
			return -1;
		}
		return str.replace( /[^\s]*/g, function( word ){			
			return word ? scrambler.scrambleWord( word ) : word;
		});
	},
	scrambleWord :  function( str ){
		if( typeof str !== 'string' ){
			return str;
		}
		str = str.replace( /[a-z]*/ig, function( str2 ){
			if( str2 && str2.length > 2 ){
				str2 = str2.charAt(0) + scrambler.randomizeStr( str2.substring( 1, str2.length - 1 ) ) + str2.charAt( str2.length - 1 );
			}
			return str2;
		});
		return str;
	},
	randomizeStr : function( str ){
		if( typeof str !== 'string' ){
			return str;
		}
		return scrambler.makeArrayRandom( str.split( '' ) ).join( '' );
	},
	makeArrayRandom : function( arr ){
		var j, x, i = arr.length;
		while( i ){
				j = parseInt(Math.random() * i, 10);
				x = arr[--i]; 
				arr[i] = arr[j];
				arr[j] = x;
		}
		return arr;
	}
};

Input:

var str = "I can't believe what I'm reading."
scrambler.scrambleStr( str );

Output: (Possible outcome)

"I can't beilvee waht I'm rndiaeg."

Try it out for yourself.
Demo: Scrambler

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the Day: DOS Open an existing file or create it if it doesn’t exist


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94
REM filename: openAndORCreateFileTXT.bat
rem\ >> file.txt && file.txt

The following will open a existing file named file.txt. However, it if doesn’t exist then it will create it for you then open it. This is very useful.

“rem\” Let’s you return a empty character.
“>> file.txt” appends the returned value on the left hand side, which in this case is nothing.
“&& file.txt” once the left hand operation is done, then open the file ( file.txt).

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Code of the Day: Groovy Print all Methods of an object


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

Groovy Code

/**
* @function printAllMethods
* @purpose Prints an objects class name and then list the associated class functions.
*/
// Filename: printAllMethodsExample.groovy
void printAllMethods( obj ){
    if( !obj ){
		println( "Object is null\r\n" );
		return;
    }
	if( !obj.metaClass && obj.getClass() ){
        printAllMethods( obj.getClass() );
		return;
    }
	def str = "class ${obj.getClass().name} functions:\r\n";
	obj.metaClass.methods.name.unique().each{ 
		str += it+"(); "; 
	}
	println "${str}\r\n";
}

Example Code

// Filename: printAllMethodsExample.groovy
void printAllMethods( obj ){
    if( !obj ){
		println( "Object is null\r\n" );
		return;
    }
	if( !obj.metaClass && obj.getClass() ){
        printAllMethods( obj.getClass() );
		return;
    }
	def str = "class ${obj.getClass().name} functions:\r\n";
	obj.metaClass.methods.name.unique().each{ 
		str += it+"(); "; 
	}
	println "${str}\r\n";
}
printAllMethods( null );
printAllMethods( 1 );
printAllMethods( "string" );
printAllMethods( [1:1] );

Output

Object is null
 
class java.lang.Integer functions:
equals(); getClass(); hashCode(); notify(); notifyAll(); toString(); wait(); byteValue(); doubleValue(); floatValue(); intValue(); longValue(); shortValue(); bitCount(); compare(); compareTo(); decode(); getInteger(); highestOneBit(); lowestOneBit(); numberOfLeadingZeros(); numberOfTrailingZeros(); parseInt(); reverse(); reverseBytes(); rotateLeft(); rotateRight(); signum(); toBinaryString(); toHexString(); toOctalString(); valueOf(); 
 
class java.lang.String functions:
equals(); getClass(); hashCode(); notify(); notifyAll(); toString(); wait(); charAt(); codePointAt(); codePointBefore(); codePointCount(); compareTo(); compareToIgnoreCase(); concat(); contains(); contentEquals(); copyValueOf(); endsWith(); equalsIgnoreCase(); format(); getBytes(); getChars(); indexOf(); intern(); isEmpty(); lastIndexOf(); length(); matches(); offsetByCodePoints(); regionMatches(); replace(); replaceAll(); replaceFirst(); split(); startsWith(); subSequence(); substring(); toCharArray(); toLowerCase(); toUpperCase(); trim(); valueOf(); 
 
class java.lang.Class functions:
equals(); getClass(); hashCode(); notify(); notifyAll(); toString(); wait(); clear(); containsKey(); containsValue(); entrySet(); get(); isEmpty(); keySet(); put(); putAll(); remove(); size(); values(); clone();
Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube

Improved Code for Javascript Decimal to Fraction


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in /home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line 380

Warning: Undefined array key "layout" in /home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line 94

This post improves the code at “Code of the Day Javascript Decimal to fraction” by using Euclid’s Algorithm to find the Great Common Factor or GCF, aka GCD. This method provides a speed up of 10x when compared to the original algorithm posted.

Code

/**
*@function gcd (aka Euclid's algorithm)
*@purpose returns the greatest common factor between two numbers;
*/
function gcd(a, b) {
    return (b) ? gcd(b, a % b) : a;
}
/**
*@function dec2Frac
*@purpose returns a decimal as a fraction.
*/
var dec2Frac = function ( num ) {
	var top = num.toString().replace(/\d+[.]/, '');
	var bot = Math.pow(10, top.length);
	if (num > 1) {
		top = +top + Math.floor(num) * bot;
	}
	var x = gcd(top, bot);
	return (top / x) + "/" + (bot / x);
};

Usage

dec2Frac( 1.24325 ) // returns "4973/4000"
dec2Frac( 2.45 ) // returns "49/20"

Speed Test between Version 1 and 2 of dec2Frac()

//@requires Firebug or Chrome Developer Tools
//The following code test the speed difference between the Version 1 and 2 of dec2Frac.
function gcd(a, b) {
    return (b) ? gcd(b, a % b) : a;
}
var dec2FracV2 = function (d) {
	var top = d.toString().replace(/\d+[.]/, '');
	var bot = Math.pow(10, top.length);
	if (d > 1) {
		top = +top + Math.floor(d) * bot;
	}
	var x = gcd(top, bot);
	return (top / x) + "/" + (bot / x);
};
function dec2FracV1(d) {
    var df = 1, top = 1, bot = 1;
    var limit = 1e5; //Increase the limit to get more precision.
 
    while (df != d && limit-- > 0) {
        if (df < d) {
            top += 1;
        }
        else {
            bot += 1;
            top = parseInt(d * bot, 10);
        }
        df = top / bot;
    }
    return top + '/' + bot;
}
var getRandomNum = function (i, decLen) {
	return (Math.random() * (i || 1)).toFixed(decLen);
};
 
var runTest = function ( funcName ) {
	var func = { "V1": dec2FracV1, "V2": dec2FracV2 }[ funcName ];
	var i = 1000;
	while (i--) {
		num = getRandomNum(10, 4);
		var x = func(num);
		if (num != eval(x)) {
			console.warn("ERROR: Function %s, The fraction %s != %s", funcName, num, x);
		}
	}
};
console.time( 'V1' );
runTest( "V1" );
console.timeEnd( 'V1' );
 
console.time( 'V2' );
runTest( "V2" );
console.timeEnd( 'V2' );

Chrome Result:
V1: 11628ms
V2: 185ms

Try the test out yourself
jsbin.com

Larry Battle

Larry Battle

I love to program, and discover new tech. Check out my <a href="http://stackoverflow.com/users/527776/larry-battle">stackoverflow</a> and <a href="https://github.com/LarryBattle">github</a> accounts.

More Posts - Website

Follow Me:Add me on XAdd me on LinkedInAdd me on YouTube