>I need a function which randomly takes a subarray of n elements from a 
given array
 > (where each element of the input array can only be once in the subarray).

>Of course I can just make a while loop, where a random element is each 
>time picked from the input array, but when this element is allready in
>the output array from a previous turn of the loop, this needs to be
>repeated. Maybe this can be quite time consuming

One good idea which someone on this list suggested some time ago was to 
swap the element that you have just found (by random (x), where x 
indicates the number of elements in a zero-based array) with the last 
element in the arraray and reduce x by one for the next time. This 
changes the order of input data of course. Example code below.
hth Malcolm

type
  TIntArray = array of integer;
procedure GetSubset(arr, result: TIntArray);
var
  HighArr,SwapInt,i,j:integer;
begin
  HighArr:=high(arr);
  assert(HighArr>high(result),'Something wrong!');

  for i:=low(result) to high(result) do begin
    j:=random(HighArr+1);
    result[i]:=arr[j];
    SwapInt:=arr[HighArr];
    arr[HighArr]:=arr[j];
    arr[j]:=SwapInt;
    dec(HighArr);
  end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
  a,b : TIntArray;
  i : integer;
  s : string;
begin
  SetLength(a,10);
  for i:=low(a) to high(a) do a[i]:=i;
  SetLength(b,3);
  GetSubSet(a,b);
  s:='';
  for i:=low(b) to high(b)-1 do begin
    s:=s+IntToStr(b[i])+',';
  end;
  s:=s+IntToStr(b[high(b)]);
  ShowMessage(s);
end;
initialization
  randomize;
_______________________________________________
Delphi mailing list -> [email protected]
http://www.elists.org/mailman/listinfo/delphi

Reply via email to