Leo Baghdass...
1 post
|
Only using the methods from the first 10 chapters of the book, the solution hasn’t come to me. What have you come up with?
|
Tyler Bird
1 post
|
I was on the exact same issue and I’m so pleased with myself that I figured it out I thought I’d share.
Keep in mind, that if you want to solve it yourself this gives you the answer and you should disregard the reply…
NOTE: Remember to uncomment the method you’d prefer to run in the sort method.
def sort an_array
#recursive_sort an_array, [], 0
#iterative_sort an_array, []
end
def iterative_sort unsorted_array, sorted_array
i = 0
loop do
break if unsorted_array.length == 0
score = 0
length = unsorted_array.length
this_word = unsorted_array[i]
# count each time this_word is the smallest & count itself once
unsorted_array.each do |array_word|
if this_word <= array_word
score += 1
end
end
# this_word is the smallest when score == length
if score == length
sorted_array.push(this_word)
unsorted_array.delete(this_word)
i = 0 # start at the beginning of the array next time.
else
i += 1 # increment the array to check the next word.
end
end
sorted_array
end
def recursive_sort unsorted_array, sorted_array, i
return if unsorted_array.length == 0
score = 0
length = unsorted_array.length
this_word = unsorted_array[i]
# count each time this_word is the smallest & count itself once
unsorted_array.each do |array_word|
if this_word <= array_word
score += 1
end
end
# this_word is the smallest when score == length
if score == length
sorted_array.push(this_word)
unsorted_array.delete(this_word)
i = 0
else
i += 1 # increment the array to check the next word.
end
recursive_sort unsorted_array, sorted_array, i
sorted_array
end
messy_array = ['alpha', 'echo', 'delta', 'beta', 'charlie']
puts sort(messy_array)
|