The first annual Facebook hackers cup was today. This is a very interesting contest in which Facebook challenges young computer students to solve various algorithmic problems in order to win potentially hefty cash prizes. I went ahead and solved one of the problems and thought I would share my solution with anyone who cared to read.
HOW TO USE:This is for the "Studious Student" problem posed in the contest. Basically you are going to copy the following into a java file named GWStudiousStudent, and then compile and run it on the input.txt file that facebook supplies for the contest. This code will generate output on the console that you can copy and paste into the Facebook popup window.
Note: each person's problem is different and randomly generated!
import java.util.*;
import java.io.*;
public class GWStudiousStudent
{
public GWStudiousStudent()
{
try
{
Scanner myScan = new Scanner(new File("input.txt"));
String trash = myScan.nextLine();
while(myScan.hasNextLine())
{
System.out.println(solveOneLine(myScan.nextLine()));
}
}
catch(FileNotFoundException e)
{
System.out.println("File not Found");
}
}
public String solveOneLine(String oneLine)
{
//Make an array the exact size of the numb of words
int numWords = countWords(oneLine);
String[] loadArray = new String[numWords];
//Scan and put each element in the correct spot
Scanner sc = new Scanner(oneLine);
int trash = sc.nextInt();
for(int x = 0; x < numWords; x ++)
{
loadArray[x] = sc.next();
}
//Sort the array using bubblesort
int n = numWords;
for(int pass = 1; pass < n; pass ++)
{
for(int i = 0; i < n-pass; i++)
{
if((loadArray[i].compareTo(loadArray[i+1]))>0)
{
//swap
String temp = loadArray[i];
loadArray[i] = loadArray[i+1];
loadArray[i+1] = temp;
}
}
}
//Concatenate the array into a string
String concat = "";
for(int x = 0; x < numWords; x ++)
{
concat = concat + loadArray[x];
}
//return the concatination results
return concat;
}
/* INT - countWords
* This method takes in the formatted string
* and returns an int representing the number
* of words found in that string
*////////////////////////////
private int countWords(String theline)
{
int count = Integer.parseInt(theline.substring(0,1));
return count;
}
public static void main (String [] args)
{
GWStudiousStudent obj = new GWStudiousStudent();
}
}
0 comments:
Post a Comment