Dutch national flag problem: Difference between revisions

m
(Add Factor)
m (→‎{{header|AppleScript}}: Tabs -> 4spaces)
Line 317:
 
on DutchNationalFlagProblem(numberOfBalls)
-- A local "owner" for the potentially long 'balls' list. Speeds up references to its items and properties.
script o
property colours : {"red", "white", "blue"}
-- Initialise the balls list with at least one instance of each colour — but not in Dutch flag order!
property balls : reverse of my colours
end script
-- Randomly fill the list from the three colours to the required number of balls (min = 3).
-- The task description doesn't say if there should be equal numbers of each colour, but it makes no difference to the solution.
repeat numberOfBalls - 3 times
set end of o's balls to some item of o's colours
end repeat
log o's balls -- Log the pre-sort order.
-- Custom comparer for the sort. Decides whether or not ball 'a' should go after ball 'b'.
script redsThenWhitesThenBlues
on isGreater(a, b)
return ((a is not equal to b) and ((a is "blue") or (b is "red")))
end isGreater
end script
-- Sort items 1 thru -1 of the balls (ie. the whole list) using the above comparer.
tell sorter to sort(o's balls, 1, -1, {comparer:redsThenWhitesThenBlues})
-- Return the sorted list.
return o's balls
end DutchNationalFlagProblem
 
557

edits