Created
September 20, 2013 20:24
-
-
Save vetri02/6643338 to your computer and use it in GitHub Desktop.
Gives back the anagram of the string thats being passed in eg. anag("abc") Result: [ 'cab', 'bca', 'abc', 'cba', 'acb', 'bac' ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* NEED TO PERFORMANCE TUNE */ | |
function anag(str){ | |
'use strict'; | |
if(typeof str !== 'string'){ | |
return ; | |
} | |
str = str.replace(/\s+/g, '').toLowerCase(); | |
console.log(str); | |
var splitStr = str.split(""), | |
strLength = splitStr.length, | |
permLengthfunc = function(len){ | |
var prem = 1; | |
for(var i=len; i >= 1; i--){ | |
(i===len)?prem = prem * len:prem = prem * i; | |
} | |
return prem; | |
}, | |
permLength = permLengthfunc(strLength), | |
finalPerm = []; | |
console.log(permLength); | |
// finalPerm.push(str); | |
// finalPerm.push(splitStr.reverse().join("")); | |
var set1 =[], | |
set2 = [], | |
halflength = permLength/2; | |
function looper(strSplit, set){ | |
for (var i = 0; i < halflength; i++) { | |
if (typeof set !== 'undefined' && set.length > 0) { | |
var setLastArr = set[(set.length-1)].split(""); | |
// console.log(setLastArr); | |
var set1Last = setLastArr.pop(); | |
setLastArr.unshift(set1Last) | |
set.push(setLastArr.join("")); | |
}else{ | |
var orgArr = splitStr; | |
var setLast = orgArr.pop(); | |
// console.log(setLast); | |
// console.log(orgArr); | |
orgArr.unshift(setLast); | |
set.push(orgArr.join("")); | |
} | |
}; | |
} | |
looper(splitStr, set1); | |
looper(splitStr.reverse(), set2); | |
// console.log(set1); | |
// console.log(set2); | |
finalPerm = set1.concat(set2); | |
return finalPerm; | |
} | |
console.log(anag("Github")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment