Thursday, January 13, 2011

Facebook Hacker Cup - Studious Student Solution

Here's my solution to the Studious Student problem in the Facebook Hacker Cup in Java


package com.facebook;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class StudiousStudent {

public StudiousStudent(String wordLine) {

ArrayList strings = new ArrayList();
StringTokenizer st = new StringTokenizer(wordLine);
int wordCount = Integer.parseInt(st.nextToken());
while (st.hasMoreTokens())
strings.add(st.nextToken());

String[] stringArray = (String[]) strings.toArray(new String[strings.size()]);
for (int index1 = 0; index1 < wordCount; index1++) {

for (int index2 = 0; index2 < wordCount; index2++) {

if ((stringArray[index1] + stringArray[index2]).compareTo(stringArray[index2] + stringArray[index1]) > 0 && (index1 < index2)) {

String tmp = stringArray[index1];
stringArray[index1] = stringArray[index2];
stringArray[index2] = tmp;

}

}

}
for (int counter = 0; counter < stringArray.length; counter++)
System.out.print(stringArray[counter]);

System.out.println();

}

public static void main(String[] args) {

BufferedReader input = null;
try {

input = new BufferedReader(new FileReader("studiousStudent.txt"));
String inputLine = input.readLine();
Integer wordLineCount = Integer.parseInt(inputLine);
for (int counter = 0; counter < wordLineCount; counter++) {

new StudiousStudent(input.readLine());

}
input.close();

} catch (Exception e) {

System.out.println("e.getMessage():" + e.getMessage());
e.printStackTrace();

}

}

}

No comments: