开发者

All array possibilities

开发者 https://www.devze.com 2022-12-16 10:24 出处:网络
I have pascal code (programming language actually doesn\'t m开发者_如何学JAVAean anything): box[1] := 14;box[2] := 2;

I have pascal code (programming language actually doesn't m开发者_如何学JAVAean anything):

box[1] := 14;

box[2] := 2;

box[3] := 4;

box[4] := 5;

box[5] := 6;

box[6] := 8;

I want to get all possibilities. For instance, box[1] = box[6], then box[6] = box[1]. Yes, I can write it by my hand, but I guess I can make it more clever, by loop. Any suggestions?


I have taken the first permutation algorithm I found in wikipedia and implemented it in Delphi (2009); I hope that is what you are looking for:

type
  TIntegerArray = array of Integer;

procedure Permutation(K: Integer; var A: TIntegerArray);
var
  I, J: Integer;
  Tmp: Integer;

begin
  for I:= 2 to Length(A) do begin
    J:= K mod I;
    Tmp:= A[J];
    A[J]:= A[I - 1];
    A[I - 1]:= Tmp;
    K:= K div I;
   end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  K, I: Integer;
  A: TIntegerArray;
  S: string;

begin
  Memo1.Lines.Clear;
  for K:= 0 to 719 do begin
    A:= TIntegerArray.Create(14, 2, 4, 5, 6, 8);
    Permutation(K, A);
    S:= '';
    for I:= 0 to Length(A) - 1 do
      S:= S + Format('%3.d ', [A[I]]);
    Memo1.Lines.Add(S);
  end;
end;


I've answered you already? =S


So basically, you have set of items that can either be included (1) or excluded (0). If you count from 0 to 2^(the number of items)-1, every integer will be a set of bits indicating which items are included.

If you have 7 items, in your loop from 0 to 127 the items chosen are:

x0000000 (loop variable = 0, no items are chosen)
x0000001 (loop variable = 1, item [1] is chosen)
x0000010 (loop variable = 2, item [2] is chosen)
x0000011 (loop variable = 3, items [1] and [2] are chosen)
...
x1111111 (loop variable = 127, items [1], [2], [3], [4], [5], [6], [7] are chosen)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号