DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Permute //JavaScript Function

09.09.2005
| 4938 views |
  • submit to reddit
        <a href="http://www.jsfromhell.com/array/permute">
It permutes elements in an array, the "m" parameter is a boolean which determines if the function should return an array with an "index map" or the real value.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/permute [v1.0]

permute = function( v, m ){
	for( var j, l = v.length, i = ( 1 << l ) - 1, r = new Array( i ); i; )
		for( r[--i] = [], j = l; j; i + 1 & 1 << --j && ( r[i].push( m ? j : v[j] ) ) );
	return r;
};



Example

document.write( permute( ["A", "B", "C" ], 1 ).join( "<br />" ), "<hr />" );
document.write( permute( ["A", "B", "C" ], 0 ).join( "<br />" ) );