Last active
September 2, 2018 21:25
-
-
Save toby-1-kenobi/2a8c2e01ce952130b9a303b494bf55a4 to your computer and use it in GitHub Desktop.
use two methods that call each other to sort penguins with quicksort in an alternating fashion
This file contains 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
## | |
# This is a demonstration of a valid reason for having two methods that call each other. | |
# It is part of a response to a queuestion online | |
# https://softwareengineering.stackexchange.com/questions/376333/is-2-methods-calling-each-other-code-smell/377660#377660 | |
# | |
# See a video of me making this at https://youtu.be/YugJV21W91A | |
# | |
# we are using recursion to implement quicksort. | |
# The sort is implemented two slightly different ways | |
# and each way calls the other to do the next level down the tree. | |
# | |
# imagine we're sorting penguins by height | |
def quicksort_pop(penguins) | |
return penguins if penguins.length <= 1 | |
pivot = penguins.pop | |
left = [] | |
right = [] | |
while penguins.any? | |
penguin = penguins.pop | |
(penguin < pivot) ? left << penguin : right << penguin | |
end | |
quicksort_shift(left) + [pivot] + quicksort_shift(right) | |
end | |
def quicksort_shift(penguins) | |
return penguins if penguins.length <= 1 | |
pivot = penguins.shift | |
left = [] | |
right = [] | |
while penguins.any? | |
penguin = penguins.shift | |
(penguin < pivot) ? left << penguin : right << penguin | |
end | |
quicksort_pop(left) + [pivot] + quicksort_pop(right) | |
end | |
def get_penguin_heights | |
puts 'Those are nice penguins' | |
puts 'Please tell me each of their heights (comma seperated ints)...' | |
heights = gets.chomp | |
heights.split(',').map{ |height| height.to_i } | |
end | |
def give_sorted_penguins(penguins) | |
puts "thank you! That's an awesome collection of penguins!" | |
puts "BTW, I put them in height order for you:" | |
puts penguins | |
favourite_index = Random.rand(penguins.length) | |
puts "My favourite is the one that's #{penguins[favourite_index]}cm tall," | |
puts 'can I keep him?' | |
end | |
init_penguins = get_penguin_heights | |
sorted_penguins = quicksort_pop(init_penguins) | |
give_sorted_penguins(sorted_penguins) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment