29
3
Is solving Sudoku too hard? Even the brute force version? Here's a coding exercise that's a little easier. I hope. :-P
Write the shortest function to implement bogosort. In specific, your function should:
- Take an array (or your language's equivalent) as input
- Check if its elements are in sorted order; if so, return the array
- If not, shuffle the elements, and start again
The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.
Clarifications: You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)
Just so it's been said, requiring a function that returns something does actually block some answers that might otherwise be interesting/valid approaches. – kojiro – 2013-10-16T12:43:35.620
What are the element types? int or strings? – Alexandru – 2011-02-02T21:39:00.340
@Alexandru: Either is fine. You choose. – Chris Jester-Young – 2011-02-02T21:40:09.473
Adding a custom comparator will increase the code length so a winning entry will not have a custom comparator. I think breaking the tie doesn't make sense. – Alexandru – 2011-02-02T21:57:47.257
@Alexandru: If you have to code your comparison by hand (e.g., in GolfScript), making it support custom comparators is easy. However, your point is generally valid. – Chris Jester-Young – 2011-02-02T21:59:58.240
sorted ascending, descending or either? – Eelvex – 2011-02-02T22:11:37.373
1It's possible that this algorithm can fail when using pseudo random generator. eg when the length of the list exceeds say 2000, there are 2000! states for the list which may exceed the number of interal states of the prng. – gnibbler – 2011-02-02T22:38:47.647
@Eelvex: Either is fine. Indeed, with a custom comparator, changing a
<
to>
is all that's required to change the sort direction. :-) – Chris Jester-Young – 2011-02-02T23:13:29.127@gnibbler: Bogosort is not required to terminate. In fact, its worse case complexity is O(∞), according to Wikipedia. – Chris Jester-Young – 2011-02-02T23:14:56.817
2Yes, the relevant quote from wikipedia "However, if a pseudorandom number generator is used in place of a random source, it may never terminate, since these exhibit long-term cyclic behavior." – gnibbler – 2011-02-02T23:30:12.750
Must we check of the array is sorted prior to shuffling? Or can we initially shuffle then check whether it's sorted? – Nemo157 – 2011-02-03T00:03:20.970
@Nemo157: That is fine too. – Chris Jester-Young – 2011-02-03T00:07:11.327