Glen Morse
Glen Morse

Reputation: 2593

Getting Random number from an array

I have an array

a[1..5] : array of integer;

next I do some checks and set some of the values to 1.

DoesSomeDataCheck()
begin
  ... 
  if True
    a[Count] = 1;
  .....
end

now lets say that made the array values to :

a[1] = 1;
a[2] = 1;
a[3] = 0;
a[4] = 0;
a[5] = 1;

Now i need to get one of these randomly of all the integers that = 1. No idea where to even start this.. but it should return a 1,2,5 in this case. Hope this is clear if not let me know and ill try to explain it better

Upvotes: 1

Views: 876

Answers (2)

Hari Babu Mandala
Hari Babu Mandala

Reputation: 295

Take a dynamic array of integers to maintain indexes whose value is 1.

Var
   indexArray : Array of Integer;
   ..........

Change your DoesSomeDataCheck() as follows,

procedure DoesSomeDataCheck()
begin
  ... 
  if True
  begin
    a[Count] := 1;
    setLength(indexArray, Length(indexArray)+1);
    indexArray[Length(indexArray)-1] := Count;
  end;
  .....
end

Now you can make use of indexArray when ever you want. No need to check again. I hope this would be useful to you.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612834

Create an array to hold indices:

var 
  Indices: array [1..5] of Integer;

And a variable to hold the number of indices that have value 1 in original array:

var
  IndicesCount: Integer;

Initialise:

IndicesCount := 0;
for i := 1 to 5 do 
  if a[i] = 1 then
  begin
    Inc(IndicesCount);
    Indices[IndicesCount] := i;
  end;

Then you can sample randomly with

Assert(IndicesCount>0);
Sample := Indices[1 + Random(IndicesCount)];

Asides:

  1. Zero-based indexing is generally to be preferred. It is more consistent with the RTL and extant libraries.
  2. The array a looks awfully like it's elements should be of type Boolean.
  3. It is conceivable that your code that builds a could instead directly build the Indices array in my answer. If you don't need a for any other purpose, that would be simpler.

Upvotes: 2

Related Questions