How do I delete randomly a specified percentage of geometry objects?

A user asked

I'm trying to create a script that will delete a certain percentage of the objects in a scene. I want the objects to be chosen randomly. I want the script to affect only the meshes.

Answer

Here is a possible approach:

SCRIPT

   (
       -- Collect the object of a certain type into an array, for example
       -- this one collects all geometry objects, excluding the target objects
       -- which are of Geometry superClass for pre-MAXScript historical reasons

       candidatesArray = for o in Geometry where classof o != TargetObject collect o

       -- Because you want to remove random objects, but a specified percentage,
       -- it is a good idea to make the decision which objects will be deleted
       -- BEFORE actually deleting any objects.
       -- You can create a second array and fill it up with the actual
       -- objects to be deleted:

       deathRowArray = #() -- init. an empty array
       thePercentage = 50.0 -- define the percentage

       -- Calculate the number of objects to delete:
       numberToDelete = (thePercentage / 100.0 * candidatesArray.count) as integer

       -- Loop until the deathRow array is filled
       -- with the desired number of objects:
       while deathRowArray.count < numberToDelete do
       (
           newIndex = random 1 candidatesArray.count --generate new random index
           --if not already chosen, add it to the deathrow array
           if findItem deathRowArray candidatesArray[newIndex] == 0 do
               append deathRowArray candidatesArray[newIndex]
       )
       delete deathRowArray --finally, delete the collected objects
   )