Write a program which asks us to type in as many words as we want (one
word per line, continuing until we just press Enter on an empty line),
and which then repeats the words back to us in alphabetical order
without using the sort method. It says I shall do it at http://pine.fm/LearnToProgram/?Chapter=07 but I'm stuck.
If I use the sort method, I do it like this:
words = []
while (word = gets.chomp) != ""
words << word
end
puts
puts words.sort
and which then repeats the words back to us in alphabetical order
without using the sort method. It says I shall do it at http://pine.fm/LearnToProgram/?Chapter=07 but I'm stuck.
Pick one (bubble sort is quite easy) and then implement it in ruby.
Or for the beginning, before you try to implement any of those
algorithms, you may try this:
Just image how YOU would sort a pile of cards with those words on
them. What would you do?
Then try to implement it in ruby. The pile is your array. You may (or
not) need another pile, and some basic operations:
remove a card from the stack, and insert it in some other place, and
maybe more. You don't have to make it fast,
or efficient. Just try to make it work anyhow.
If you're stuck, try with small arrays - the smallest one is empty
It's easy to sort an empty array, right? Then try one word.
Still easy. Two words? Three? Four?
After you have done this, look at the "properly designed" algorithms
and try to implement some of them.
Finally you can more-or-less forget about this all and use the sort
method It's always good to know what's
going on under the hood.
Good luck!
Jano
···
On Nov 19, 2007 8:22 PM, Sebastian Hungerecker <sepp2k@googlemail.com> wrote:
Joakim Olsson wrote:
> and which then repeats the words back to us in alphabetical order
> without using the sort method. It says I shall do it at
> Arrays and Iterators - Learn to Program but I'm stuck.
Thanks for the cool answer! However, I must say that I can't solve the
problem yet. I guess I should use the pop method and the <-thingy but I
can't solve it.
sorted=; words.length.times do sorted<<words.delete(words.min) end;
sorted
How can I use that in the code?
It returns the sorted array. You can puts it or do whatever you want with it.
It would be really nice with an example
which I can read and then understand.
words=gets("").split("\n")
sorted=;
# At this point sorted is an emtpy array and words is an unsorted array
# of the words that the user entered.
words.length.times do # Do the following as many times
# as there are items in words.
sorted << words.delete(words.min)
# Take the smallest item in words (words.min),
# delete it from words (words.delete) and then
# put it at the end of sorted (sorted <<)
end
puts sorted # Print the sorted array to the screen