Marijus
Marijus

Reputation: 4375

Recursive permutation

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.

Upvotes: 2

Views: 3066

Answers (1)

Anders
Anders

Reputation: 552

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.

Upvotes: 2

Related Questions