Created
January 14, 2015 13:35
-
-
Save theeluwin/fcbad2f31c5e9168eac5 to your computer and use it in GitHub Desktop.
Simple integer sorting algorithm based on infinite monkey theorem (http://en.wikipedia.org/wiki/Infinite_monkey_theorem).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| # -*- coding: utf-8 -*- | |
| import random | |
| import unittest | |
| def infinite_monkey_sort(numbers): | |
| length = len(str(numbers)) | |
| while True: | |
| monkey_output = ''.join([chr(int(random.random() * 255)) for i in range(length)]) | |
| if monkey_output[0] != '[' or monkey_output[-1] != ']': | |
| continue | |
| if len([comma for comma in monkey_output if comma == ',']) != len(numbers) - 1: | |
| continue | |
| monkey_array = monkey_output[1:-1].replace(' ', '').split(',') | |
| if len([digit for digit in monkey_array if digit.isdigit()]) != len(monkey_array): | |
| continue | |
| monkey_array = [int(digit) for digit in monkey_array] | |
| sorted = True | |
| for index in range(1, len(monkey_array)): | |
| if monkey_array[index - 1] > monkey_array[index]: | |
| sorted = False | |
| break | |
| if sorted: | |
| return monkey_array | |
| class TestSorted(unittest.TestCase): | |
| def setUp(self): | |
| self.numbers = range(4) | |
| random.shuffle(self.numbers) | |
| def test_sorted(self): | |
| self.assertEqual(infinite_monkey_sort(self.numbers), [0, 1, 2, 3]) | |
| if __name__ == '__main__': | |
| unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment