Last active
August 29, 2019 15:15
-
-
Save PartyLich/b9a28d5b5a6b5c7af1d1b4bdd97e053a to your computer and use it in GitHub Desktop.
FreeCodeCamp => Algorithms: No Repeats Please
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
/** | |
* @param {array} arr array to insert into | |
* @param {number} i index for insertion | |
* @param {object} val value to be inserted | |
* @return {array} a new array with val inserted at i | |
*/ | |
const insert = (i, arr, val) => [...arr.slice(0, i), val, ...arr.slice(i)]; | |
/** | |
* @param {string} | |
* @return {array} array of permutations | |
*/ | |
const getPermutations = (str) => { | |
let strArray = str.split(''); | |
let permutations = [[]]; | |
strArray.forEach((curChar, i) => { | |
let tempArray = []; | |
permutations.forEach((val) => { | |
for (let j = 0; j <= val.length; j++) { | |
tempArray.push(insert(j, val, curChar)); | |
} | |
}); | |
permutations = tempArray.slice(); | |
}); | |
return permutations | |
.map((val) => val.join('')); | |
}; | |
/** | |
* @param {string} str | |
* @return {number} number of total permutations of the provided string | |
* that don't have repeated consecutive letters | |
*/ | |
function permAlone(str) { | |
const repeatRe = /(\w{1})\1/i; | |
const noRepeat = (val) => !repeatRe.test(val); | |
const permutations = getPermutations(str); | |
return permutations | |
.filter(noRepeat) | |
.length; | |
} | |
// console.log( | |
// `aab: ${permAlone('aab')}` | |
// ) | |
// console.log( | |
// `aabb: ${permAlone('aabb')}` | |
// ) | |
// console.log( | |
// `ab: ${permAlone('ab')}` | |
// ) | |
// console.log( | |
// `aaabb: ${permAlone('aaabb')}` | |
// ) | |
console.log( | |
`123: ${permAlone('123')}` | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment