Reversing Words Order in C++ and Using CMake

Saw this challenge in a job posting, thought I would give it a try. I also set up CMake for the first time to build this project. It worked great. I was able to create the program on my windows machine using the command line as I wanted. I think I like Linux Make a bit better though. I think its a bit simpler. I don’t have a Linux machine set up at the moment, so I am glad I got CMake working.

Challenge: Reversing Words Order

This is a pretty simple challenge. The challenge is to write a program that can take words like this “Keyboard and Mouse” and change it to “Mouse and Keyboard” as the output.

My Code:

#include <iostream>
using namespace std;

char *reverseWordOrder(char *, int);

int main()
{
    const int size = 19;
    char wordsToReverse[size] = "Keyboard and Mouse";
    cout << reverseWordOrder(wordsToReverse, size) << endl;
    return 0;
}

char *reverseWordOrder(char *words, int size)
{
    char *reversedWords = new char[size];
    int cursor = 0;

    for (int i = size; i >= 0; i--)
    {
        if (words[i] == ' ' || i == 0)
        {
            int j = (i == 0) ? i : i + 1;

            while (words[j] != ' ' && words[j] != '\0')
            {
                reversedWords[cursor] = words[j];
                cursor++;
                j++;
            }

            if (cursor < size - 1)
            {
                reversedWords[cursor] = ' ';
                cursor++;
            }
            reversedWords[cursor] = '\0';
        }
    }

    return reversedWords;
} 

Conclusion:

I looked up a solution online after I finished mine. Performance-wise I believe mine would be faster. I choose to navigate backwards through the phrase and grab each word then add it to a new string.

Example: (Note: This example is not exactly what the code is doing)
Input: Keyboard and Mouse
Step1: Get the last word.
Output: Mouse
Step2: Get the next word.
Output: Mouse and
Step3: Get the next word.
Output: Mouse and Keyboard

In the solution I found online here, they reversed each word individually and then reversed the whole phrase. The act of reversing the words and phrase is a smart way of completing the task, but it is more expensive. In this algorithm, it will visit each letter around four times. In my algorithm, it visits each letter two times.

Example: (Note: This example is not exactly what the code is doing)
Input: Keyboard and Mouse
Step1: Reverse each word.
Output: draobyeK dna esuoM
Step2: Reversed the whole phrase.
Output: Mouse and Keyboard

Leave a Reply

Your email address will not be published. Required fields are marked *