Surely there has to be a better way to do this

What i wanted to do was take an array of integers and get all permutations of that array keeping the same length. I was using the array [1,2,3,4,5] after trying for a bit i just decided to do it the hard way. However im sure there is a better way. If you’ve ever done this before I’d love to see how you did it. This is how i did it in an ugly non scalable way.

let nums = [1,2,3,4,5];
let perms = [];

function permutate(arr){

	for(let i = 0; i < arr.length; i++){
		for(let j = 0; j < arr.length; j++){
			for(let k = 0; k < arr.length; k++){
				for(let l = 0; l < arr.length; l++){
					for(let m = 0; m < arr.length; m++){
						if(i != j && i != k && i != l && i != m && j != k && j != l && j != m && k != l && k != m && l != m){
							let newArr = [arr[i],arr[j],arr[k],arr[l],arr[m]];
							perms.push(newArr);
						}
					}
				}
			}
		}
	}
}

permutate(nums);
1 Like

found some info here:

2 Likes

Here’s an iterative version of Heap’s algorithm. It’s able to handle large arrays of any data type without stack overflows, it does not alter the original list order, and it calls a user-specified function for each iteration.

const perm = ( list, func ) => {
	const len = list.length
	const indices = []
	const listCopy = list.slice( )
	
	for ( let i = 0; i < len; i++ ) indices.push( 0 )
	
	let idx = 1
	
	func && func( list )
	
	while ( idx < len ) {
		if ( indices[ idx ] < idx ) {
			const swap = idx % 2 * indices[ idx ]
			
			;[ listCopy[ swap ], listCopy[ idx ] ] = [ listCopy[ idx ], listCopy[ swap ] ]
			
			func && func( listCopy )
			
			indices[ idx ]++
			idx = 1
		} else {
			indices[ idx++ ] = 0
		}
	}
}


const nums = [ 1, 2, 3, 4, 5 ]

perm( nums, ( list ) => console.log( list.join( ', ' ) ) )

1 Like