This uses generator functions to generate permutations on demand.
The typescript is the original, the js version is just the compiled typescript.
This uses generator functions to generate permutations on demand.
The typescript is the original, the js version is just the compiled typescript.
function* permGenerator<T>(items: T[]): Generator<T[]> { | |
const indices = items.map((_, idx) => idx); | |
const reformArray = (idxs: number[]): T[] => idxs.map(idx => items[idx]); | |
function* permute(stack: number[]): Generator<T[]> { | |
if (stack.length === indices.length) { | |
yield reformArray(stack); | |
} | |
for (let i = 0; i < indices.length; i++) { | |
const idx = indices[i]; | |
if (!stack.includes(idx)) { | |
stack.push(idx); | |
yield* permute(stack); | |
stack.pop(); | |
} | |
} | |
} | |
yield* permute([]); | |
} | |
function findPalindrome(str: string): string | null { | |
const gen = permGenerator(str.toLowerCase().split('')); | |
for (const perm of gen) { | |
const reverse = [...perm].reverse().join(''); | |
const forward = perm.join(''); | |
if (forward === reverse) { | |
return forward; | |
} | |
} | |
return null; | |
} | |
console.log(findPalindrome('tactcoa')); | |
console.log(findPalindrome('acecarr')); |
function* permGenerator(items) { | |
const indices = items.map((_, idx)=>idx | |
); | |
const reformArray = (idxs)=>idxs.map((idx)=>items[idx] | |
) | |
; | |
function* permute(stack) { | |
if (stack.length === indices.length) { | |
yield reformArray(stack); | |
} | |
for(let i = 0; i < indices.length; i++){ | |
const idx = indices[i]; | |
if (!stack.includes(idx)) { | |
stack.push(idx); | |
yield* permute(stack); | |
stack.pop(); | |
} | |
} | |
} | |
yield* permute([]); | |
} | |
function findPalindrome(str) { | |
const gen = permGenerator(str.toLowerCase().split('')); | |
for (const perm of gen){ | |
const reverse = [ | |
...perm | |
].reverse().join(''); | |
const forward = perm.join(''); | |
if (forward === reverse) { | |
return forward; | |
} | |
} | |
return null; | |
} | |
console.log(findPalindrome('tactcoa')); | |
console.log(findPalindrome('acecarr')); |