Flipkart

Thursday, June 3, 2010

Word Jumbling

According to a researcher at Cambridge University, it doesn’t matter in what order the letters in a word are, the only important thing is that the first and last letter be at the right place. The rest can be a total mess and you can still read it without problem. This is because the human mind does not read every letter by itself but the word as a whole.

Here is the little JavaScript ‘program’ to do word jumbling written by James Padolsey.

The first component is a function which jumbles a string’s characters:

function jumble(word) {

// Rand function will return 2-part array
// [0] -> Index of rand, [1] -> random found value (from args)
var rand = function(){
var myRand = Math.floor(Math.random() * arguments.length);
return [myRand, arguments[myRand]];
},

// Split passed word into array
word = word.split(''),

// Cache word length for easy looping
length = word.length,

// Prepate empty string for jumbled word
jumbled = '',

// Get array full of all available indexes:
// (Reverse while loops are quickest: http://reque.st/1382)
arrIndexes = [];
while (length--) {
arrIndexes.push(length);
}

// Cache word length again:
length = word.length;

// Another loop
while (length--) {
// Get a random number, must be one of
// those found in arrIndexes
var rnd = rand.apply(null,arrIndexes);
// Append random character to jumbled
jumbled += word[rnd[1]];
// Remove character from arrIndexes
// so that it is not selected again:
arrIndexes.splice(rnd[0],1);
}

// Return the jumbled word
return jumbled;

}

The second component get’s the value of the textarea on each keyup event and jumbles all characters between the first and last letter of each word: (It also has a primitive way of handling simple punctuation)


$('textarea').keyup(function(){
var text = $(this).val().split(/\s/g),
converted = '';

$.each(text, function(i,word){
if(!word.length) return;

// Extract punctuation:
var puncPattern = /[,\.;:'!\?]+/,
punc = word.match(puncPattern) ? word.match(puncPattern)[0] : '',
puncIndex = word.search(puncPattern),
word = word.replace(punc,'');

// Compile new word, split to array:
var newWord =
(word.length > 2 ?
word.substr(0,1) + jumble(word.substr(1,word.length-2))
+ word.substr(word.length-1)
: word).split('');

// Insert punctuation back in:
newWord.splice(puncIndex,0,punc);

// Add space after word:
converted += newWord.join('') + '\u0020';

});

// Inserted jumbled test into receiver:
$('#receiver').text(converted);
});


You can see a demo of the above script here.

No comments:

Post a Comment