Randomly select document from view

My code is working fine but with one problem I can’t get exactly the number of documents that I specified I need to get 28 documents randomly but sometimes I get 23 or 26 or 30… Can someone tell me why? What’s wrong with my code?

For x = 0 To 28

		randomnumber = CLng (totalinView * Rnd())

		Set doc = nav.GetNth(randomnumber).document

		Call doc.Replaceitemvalue( "rank",Null)

		Call doc.Replaceitemvalue( " season", "12" )

		Call doc.Save( True, False)

Next

Subject: Randomly select document from view

As Carl mentioned, you are probably not getting 28 distinct random numbers. There is an off-by-one error as well, since

For x = 0 To 28

actually produces 29 iterations. You’ll need to create a list of random numbers first, making sure that there are 28 of them, all unique, then run through the list to get the corresponding documents. The easiest way to do that is using a List:

Dim entryNumberList List As Long

Dim randomNumber As Long

Dim randomTag As String

Dim entryNumberCount as Integer

entryNumberCount = 0

Do Until entryNumberCount = 28

randomNumber = Clng(totalInView * Rnd()) + 1

randomTag = Cstr(randomNumber)

If Not Iselement entryNumberList(randomTag)

  entryNumberList(randomTag) = randomNumber

  entryNumberCount = entryNumberCount + 1

End If

Loop

Then you can use a Forall on the list to get your documents.

This may not be the most efficient way of doing things, but it is the most readable and maintainable. Changing the range and the number of numbers chosen is very easy, and the time complexity (which should be O(log n)) means that things won’t get out of control slow as the number of choices increases (at least up to the point where new choices are more likely to be hits than misses).

[EDIT: an error in the code could have resulted in a 0 and would have made the last document in the view unreachable; adding one to the truncated random number fixes it.]

Subject: RE: Randomly select document from view

Thank you very much Stan, it worked very well :slight_smile:

Subject: Your code could randomly select the same document multiple times

as you don’t check to see if you have already used the document, so you probably create 28 random numbers but some are probably the same.

Subject: RE: Your code could randomly select the same document multiple times

Some times I got less than 28 and I never got the same documen twice…Even if it’s as you suggest, do you have a solution?