Google Code Jam Problem : Reverse Words : Solution

This is my second code jam solution.
This one was tougher than the last one. The logic seemed simple but it's application in C is a little tricky, considering the fact that C doesn't have much library functions available. You can read the problem description from the zip file which has the solution or directly from this link.

Input

The first line of the input, as always, gives the number of test cases. Every line that follows, has a series of space seperated words forming a framed sentence. Without punctuations. It must also be noted that there are no space characters in the beginning and ending of the sentence.

Output

Output is something simple to define. The sentence should be printed with the reverse order of words. That is, the last word comes first, the second last one comes next and so on.

Solution

The solution would have less code if we were making it in Java or C++. But I am going with C because that's all I have :). Anyway the algorithm should be similar.
  1. Read the test case number.
  2. Read the line of words one by one for each test case.
  3. For each test case, take the words of the string into an array.
  4. Print the words on by one in reverse order from the array.

Code


Functions

count

Returns the number of characters in the given string.

explode

Breaks the string into a series of words and adds them to a new 2D string array. Considers a character for splitting (here space). Parameters include the address of the string that has the actual input, the address of the 2D array, the character based on which the splitting take place and the count of the string array t. It may also be noted that this function also returns the number of words in the string provided.

reverse

The function takes the address of the 2D array and the number of words as parameters. It basically prints the 2D array in reverse order. Returns 1 on success.

empty

This function is introduced to clear a bug. You can understand it easily, if you comment out the line that calls it from the code. It basically empties the array expl. It takes the address of expl array (expt) as parameter.


This solution can be easily rewritten to any other language with less code. Please feel free to ask any doubts in the comments. If you see any bugs in the code just let me know in the comments. Also if you have an easier solution let me know, it'll help me.. For getting the latest updates from BlockCoder follow @Blockcoder on twitter or G+. If you like my post, please feel free to share it. And thanks for reading.

Share this:

, , , ,

CONVERSATION

0 comments :

Post a Comment