Skip to content

Instantly share code, notes, and snippets.

@ambroseus
Created October 10, 2020 07:50
Show Gist options
  • Save ambroseus/2a0809a9f351e6c1f029d76696935ac2 to your computer and use it in GitHub Desktop.
Save ambroseus/2a0809a9f351e6c1f029d76696935ac2 to your computer and use it in GitHub Desktop.
imperative variants
module.exports = getVariants
function getVariants(str = '', symbol = '.') {
const variants = [str]
const bitsLength = str.length - 1
if (bitsLength === -1) {
return []
}
if (bitsLength === 0) {
return variants
}
const bitsArray = new Array(bitsLength)
bitsArray[0] = 1
let bitsSum = 1
while (bitsSum > 0) {
let strWithSymbol = ''
let currentSum = 0
let carryBit = 1
let pos = 0
while (pos < bitsLength) {
const currentBit = bitsArray[pos]
const charWithSymbol = currentBit ? `${str[pos]}${symbol}` : str[pos]
strWithSymbol += charWithSymbol
if (carryBit) {
bitsArray[pos] = currentBit ? 0 : 1
carryBit = currentBit
}
currentSum += bitsArray[pos] || 0
pos++
}
bitsSum = currentSum
variants.push(strWithSymbol + str[pos])
}
return variants
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment