Re: Randomize order of an array?
Posted by
dscho on
Feb 27, 2009; 10:10pm
URL: http://imagej.273.s1.nabble.com/Randomize-order-of-an-array-tp3693530p3693535.html
Hi,
On Fri, 27 Feb 2009, Mike Myerburg wrote:
> I use a modified version of the BatchProcessFolders Macro to analyze all
> the images in a folder. In order to be as objective as possible, I
> would like to randomize the order that the images are processed (I have
> already blanked out the filename, so I cant cheat that way). Here is a
> snippet of the macro that call sends each file to processFile-
>
> function processFiles(dir) {
> list = getFileList(dir);
> for (i=0; i<list.length; i++) {
> if (endsWith(list[i], "/"))
> processFiles(""+dir+list[i]);
> else {
> showProgress(n++, count);
> path = dir+list[i];
> processFile(path);
> }
> }
> }
>
> The array list then would contain the ordered list of files. Is there a
> way to randomize the order of these file in the array using the macro
> language?
Maybe you want something like this (totally untested):
function randomize(array) {
for (i = 0; i < array.length - 1; i++) {
j = i + floor(random() * (array.length - i));
if (i != j) {
swap = array[j];
array[j] = array[i];
array[i] = swap;
}
}
}
The idea is to iterate over all indices (except the last one), pick a
random index greater or equal to that index, and swap the respective list
items. (You might need to fix the code to implement that idea; as I said,
I did not test.)
You would call the function directly after calling getFileList():
list = randomize(list);
However, I see that you may have subdirectories; you will have to build a
complete list of all files before randomizing in order to get an unbiased
result.
Ciao,
Dscho