提问者:小点点

使用node.js,我如何将一个字符放在字符串中其他字符空间之间


我的目标的一个例子是:

let string = "hello"

我的目标是:

h.ello
h.e.llo
h.e.l.lo
h.e.l.l.o
h.el.l.o
h.ell.o
he.l.l.o
he.ll.o
he.llo
h.el.lo
//so on until all possibilities are met

我不知道如何处理这件事,任何帮助都是很好的,我的目标是在最后有每一个可能的组合点和我的字,这是“你好”。


共1个答案

匿名用户

多么有趣的小挑战。

以下是我的解决方案:

const interject = (text, char) => {
  const n = text.length - 1
  return Array.from(Array(2**n))
    .map((v,i) => {
      const binary = i.toString(2).padStart(n, '0').split('')
      return text.split('').map((c,j) => binary[j] === '1' ?  c+char : c).join('')
    })
}

console.log(interject('hello','.'))

// prints:
// [
//   'hello',    'hell.o',
//   'hel.lo',   'hel.l.o',
//   'he.llo',   'he.ll.o',
//   'he.l.lo',  'he.l.l.o',
//   'h.ello',   'h.ell.o',
//   'h.el.lo',  'h.el.l.o',
//   'h.e.llo',  'h.e.ll.o',
//   'h.e.l.lo', 'h.e.l.l.o'
// ]