Thursday, July 17, 2008

Google Code Jam : Qualification Round : Problem # 2

URL:
http://code.google.com/codejam/contest/dashboard?c=agdjb2RlamFtcg8LEghjb250ZXN0cxjqOQw&selected_problem=2&csrfmiddlewaretoken=

Problem Name: Train Timetable
Problem

A train line has two stations on it, A and B. Trains can take trips from A to B or from B to A multiple times during a day. When a train arrives at B from A (or arrives at A from B), it needs a certain amount of time before it is ready to take the return journey - this is the turnaround time. For example, if a train arrives at 12:00 and the turnaround time is 0 minutes, it can leave immediately, at 12:00.

A train timetable specifies departure and arrival time of all trips between A and B. The train company needs to know how many trains have to start the day at A and B in order to make the timetable work: whenever a train is supposed to leave A or B, there must actually be one there ready to go. There are passing sections on the track, so trains don't necessarily arrive in the same order that they leave. Trains may not travel on trips that do not appear on the schedule.

Input


The first line of input gives the number of cases, N. N test cases follow.

Each case contains a number of lines. The first line is the turnaround time, T, in minutes. The next line has two numbers on it, NA and NB. NA is the number of trips from A to B, and NB is the number of trips from B to A. Then there are NA lines giving the details of the trips from A to B.


Each line contains two fields, giving the HH:MM departure and arrival time for that trip. The departure time for each trip will be earlier than the arrival time. All arrivals and departures occur on the same day. The trips may appear in any order - they are not necessarily sorted by time. The hour and minute values are both two digits, zero-padded, and are on a 24-hour clock (00:00 through 23:59).

After these NA lines, there are NB lines giving the departure and arrival times for the trips from B to A.


Output

For each test case, output one line containing "Case #x: " followed by the number of trains that must start at A and the number of trains that must start at B.

Limits

1 ≤ N ≤ 100

Small dataset

0 ≤ NA, NB ≤ 20

0 ≤ T ≤ 5

Large dataset

0 ≤ NA, NB ≤ 100

0 ≤ T ≤ 60

Sample

Input
2
5
3 2
09:00 12:00
10:00 13:00
11:00 12:30
12:02 15:00
09:00 10:30
2
2 0
09:00 09:01
12:00 12:02

Output
Case #1: 2 2
Case #2: 2 0


My Solution:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;


public class TrainTime {


public Long[] countTrains(Integer turnAround,String[] aScheds, String[] bScheds){
Station a = new Station();
for (String s: aScheds){
a.times.add(new Time(s));
}
Station b = new Station();
for (String s: bScheds){
b.times.add(new Time(s));
}
Collections.sort(a.times);
Collections.sort(b.times);
//System.out.println(a.times);
//System.out.println(b.times);
while (a.times.size()+b.times.size()!=0){
Station cur;
Station oth;
if (a.times.size()==0){
cur=b;
oth=a;
} else if (b.times.size()==0){
cur=a;
oth=b;
} else {
cur=a.times.get(0).startTime<b.times.get(0).startTime? a: b;
oth=a.times.get(0).startTime<b.times.get(0).startTime? b: a;
}
//System.out.println("cur = "+cur.times+" "+cur.trains+",oth = "+oth.times+" "+oth.trains);
if (cur.trains.size()!=0&&cur.trains.get(0).willRunAt<=cur.times.get(0).startTime){
Train t=cur.trains.get(0);
cur.trains.remove(0);
t.willRunAt=cur.times.get(0).endTime+turnAround;
oth.trains.add(t);
Collections.sort(oth.trains);
cur.times.remove(0);
} else {
Train t = new Train(cur.times.get(0).endTime+turnAround);
cur.count++;
oth.trains.add(t);
Collections.sort(oth.trains);
cur.times.remove(0);
}

}

return new Long[]{a.count,b.count};
}

public class Station {

public List<Time> times = new ArrayList<Time>();

public List<Train> trains = new ArrayList<Train>();

public long count =0;


}

public class Train implements Comparable<Train>{
public Long willRunAt;

public Train(Long willRunAt){
this.willRunAt=willRunAt;
}
public int compareTo(Train o) {
return this.willRunAt.compareTo(o.willRunAt);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return willRunAt.toString();
}


}

public class Time implements Comparable<Time>{

public Long startTime;

public Long endTime;

public Time(String time){
String[] spls= time.split(" ");
this.startTime=getTime(spls[0]);
this.endTime= getTime(spls[1]);
}

private Long getTime(String t){
String[] spls=t.split(":");
return (Long.valueOf(spls[0])*60)+Long.valueOf(spls[1]);
}

public int compareTo(Time o) {
if (this.startTime.compareTo(o.startTime)!=0){
return this.startTime.compareTo(o.startTime);
} else {
return this.endTime.compareTo(o.endTime);
}
}

/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return startTime+" "+endTime;
}



}

public static void main(String[] args) throws FileNotFoundException{
TrainTime tt = new TrainTime();

Scanner scan = new Scanner(new File("Input.txt"));
PrintWriter pw = new PrintWriter("Output.txt");
Integer count =new Integer(scan.nextLine());
for (int i=0;i<count;i++){
Integer turnAround = new Integer(scan.nextLine());
String[] cs=(scan.nextLine()).split(" ");
Integer aCount = new Integer(cs[0]);
Integer bCount = new Integer(cs[1]);
String[] aScheds = new String[aCount];
String[] bScheds = new String[bCount];
for (int j=0;j<aCount;j++){
aScheds[j]= scan.nextLine();
}
for (int j=0;j<bCount;j++){
bScheds[j]= scan.nextLine();
}
Long[] res = tt.countTrains(turnAround, aScheds, bScheds);
pw.write("Case #"+(i+1)+": "+res[0]+" "+res[1]+"\n");
}
pw.close();
scan.close();


}
}

Google Code Jam : Qualification Round : Problem #1

URL


Problem

The urban legend goes that if you go to the Google homepage and search for "Google", the universe will implode. We have a secret to share... It is true! Please don't try it, or tell anyone. All right, maybe not. We are just kidding.

The same is not true for a universe far far away. In that universe, if you search on any search engine for that search engine's name, the universe does implode!

To combat this, people came up with an interesting solution. All queries are pooled together. They are passed to a central system that decides which query goes to which search engine. The central system sends a series of queries to one search engine, and can switch to another at any time. Queries must be processed in the order they're received. The central system must never send a query to a search engine whose name matches the query. In order to reduce costs, the number of switches should be minimized.

Your task is to tell us how many times the central system will have to switch between search engines, assuming that we program it optimally.

Input

The first line of the input file contains the number of cases, N. N test cases follow.

Each case starts with the number S -- the number of search engines. The next S lines each contain the name of a search engine. Each search engine name is no more than one hundred characters long and contains only uppercase letters, lowercase letters, spaces, and numbers. There will not be two search engines with the same name.

The following line contains a number Q -- the number of incoming queries. The next Q lines will each contain a query. Each query will be the name of a search engine in the case.

Output

For each input case, you should output:

Case #X: Y
where X is the number of the test case and Y is the number of search engine switches. Do not count the initial choice of a search engine as a switch.

Limits

0 < N ≤ 20

Small dataset

2 ≤ S ≤ 10

0 ≤ Q ≤ 100

Large dataset

2 ≤ S ≤ 100

0 ≤ Q ≤ 1000

Sample

Input

2
5
Yeehaw
NSM
Dont Ask
B9
Googol
10
Yeehaw
Yeehaw
Googol
B9
Googol
NSM
B9
NSM
Dont Ask
Googol
5
Yeehaw
NSM
Dont Ask
B9
Googol
7
Googol
Dont Ask
NSM
NSM
Yeehaw
Yeehaw
Googol

Output
Case #1: 1
Case #2: 0

In the first case, one possible solution is to start by using Dont Ask, and switch to NSM after query number 8.
For the second case, you can use B9, and not need to make any switches.

My Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class SearchUniverse {
public int getMin(String[] engines, String[] queries){

List<String> engs = new ArrayList<String>(Arrays.asList(engines));
int index=0;
int switches=0;

while (index<queries.length){
engs.remove(queries[index]);
if (engs.size()==0){
switches++;
engs= new ArrayList<String>(Arrays.asList(engines));
engs.remove(queries[index]);
}
index++;
}


return switches;
}

public static void main(String[] args) throws FileNotFoundException{
SearchUniverse su = new SearchUniverse();
/*System.out.println(su.getMin(new String[]{"Yeehaw",
"NSM",
"Dont Ask",
"B9",
"Googol"}, new String[]{
"Yeehaw",
"Yeehaw",
"Googol",
"B9",
"Googol",
"NSM",
"B9",
"NSM",
"Dont Ask",
"Googol"}));

System.out.println(su.getMin(new String[]{"Yeehaw",
"NSM",
"Dont Ask",
"B9",
"Googol"}, new String[]{
"Googol",
"Dont Ask",
"NSM",
"NSM",
"Yeehaw",
"Yeehaw",
"Googol"}));*/

Scanner scan = new Scanner(new File("Input.txt"));
PrintWriter pw = new PrintWriter("Output.txt");
Integer count =new Integer(scan.nextLine());
for (int i=0;i<count;i++){
Integer sengs = new Integer(scan.nextLine());
String[] engines = new String[sengs];
for (int j=0;j<sengs;j++){
engines[j]=scan.nextLine();
}
Integer ss = new Integer(scan.nextLine());
String[] queries = new String[ss];
for (int j=0;j<ss;j++){
queries[j]=scan.nextLine();
}
pw.write("Case #"+(i+1)+": "+su.getMin(engines, queries)+"\n");
}
pw.close();
scan.close();


}
}

Tuesday, July 15, 2008

Google Code Jam: Triangle Trilemma

Triangle Trilemma

http://code.google.com/codejam/contest/dashboard?c=agdjb2RlamFtcg4LEghjb250ZXN0cxhRDA

Problem

You're interested in writing a program to classify triangles. Triangles can be classified according to their internal angles. If one of the internal angles is exactly 90 degrees, then that triangle is known as a "right" triangle. If one of the internal angles is greater than 90 degrees, that triangle is known as an "obtuse" triangle. Otherwise, all the internal angles are less than 90 degrees and the triangle is known as an "acute" triangle.

Triangles can also be classified according to the relative lengths of their sides. In a "scalene" triangle, all three sides have different lengths. In an "isosceles" triangle, two of the sides are of equal length. (If all three sides have the same length, the triangle is known as an "equilateral" triangle, but you can ignore this case since there will be no equilateral triangles in the input data.)

Your program must determine, for each set of three points, whether or not those points form a triangle. If the three points are not distinct, or the three points are collinear, then those points do not form a valid triangle. (Another way is to calculate the area of the triangle; valid triangles must have non-zero area.) Otherwise, your program will classify the triangle as one of "acute", "obtuse", or "right", and one of "isosceles" or "scalene".

Input

The first line of input gives the number of cases, N. N test cases follow. Each case is a line formatted as

x1 y1 x2 y2 x3 y3

Output

For each test case, output one line containing "Case #x: " followed by one of these strings:

  • isosceles acute triangle
  • isosceles obtuse triangle
  • isosceles right triangle
  • scalene acute triangle
  • scalene obtuse triangle
  • scalene right triangle
  • not a triangle

Limits

1 ≤ N ≤ 100,
x1, y1, x2, y2, x3, y3 will be integers.

Small dataset

0 ≤ x1, y1, x2, y2, x3, y3 ≤ 9

Large dataset

-1000 ≤ x1, y1, x2, y2, x3, y3 ≤ 1000

Sample


Input





Output
8
0 0 0 4 1 2
1 1 1 4 3 2
2 2 2 4 4 3
3 3 3 4 5 3
4 4 4 5 5 6
5 5 5 6 6 5
6 6 6 7 6 8
7 7 7 7 7 7





Case #1: isosceles obtuse triangle
Case #2: scalene acute triangle
Case #3: isosceles acute triangle
Case #4: scalene right triangle
Case #5: scalene obtuse triangle
Case #6: isosceles right triangle
Case #7: not a triangle
Case #8: not a triangle







My Solution:


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class Triangle {

public String classify(String input){
String[] spl = input.split(" ");
long x1 = new Integer(spl[0]);
long y1 = new Integer(spl[1]);
long x2 = new Integer(spl[2]);
long y2 = new Integer(spl[3]);
long x3 = new Integer(spl[4]);
long y3 = new Integer(spl[5]);

StringBuffer sb = new StringBuffer();

if ((y2-y1)*(x3-x1)==(y3-y1)*(x2-x1)) return "not a triangle";

long s12= (long)(Math.pow(x2-x1, 2)+Math.pow(y2-y1, 2));

long s23= (long)(Math.pow(x3-x2, 2)+Math.pow(y3-y2, 2));

long s13= (long)(Math.pow(x3-x1, 2)+Math.pow(y3-y1, 2));
if (s12==0||s23==0||s12==0) return "not a triangle";


if (s12==s23||s23==s13||s12==s13)
sb.append("isosceles ");
else
sb.append("scalene ");

long min = Math.min(Math.min(s12, s13),s23);

long max = Math.max(Math.max(s12, s13),s23);

long mid = s12+s23+s13-min-max;

if (min+mid==max) sb.append("right ");

if (min+mid<max) sb.append("obtuse ");

if (min+mid>max) sb.append("acute ");

sb.append("triangle");

return sb.toString();
}

public static void main(String[] args) throws FileNotFoundException {

Triangle an = new Triangle();
System.out.println(an.classify("0 0 0 4 1 2"));
System.out.println(an.classify("1 1 1 4 3 2"));
System.out.println(an.classify("2 2 2 4 4 3"));
System.out.println(an.classify("3 3 3 4 5 3"));
System.out.println(an.classify("4 4 4 5 5 6"));
System.out.println(an.classify("5 5 5 6 6 5"));
System.out.println(an.classify("6 6 6 7 6 8"));
System.out.println(an.classify("7 7 7 7 7 7"));
Scanner scan = new Scanner(new File("Input.txt"));
PrintWriter pw = new PrintWriter("Output.txt");
Integer count =new Integer(scan.nextLine());
for (int i=0;i<count;i++){
pw.write("Case #"+(i+1)+": "+an.classify(scan.nextLine())+"\n");
}
pw.close();
scan.close();
}

}

Alien Numbers

Google Code Jam Link
http://code.google.com/codejam/contest/dashboard?c=agdjb2RlamFtcg4LEghjb250ZXN0cxh5DA

Problem

The decimal numeral system is composed of ten digits, which we represent as "0123456789" (the digits in a system are written from lowest to highest). Imagine you have discovered an alien numeral system composed of some number of digits, which may or may not be the same as those used in decimal. For example, if the alien numeral system were represented as "oF8", then the numbers one through ten would be (F, 8, Fo, FF, F8, 8o, 8F, 88, Foo, FoF). We would like to be able to work with numbers in arbitrary alien systems. More generally, we want to be able to convert an arbitrary number that's written in one alien system into a second alien system.

Input

The first line of input gives the number of cases, N. N test cases follow. Each case is a line formatted as

alien_number source_language target_language

Each language will be represented by a list of its digits, ordered from lowest to highest value. No digit will be repeated in any representation, all digits in the alien number will be present in the source language, and the first digit of the alien number will not be the lowest valued digit of the source language (in other words, the alien numbers have no leading zeroes). Each digit will either be a number 0-9, an uppercase or lowercase letter, or one of the following symbols !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Output

For each test case, output one line containing "Case #x: " followed by the alien number translated from the source language to the target language.

Limits

1 ≤ N ≤ 100.

Small dataset

1 ≤ num digits in alien_number ≤ 4,
2 ≤ num digits in source_language ≤ 16,
2 ≤ num digits in target_language ≤ 16.

Large dataset

1 ≤ alien_number (in decimal) ≤ 1000000000,
2 ≤ num digits in source_language ≤ 94,
2 ≤ num digits in target_language ≤ 94.

Sample


Input

Output
4
9 0123456789 oF8
Foo oF8 0123456789
13 0123456789abcdef 01
CODE O!CDE? A?JM!.

Case #1: Foo
Case #2: 9
Case #3: 10011
Case #4: JAM



import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;


public class AlienNumbers {

public String convert(String input){
String[] sp = input.split(" ");
String sourceLang = sp[1];
String destLang = sp[2];
String number =sp[0];
long exactVal =0;
for (int i=0;i<number.length();i++){
exactVal+=sourceLang.indexOf(number.substring(i, i+1))*Math.pow(sourceLang.length(), number.length()-i-1);
}
StringBuffer sb = new StringBuffer();
for (int i=0;exactVal!=0;i++){
sb.append(destLang.substring((int)(exactVal%destLang.length()),(int)((exactVal%destLang.length())+1)));
exactVal = (long)(exactVal/destLang.length());
}
return sb.reverse().toString();
}

public static void main(String[] args) throws FileNotFoundException {

AlienNumbers an = new AlienNumbers();
System.out.println(an.convert("9 0123456789 oF8"));
System.out.println(an.convert("Foo oF8 0123456789"));
System.out.println(an.convert("13 0123456789abcdef 01"));
System.out.println(an.convert("CODE O!CDE? A?JM!."));
InputStream is = new BufferedInputStream(new FileInputStream("Input.txt"));
Scanner scan = new Scanner(new File("Input.txt"));
PrintWriter pw = new PrintWriter("Output.txt");
Integer count =new Integer(scan.nextLine());
for (int i=0;i<count;i++){
pw.write("Case #"+(i+1)+": "+an.convert(scan.nextLine())+"\n");
}
pw.close();
scan.close();
}
}

Sunday, July 13, 2008

TopCoder Problem

http://www.topcoder.com/stat?c=problem_statement&pm=2922&rd=5855

Problem Statement


The Olympic Games in Athens end tomorrow. Given the results of the olympic disciplines, generate and return the medal table.



The results of the disciplines are given as a String[] results, where each element is in the format "GGG SSS BBB". GGG, SSS and BBB are the 3-letter country codes (three capital letters from 'A' to 'Z') of the countries winning the gold, silver and bronze medal, respectively.



The medal table is a String[] with an element for each country appearing in results. Each element has to be in the format "CCO G S B" (quotes for clarity), where G, S and B are the number of gold, silver and bronze medals won by country CCO, e.g. "AUT 1 4 1". The numbers should not have any extra leading zeros.

Sort the elements by the number of gold medals won in decreasing order. If several countries are tied, sort the tied countries by the number of silver medals won in decreasing order. If some countries are still tied, sort the tied countries by the number of bronze medals won in decreasing order. If a tie still remains, sort the tied countries by their 3-letter code in ascending alphabetical order.

Definition


Class:MedalTable
Method:generate
Parameters:String[]
Returns:String[]
Method signature:String[] generate(String[] results)
(be sure your method is public)



Constraints

-results contains between 1 and 50 elements, inclusive.
-Each element of results is formatted as described in the problem statement.
-No more than 50 different countries appear in results.

Examples

0)

{"ITA JPN AUS", "KOR TPE UKR", "KOR KOR GBR", "KOR CHN TPE"}
Returns:
{ "KOR 3 1 0",
"ITA 1 0 0",
"TPE 0 1 1",
"CHN 0 1 0",
"JPN 0 1 0",
"AUS 0 0 1",
"GBR 0 0 1",
"UKR 0 0 1" }
These are the results of the archery competitions.
1)

{"USA AUT ROM"}
Returns: { "USA 1 0 0",  "AUT 0 1 0",  "ROM 0 0 1" }

2)

{"GER AUT SUI", "AUT SUI GER", "SUI GER AUT"}
Returns: { "AUT 1 1 1",  "GER 1 1 1",  "SUI 1 1 1" }




My Solution:

import java.util.*;

public class MedalTable{
public String[] generate(String[] results){
Map<String,Country> map = new HashMap<String,Country>();
for (int i=0; i<results.length; i++){
String[] cont = results[i].split(" ");
Country cy = map.get(cont[0])!=null? map.get(cont[0]):new Country(cont[0]);
cy.g=cy.g+1;
map.put(cont[0],cy);
Country cy1 = map.get(cont[1])!=null? map.get(cont[1]):new Country(cont[1]);
cy1.s=cy1.s+1;
map.put(cont[1],cy1);
Country cy2 = map.get(cont[2])!=null? map.get(cont[2]):new Country(cont[2]);
cy2.b=cy2.b+1;
map.put(cont[2],cy2);
}

List<Country> list = new ArrayList<Country>();
list.addAll(map.values());
Collections.sort(list);
Collections.reverse(list);
System.out.println(list);
String[] r = new String[list.size()];
for (int i=0;i<list.size();i++){
r[i]=list.get(0).toString();
}
return r;
}

public class Country implements Comparable<Country> {
public int g=0;
public int s=0;
public int b=0;

public String name;

public Country(String name) {
this.name = name;
}
public String toString(){
return name+" "+g+" "+s+" "+b;
}

public int compareTo(Country con){
if (this.g!=con.g) return this.g-con.g;
if (this.s!=con.s) return this.s-con.s;
if (this.b!=con.b) return this.b-con.b;
return con.name.compareTo(this.name);
}
}

public static void main(String[] args){

MedalTable mt = new MedalTable();
mt.generate(new String[]{"ITA JPN AUS", "KOR TPE UKR", "KOR KOR GBR", "KOR CHN TPE"});
mt.generate(new String[]{"USA AUT ROM"});
mt.generate(new String[]{"GER AUT SUI", "AUT SUI GER", "SUI GER AUT"});

}
}

Problem Statement for TallPeople


Problem URL:

http://www.topcoder.com/stat?c=problem_statement&pm=2923&rd=5854

Problem Statement


A group of people stand before you arranged in rows and columns. Looking from above, they form an R by C rectangle of people. You will be given a String[] people containing the height of each person. Elements of people correspond to rows in the rectangle. Each element contains a space-delimited list of integers representing the heights of the people in that row. Your job is to return 2 specific heights in a int[]. The first is computed by finding the shortest person in each row, and then finding the tallest person among them (the "tallest-of-the-shortest"). The second is computed by finding the tallest person in each column, and then finding the shortest person among them (the "shortest-of-the-tallest").

Definition


Class:TallPeople
Method:getPeople
Parameters:String[]
Returns:int[]
Method signature:int[] getPeople(String[] people)
(be sure your method is public)



Constraints

-people will contain between 2 and 50 elements inclusive.
-Each element of people will contain between 3 and 50 characters inclusive.
-Each element of people will be a single space-delimited list of positive integers such that:

1) Each positive integer is between 1 and 1000 inclusive with no extra leading zeros.

2) Each element contains the same number of integers.

3) Each element contains at least 2 positive integers.

4) Each element does not contain leading or trailing whitespace.

Examples

0)

{"9 2 3",
"4 8 7"}
Returns: { 4,  7 }
The heights 2 and 4 are the shortest from the rows, so 4 is the taller of the two. The heights 9, 8, and 7 are the tallest from the columns, so 7 is the shortest of the 3.
1)

{"1 2",
"4 5",
"3 6"}
Returns: { 4,  4 }

2)

{"1 1",
"1 1"}
Returns: { 1,  1 }

My Solution:


public class TallPeople{
public int[] getPeople(String[] people){
int[][] a = new int[people.length][people[0].split(" ").length];
int row=people.length,col=people[0].split(" ").length;
for (int i=0;i< spl =" people[i].split(" j="0;" tallofshort="-1,shortOfTall="Integer.MAX_VALUE;" i="0;i<" s="a[i][0];" j="0;j<" s=" s<" tallofshort="s;" i="0;i<" s="a[0][i];" j="0;j<" s=" s"> a[j][i]?s:a[j][i];
}
if (shortOfTall > s) shortOfTall=s;
}
System.out.println(tallOfShort+" "+shortOfTall);
return new int[]{tallOfShort,shortOfTall};
}

public static void main(String[] args){
TallPeople tp = new TallPeople();
tp.getPeople(new String[]{"9 2 3","4 8 7"});
tp.getPeople(new String[]{"1 2","4 5","3 6"});
tp.getPeople(new String[]{"1 1","1 1"});
}
}

Saturday, July 12, 2008

Problem Statement for BusinessTasks

TopCoder Problem:
http://www.topcoder.com/stat?c=problem_statement&pm=1585&rd=6535

Problem Statement


A busy businessman has a number of equally important tasks which he must accomplish. To decide which of the tasks to perform first, he performs the following operation.

He writes down all his tasks in the form of a circular list, so the first task is adjacent to the last task. He then thinks of a positive number. This number is the random seed, which he calls n. Starting with the first task, he moves clockwise (from element 1 in the list to element 2 in the list and so on), counting from 1 to n. When his count reaches n, he removes that task from the list and starts counting from the next available task. He repeats this procedure until one task remains. It is this last task that he chooses to execute.

Given a String[] list representing the tasks and an int n, return the task which the businessman chooses to execute.


Definition


Class:BusinessTasks
Method:getTask
Parameters:String[], int
Returns:String
Method signature:String getTask(String[] list, int n)
(be sure your method is public)



Constraints

-list will contain between 2 and 50 elements inclusive.
-Each element in list will contain between 1 and 50 characters inclusive.
-Each element in list will contain only characters 'a'-'z'.
-n will be between 1 and 10000000 inclusive.

Examples

0)

{"a","b","c","d"}
2
Returns: "a"
We start counting from a. So a is 1, b is 2. We remove b, so list is now {a,c,d}. We continue from c. So c is 1, d is 2. We remove d, so list is now {a,c}. We continue from a. So a is 1, c is 2. We remove c, and now we are left with the last task a.
1)

{"a","b","c","d","e"}
3
Returns: "d"
We start counting from a. So a is 1, b is 2, c is 3. We remove c, now list = {a,b,d,e}. We continue from d. So d is 1, e is 2, a is 3. We remove a, now list = {b,d,e}. We continue from b. So b is 1, d is 2, e is 3. We remove e, now list = {b,d}. We continue from b. So b is 1, d is 2 and finally b is 3. We remove b, and now we are left with just one task d.
2)

{"alpha","beta","gamma","delta","epsilon"}
1
Returns: "epsilon"

3)

{"a","b"}
1000
Returns: "a"

4)

{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t",
"u","v","w","x","y","z"}
17
Returns: "n"

5)

{"zlqamum","yjsrpybmq","tjllfea","fxjqzznvg","nvhekxr","am","skmazcey","piklp",
"olcqvhg","dnpo","bhcfc","y","h","fj","bjeoaxglt","oafduixsz","kmtbaxu",
"qgcxjbfx","my","mlhy","bt","bo","q"}
9000000
Returns: "fxjqzznvg"


My Solution:


import java.util.*;
public class BusinessTasks{

public String getTask(String[] list, int n){
List l = new ArrayList();
for (String a: list){
l.add(a);
}
int start =0;
while (l.size()!=1){
int index = start + n;
index = index % l.size();
if (index==0) {
index=l.size();
start=0;
} else {
start=index-1;
}
l.remove(index-1);
//System.out.println(l);
}
return l.get(0);
}

public static void main(String[] args){
BusinessTasks bt = new BusinessTasks();
System.out.println(bt.getTask(new String[]{"a","b","c","d"},2));
System.out.println(bt.getTask(new String[]{"a","b","c","d","e"},3));
System.out.println(bt.getTask(new String[]{"alpha","beta","gamma","delta","epsilon"},1));
System.out.println(bt.getTask(new String[]{"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t",
"u","v","w","x","y","z"},17));
System.out.println(bt.getTask(new String[]{"zlqamum","yjsrpybmq","tjllfea","fxjqzznvg","nvhekxr","am","skmazcey","piklp",
"olcqvhg","dnpo","bhcfc","y","h","fj","bjeoaxglt","oafduixsz","kmtbaxu",
"qgcxjbfx","my","mlhy","bt","bo","q"},9000000));
}
}