Created
May 30, 2012 23:17
-
-
Save jeffreybaird/2839510 to your computer and use it in GitHub Desktop.
Learn to Program Exercise 10.3
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
| @new_array = %w(fun apple dance Zebra goose teenager) | |
| def choose_a_random_word some_array | |
| word = some_array[rand(0...some_array.size)] | |
| some_array.delete_if do |w| | |
| w == word | |
| end | |
| word | |
| end | |
| def shuffle some_array | |
| arr = [] | |
| while some_array.size > 0 | |
| word = choose_a_random_word some_array | |
| arr << word | |
| end | |
| p arr | |
| end | |
| shuffle @new_array |
gstark
commented
May 30, 2012
- The method is #shuffle on an array, but the variable names assume "words" -- There is nothing specific that says I can't supply an array of numbers, or an array of objects, etc. The variable names shouldn't be specific to a type of element. I'd suggest a new name for "word"
- What is the purpose of "arr" in #shuffle? It seems to have no use other than a way to print some result for debugging? I think #shuffle should return the newly shuffled array.
- The supplied array (some_array) is destroyed by shuffle. I don't think the method should do that.
- The algorithm is inefficient for large arrays. The algoritm is O(n^2) because shuffle will make N passes and for each of those choose_a_random_word will make multiple passes (N the first time, N-1 the second time, N-2 the third time, etc.)
- Use #sample to pick a random element from the collection.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment