Skip to content

Instantly share code, notes, and snippets.

@btray77
Created September 21, 2022 09:27
Show Gist options
  • Save btray77/b20b041365a29789458ba0061da063bc to your computer and use it in GitHub Desktop.
Save btray77/b20b041365a29789458ba0061da063bc to your computer and use it in GitHub Desktop.
Random Order String List Sorted
var str = "word1 word2 word3 word4 word5";
var wordList = str.split(" ");
var wordCount = wordList.length;
function permute(wordList, wordCount) {
var results = [];
if (wordCount === 1) {
return wordList;
}
wordList.forEach(function(word) {
var subPermutations = permute(wordList.filter(function(v) {
return v !== word;
}), wordCount - 1);
subPermutations.forEach(function(subPermutation) {
results.push(word + " " + subPermutation);
});
});
return results;
}
console.log(permute(wordList, wordCount).sort());
/*
var str = "chocolate whey protein today";
var wordList = str.split(" ");
var wordCount = wordList.length;
function permut(wordList) {
if (wordList.length === 0) {
return [];
} else if (wordList.length === 1) {
return [wordList];
} else {
var result = [];
for (var i = 0; i < wordList.length; i++) {
var firstWord = wordList[i];
var wordsLeft = wordList.slice(0, i).concat(wordList.slice(i + 1));
var innerPermutations = permut(wordsLeft);
for (var j = 0; j < innerPermutations.length; j++) {
result.push([firstWord].concat(innerPermutations[j]));
}
}
return result;
}
}
var result = permut(wordList);
console.log(result);
*/
/*
var str = "chocolate whey protein today";
var wordList = str.split(" ");
var wordCount = wordList.length;
var wordCombinations = [];
function permute(arr, memo) {
var cur, memo = memo || [];
for (var i = 0; i < arr.length; i++) {
cur = arr.splice(i, 1);
if (arr.length === 0) {
wordCombinations.push(memo.concat(cur));
}
permute(arr.slice(), memo.concat(cur));
arr.splice(i, 0, cur[0]);
}
return wordCombinations;
}
console.log(permute(wordList).sort());
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment