康託展開和逆康託展開
標籤(空格分隔): 算法
康託展開
詳述
康託展開的公式是
X=a[n]*(n-1)!+a[n-1]*(n-2)!+...+a[i]*(i-1)!+...+a[1]*0!
其中,ai爲當前未出現的元素中是排在第幾個(從0開始)。
意義
康託展開表示的是當前排列在n個不同元素的全排列中的名次。比如213在這3個數所有排列中排第3。
例子
例如,有一個數組 s = [“A”, “B”, “C”, “D”],它的一個排列 s1 = [“D”, “B”, “A”, “C”],現在要把 s1 映射成 X。
n 指的是數組的長度,也就是4,所以
X(s1) = a4*3! + a3*2! + a2*1! + a1*0!
關鍵問題是 a4、a3、a2 和 a1 等於啥?
a4 = “D” 這個元素在子數組[“D”,”B”,”A”,”C”]中是第幾大的元素。”A”是第0大的元素,”B”是第1大的元素,”C”是第2大的元素,”D”是第3大的元素,所以 a4 = 3。
a3 = “B” 這個元素在子數組[“B”,”A”,”C”]中是第幾大的元素。”A”是第0大的元素,”B”是第1大的元素,”C” 是第2大的元素,所以 a3 = 1。
a2 = “A” 這個元素在子數組 [“A”, “C”] 中是第幾大的元素。”A”是第0大的元素,”C”是第1大的元素,所以 a2 = 0。
a1 = “C” 這個元素在子數組 [“C”] 中是第幾大的元素。”C” 是第0大的元素,所以 a1 = 0。(因爲子數組只有1個元素,所以a1總是爲0)
所以,X(s1) = 3*3! + 1*2! + 0*1! + 0*0! = 20
逆康託展開
詳述
如果已知 s = [“A”, “B”, “C”, “D”],X(s1) = 20,能否推出 s1 = [“D”, “B”, “A”, “C”] 呢?
意義
就是根據某個排列的在總的排列中的名次來確定這個排列。
例子
因爲已知 X(s1) = a4*3! + a3*2! + a2*1! + a1*0! = 20,所以問題變成由 20 能否唯一地映射出一組 a4、a3、a2、a1?如果不考慮 ai 的取值範圍,有
3*3! + 1*2! + 0*1! + 0*0! = 20
2*3! + 4*2! + 0*1! + 0*0! = 20
1*3! + 7*2! + 0*1! + 0*0! = 20
0*3! + 10*2! + 0*1! + 0*0! = 20
0*3! + 0*2! + 20*1! + 0*0! = 20
等等。但是滿足 0 <= ai <= n-1 的只有第一組。可以使用輾轉相除的方法得到 ai,如下圖所示:
代碼實現
# author: jtusta
# contact: [email protected]
# site: http://www.jtahstu.com
# software: RubyMine
# time: 2017/6/8 14:35
class Cantor
@@fac = Array.new 25,0
def initialize(n)
@@fac[0] = 1
for i in 1..n-1
@@fac[i] = @@fac[i-1]*i
end
end
# 康託展開,根據給出的數組,求第多少大
def cantor(list,len)
ans = 0
for i in 0..len-1
cnt = 0
for j in i+1..len-1
if list[j]<list[i]
cnt += 1
end
end
ans += cnt*@@fac[len-i-1]
end
ans
end
# 逆康託展開,根據是多少大,找出數組是多少
def cantorInver(n,len)
subset = [] # 當前剩餘的子集
res = []
for i in 1..len
subset << i
end
i = len
while(i>0)
r = n%@@fac[i-1]
t = n/@@fac[i-1]
n = r
subset = subset.sort()
res << subset[t]
subset.delete(subset[t])
i -= 1
end
res
end
# 生成全排列
def fullPermutation(len)
endf = @@fac[len]-1
for i in 0..endf
print i,'->',cantorInver(i,len)
puts
end
end
end
cantor = Cantor.new(20)
list = [3,2,4,1]
len = 4
p cantor.cantor(list,len)
p cantor.cantorInver(cantor.cantor(list,len),len)
p cantor.fullPermutation(4)
執行結果
/usr/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/jtusta/Documents/Code/Ruby/algorithm/cantor.rb
15
[3, 2, 4, 1]
0->[1, 2, 3, 4]
1->[1, 2, 4, 3]
2->[1, 3, 2, 4]
3->[1, 3, 4, 2]
4->[1, 4, 2, 3]
5->[1, 4, 3, 2]
6->[2, 1, 3, 4]
7->[2, 1, 4, 3]
8->[2, 3, 1, 4]
9->[2, 3, 4, 1]
10->[2, 4, 1, 3]
11->[2, 4, 3, 1]
12->[3, 1, 2, 4]
13->[3, 1, 4, 2]
14->[3, 2, 1, 4]
15->[3, 2, 4, 1]
16->[3, 4, 1, 2]
17->[3, 4, 2, 1]
18->[4, 1, 2, 3]
19->[4, 1, 3, 2]
20->[4, 2, 1, 3]
21->[4, 2, 3, 1]
22->[4, 3, 1, 2]
23->[4, 3, 2, 1]
Process finished with exit code 0