Monday, August 1, 2011

Algorithm-a-Day : Day 01 : Reversing words in a string.

This seems to come up as an interview question more often than not. Here is the solution in C, Python, and Haskell.

Github :: Reversing words in a string

While the Python solution is pretty trivial, Haskell wins out of the three.
Nothing beats a one-liner built from library functions.
I think there's sense in "Don't reinvent the wheel" except when you're reinventing it as a nice exercise, as I did with the C solution.

EDIT (8/11/2011) : Fixed link, and bug in code.

8 comments:

  1. What if, instead of reversing each word, and then reversing the orders of words (as in your C solution), you created a separate string equal to the length of the initial string, and began copying characters from the end of the initial string to the beginning of the new string?

    ReplyDelete
  2. By the way, I love this idea. I've subscribed to your posts. I hope you keep it up.

    ReplyDelete
  3. @Nick: Thanks for subscribing! I was hoping someone would pay attention to this, haha.

    Let's talk about your suggestion: Wouldn't simply copying everything backwards give you the words spelled backwards as well? We're looking for proper spelling with the order of the words reversed. Check out the Haskell solution, it's probably the easiest to understand.

    ReplyDelete
  4. Ah yes. I wasn't paying enough attention.

    ReplyDelete
  5. https://github.com/fosskers/alg-a-day/blob/master/day01-reverse-words/reverse-words.py

    I believe there's an error here.

    ReplyDelete
  6. @ Yoyokirby: I probably fixed it.

    ReplyDelete
  7. I just realized the link doesn't work. It's your python solution for algorithm day one.

    def reverse_words(line):
    '''Reverses the order of words in a string.'''
    words = items.split()
    words.reverse()
    return ' '.join(words)

    Notice that 'line' never gets used and 'items' is never initialized.

    ReplyDelete