Combinatorial mathematics permutation generation algorithm lexicographical order

lexicographical sort generation

Numbers use 1~MAX 

function dfs(n) {
  if (n == MAX) {
    // console.log(a)
    ALL.push(Array.from(a))
    used.delete(a.pop())
    return
  }

  for (let i = 1; i <= MAX; i++) {
    if (!used.has(i)) {
      a.push(i)
      used.add(i)
      dfs(n + 1)
    }
  }

  used.delete(a.pop())
}

 

Incrementing base

Since there are n permutations there are n! , n-digit incrementing base numbers can be arranged one-to-one

 

various conversions

permutation transfer intermediary

intermediary number to permutation

ordinal to intermediate

intermediary number to ordinal number

 

 

let a = []
let MAX = 4
let used = new Set()
let ALL = []

function dfs(n) {
  if (n == MAX) {
    // console.log(a)
    ALL.push(Array.from(a))
    used.delete(a.pop())
    return
  }

  for (let i = 1; i <= MAX; i++) {
    if (!used.has(i)) {
      a.push(i)
      used.add(i)
      dfs(n + 1)
    }
  }

  used.delete(a.pop())
}

// 阶乘
function fac(n) {
  return n < 2 ? 1 : n * fac(n - 1)
}


// 字典序中介数计算
function f1(arr) {
  let ret = []
  for (let i = 0; i < arr.length; i++) {
    let c = 0
    for (let j = i + 1; j < arr.length; j++)
      arr[j] < arr[i] ? c++ : c
    ret[i] = c
  }

  return ret
}

// 字典序求序数
function getM1(arr) {
  return arr.reduce(
    (pre, cur, index) => pre + cur * fac(arr.length - 1 - index),
    0
  )
}


// 字典序序数转中介数
function g1(m) {
  let len = MAX
  while (fac(len) < m)
    len++
  let arr = []
  for (let i = 1; i < len; i++) {
    m = Math.floor(m / i)
    arr.push(Math.floor(m) % (i + 1))
  }
  return arr.reverse()
}

// 中介数转排列
function h1(arr) {
  let used = new Set()
  let ret = []
  for (let i = 0; i < arr.length; i++) {
    let t = arr[i] + 1
    while (used.has(t))
      t++
    ret.push(t)
    used.add(t)
  }
  return ret
}


dfs(0)
for (let i of ALL) {
  console.log(i, f1(i), getM1(f1(i)), g1(getM1(f1(i))), h1(f1(i)))
}
[ 1, 2, 3, 4 ] [ 0, 0, 0, 0 ] 0 [ 0, 0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