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
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
(Page view Count: 187)