Recursive permutation

血红的双手。 提交于 2019-12-11 04:17:17

问题


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.

回答1:


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 is much harder.

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.

The Bell Permutation algorithm: http://programminggeeks.com/bell-algorithm-for-permutation/

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.


来源:https://stackoverflow.com/questions/4856615/recursive-permutation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!