views:

310

answers:

3

I have pascal code (programming language actually doesn't mean 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?

A: 

I've answered you already? =S

Alix Axel
Wow ...... I can't believe that this confusing of a question has ever came up before. (It really isn't that confusing, but wow...)
Chacha102
@Chacha102: Actually, the asker is the same. And that is strange...
Alix Axel
It is not what I want actually, because when one array's var changes, it has to change another one. For example when box[1] becomes box[2], box[2] also has to change to box[1]
hey
If the results are unique you can quickly delete all the arrays that have the repeated value. I'm not sure if I'm following.
Alix Axel
Donator, when box[2] becomes box[1] and box[1] must take box[2]'s previous value, the vocabulary word you want is **swap**. The beginning-level classes that you're taking right now are more about learning the vocabulary of the topic fields than about anything else. Without the vocabulary, you won't understand anything, and nobody will understand you, as in today's example of using *possibilities* when you really mean *permutations*.
Rob Kennedy
A: 

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;
Serg
A: 

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)
Graham