递归排列 [英] Recursive permutation

查看:66
本文介绍了递归排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图从 x 长数组/元素集中置换所有可能的 n 位长数字.我想出了一个代码来做到这一点,但是数字是一样的,我该如何防止这种情况发生.我来了(帕斯卡):

So I'm trying to permute all possible n digit long numbers out of x long array/set of elements. I've come up with a code that does that, however the digits are the same, how do I prevent that from happening. Here's my come(Pascal):

program Noname10;

var stop : boolean;
    A : array[1..100] of integer;



function check( n : integer ) : boolean;
begin
    if n = 343 // sets the limit when to stop.
        then check := true
        else check := false;
end;


procedure permute(p,result : integer);
    var i : integer;
begin
    if not stop
        then if p = 0  then
            begin

                WriteLn(result);

                if check(result)
                    then stop := true
            end


        else for i := 1 to 9 do
            begin
                permute(p - 1, 10*result+i);
            end;


end;


begin
  stop := false;
  permute(3,0);
  readln;
end.

推荐答案

这是Prolog中的代码

Here is the code in Prolog

permutate(As,[B|Cs]) :- select(B, As, Bs), permutate(Bs, Cs).
select(A, [A|As], As).
select(A, [B|Bs], [B|Cs]) :- select(A, Bs, Cs).

?- permutate([a,b,c], P).

Pascal 更难.

这是一个有用的算法,您可能想使用.但是它没有经过测试,所以你必须自己调试它.所以你必须知道算法是如何工作的.

Here is an usefull algorithm, you might want to use. But it is not tested, so you have to debug it yourself. So you have to know how the algorithm works.

贝尔置换算法:http://programminggeeks.com/bell-algorithm-for-排列/

procedure permutate(var numbers: array [1..100] of integer; size: integer; 
                    var pos, dir: integer)
begin
  if pos >= size then
  begin
     dir = -1 * dir;
     swap(numbers, 1, 2);
  end
  else if pos < 1 then 
  begin
     dir = -1 * dir;
     swap(numbers, size-1, size);
  end
  else
  begin
     swap(numbers, pos, pos+1);
  end;
  pos = pos + dir;
end;

begin
    var a, b: integer;
    a = 1; b = 1;
    while true do
    begin
       permutate(A, 5, a, b);
       printArray(A, 5);
    end;
end.

这篇关于递归排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆