// Random Delete — Adobe Illustrator compatible
// Port of randomDelete 1.0 (Ken Frederick / Jolin Masson, scriptographer.org).
//
// WHAT IT DOES: thins out the SELECTION at random. Every selected object is tested on its
// own and deleted when Math.random() <= PERCENTAGE / 100 — so 50 removes about half of the
// selection, 100 removes all of it and 0 removes nothing. WHICH objects fall is random:
// run it twice on the same selection and you get two different results, which is the whole
// point of the original script (irregular, hand-made-looking thinning of a regular grid,
// a scatter of dots, a set of duplicated strokes …).
//
// USE: select the objects, run the script. The whole run is ONE undo step, so a single ⌘Z
// brings back every object it deleted.
//
// THE PERCENTAGE: the Scriptographer original asked for the value in a small dialog before
// running. This script asks the same way, through the ExtendScript prompt() — but the .jsx
// runtime here answers prompts headlessly with the DEFAULT it is given, so the value that
// actually applies is PERCENTAGE below. Change that number (0-100) to change the amount;
// the prompt() call stays, so the day the runtime shows a real dialog the script already
// asks for it and needs no edit.
#target illustrator

var PERCENTAGE = 50;   // 0..100 — the chance that any ONE selected object is deleted

var doc = app.activeDocument;

// Ask for the percentage (headless ⇒ comes back as PERCENTAGE; see the note above).
var answer = prompt('Random Delete — percentage of the selection to delete (0-100):',
                    String(PERCENTAGE));
var percent = parseFloat(answer);
if (isNaN(percent)) percent = PERCENTAGE;
percent = Math.max(0, Math.min(100, percent));

// Snapshot the selection ONCE. doc.selection is a live getter and the loop below deletes
// out of it, so iterating it directly would skip objects.
var sel = doc.selection;
var items = [];
for (var i = 0; sel && i < sel.length; i++) if (sel[i]) items.push(sel[i]);

if (!items.length)
    throw new Error('Random Delete needs a selection: select the objects you want to thin ' +
                    'out, then run the script again.');

var chance = percent / 100;
var removed = 0;
for (var j = 0; j < items.length; j++) {
    // The original test, verbatim: Math.random() <= p/100 deletes the object. The
    // `chance > 0` guard only keeps 0% honest — Math.random() can return exactly 0.
    if (chance > 0 && Math.random() <= chance) {
        items[j].remove();
        removed++;
    }
}

app.redraw();
$.writeln('Random Delete: removed ' + removed + ' of ' + items.length +
          ' selected object(s) at ' + percent + '%.');
