A little help, guys.
How do you sort a list according to a certain pattern
An example would be sorting a list of R,W,B where R comes first then W then B.
Something like (sortf '(W R W B R W B B))
to (R R W W W B B B)
Any answer is greatly appreciated.
You just use the built-in sort or the sort you already have and use a custom predicate.
(sort '(W R W B R W B) (follow-order '(R W B)))
;Value 50: (r r w w w b b)
This is a solution without using
sort
or higher order functions. (I.e. no fun at all) This doesn't really sort but it solves your problem without using sort.named let
andcase
are the most exotic forms in this solution.I wouldn't have done it like this unless it's required not to use sort. I think lepple's answer is both elegant and easy to understand.
This solution is
O(n)
so it's probably faster than the others with very large number of balls.Make a lookup eg
Runnable R6RS (IronScheme) solution here: http://eval.ironscheme.net/?id=110
This is a functional version of the Dutch national flag problem. Here are my two cents - using the
sort
procedure withO(n log n)
complexity:Using
filter
withO(4n)
complexity:Using
partition
withO(3n)
complexity::The above solutions are written in a functional programming style, creating a new list with the answer. An optimal
O(n)
, single-pass imperative solution can be constructed if we represent the input as a vector, which allows referencing elements by index. In fact, this is how the original formulation of the problem was intended to be solved:Be aware that the previous solution mutates the input vector in-place. It's quite elegant, and works as expected: