Random sort demonstration
Dar Scott
dsc at swcp.com
Thu May 23 02:08:15 EDT 2013
This script demonstrates what is going on with random sorts of short lists using this:
sort items of myVar by random( the number of items of myVar)
This is a button script on a stack with a wide field with a scrollbar.
local lineAssignments
on mouseUp
set the cursor to watch
put empty into field 1
put "a,b,c" into original
put 0 into numFirstSame
put 100 into trials
repeat trials times
put original into myVar
put empty into lineAssignments
sort items of myVar by randomLog( the number of items of myVar, each)
delete char -1 of lineAssignments
put "(" & original & ") is assigned (" & lineAssignments & ") and sorted as (" & myVar & ") where the" after field 1
if (item 1 of original) is (item 1 of myVar) then
put " first is same" after field 1
add 1 to numFirstSame
else
put " first is different" after field 1
end if
put return after field 1
end repeat
put round( (numFirstSame/trials) * 100) into percentSame
put "The first was the same " & percentSame & "% of the time" after field 1
set the scroll of field 1 to 999999
end mouseUp
function randomLog pRange, pEach
get random(pRange)
put pEach & "->" & it & comma after lineAssignments
return it
end randomLog
Note that this uses function randomLog() instead of random() so the assignments can be gleamed.
These are the last few lines of a typical output:
(a,b,c) is assigned (a->3,b->2,c->2) and sorted as (b,c,a) where the first is different
(a,b,c) is assigned (a->1,b->2,c->2) and sorted as (a,b,c) where the first is same
(a,b,c) is assigned (a->1,b->2,c->1) and sorted as (a,c,b) where the first is same
(a,b,c) is assigned (a->2,b->2,c->3) and sorted as (a,b,c) where the first is same
The first was the same 53% of the time
I got percentages in the range 45% to 60%. My theory (other email) predicted 52 percent. You can try upping the number of trials and commenting out the per-sort lines, and see what you get.
The problem is equality in the sort. It keeps the same order in comparison of pairs of items. For example, the items sorted in the last case above as though they were 2,2,3. The first item is still first.
So...
Use large values for the argument to random() in random sorts.
Dar
More information about the use-livecode
mailing list