## Google code Jam qualification round 2010 – Reverse Words solution

0 / 992

Below is the problem taken from GC jam qualification round 2010:-

Problem

Given a list of space separated words, reverse the order of the words. Each line of text contains

 1 L

letters and

 1 W

words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.

Input

The first line of input gives the number of cases, N.
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.

Output

For each test case, output one line containing “Case #x: ” followed by the list of words in reverse order.

Limits

Small dataset

N = 5
1 ≤ L ≤ 25

Large dataset

N = 100
1 ≤ L ≤ 1000

Sample

reverse words input

Below is a solution to the problem using node.js. To run this program. install nodejs from here. From the command line, go to the directory where this file is saved, say for eg. readFile.js and type in node readFile.js from the command prompt. It will output data to a file called output.txt and will also print it on screen.

``````fs = require('fs')
if (err) {
return console.log(err);
}

var list_of_strings = data.split("\n"),
result = '', num = 1;

for (var index = 1; index < list_of_strings.length; index++) {
if(list_of_strings[index] && list_of_strings[index].trim()) {
reverse(list_of_strings[index]);
}
}
console.log(result);
fs.writeFile("C:\Users\sgattani\Desktop\output.txt", result, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});

function reverse (str) {
if (str) {
var minLength = str.length/2,
start = 0,
end = str.length - 1,
output = '';

str = str.split(/[ ]+/);
for (var index = str.length-1; index >= 0; index--) {
output += str[index] + " ";
}

result = result + "Case #"+num+': '+output + "\r\n";
num++;
}
}

});``````

The above code starts off reading list of words given in file , splitting the read stream by new line, process one string present per line and reverse words of each of the strings one by one. To reverse words, first each of the strings is split off by whitespaces and stored in an array using javascriptsplit method and then the array is print in reverse order. Each of the array output is written to a file creating a final output file.

Link to the problem is here. 2 set of input files (large and small are as below)

Input set:

B-large-practice

B-small-practice

Output set

output_large

output-small