#/*********************************************************** # permnum.rb -- 界误 #***********************************************************/ # 极脸眶との陵高恃垂 N = 4 $a = [] def encode c = 0 N.downto(2) do |i| k = 1 for j in 2..i if ($a[j] > $a[k]); k = j; end end t = $a[i]; $a[i] = $a[k]; $a[k] = t c = c * i + k - 1 end return c end def decode(c) for i in 2..N k = c % i + 1; c /= i t = $a[i]; $a[i] = $a[k]; $a[k] = t end end def nextperm $a[0] = 0; # 戎客 i = N - 1 while ($a[i] >= $a[i + 1]); i -= 1; end if (i == 0); return 0; end # 窗位 j = N while ($a[i] >= $a[j]); j -= 1; end t = $a[i]; $a[i] = $a[j]; $a[j] = t i += 1; j = N while (i < j) t = $a[i]; $a[i] = $a[j]; $a[j] = t; i += 1; j -= 1 end return 1; # 踏位 end def show(count) printf("%5d: ", count) for i in 1..N; printf("%4d", $a[i]); end printf("\n") end count = 0 for i in 1..N; $a[i] = i; end begin count += 1 show(count) printf("code = %d\n", c = encode) show(count) decode(c) show(count) printf("\n") end while (nextperm() == 1) exit 0