Sunday, August 3, 2008

Problem: MatchMaker

Problem Statement

THIS PROBLEM WAS TAKEN FROM THE SEMIFINALS OF THE TOPCODER INVITATIONAL
TOURNAMENT

DEFINITION
Class Name: MatchMaker
Method Name: getBestMatches
Paramaters: String[], String, int
Returns: String[]
Method signature (be sure your method is public): String[]
getBestMatches(String[] members, String currentUser, int sf);

PROBLEM STATEMENT
A new online match making company needs some software to help find the "perfect couples". People who sign up answer a series of multiple-choice questions. Then, when a member makes a "Get Best Mates" request, the software returns a list of users whose gender matches the requested gender and whose answers to the questions were equal to or greater than a similarity factor when compared to the user's answers.

Implement a class MatchMaker, which contains a method getBestMatches. The method takes as parameters a String[] members, String currentUser, and an int sf:
- members contains information about all the members. Elements of members are
of the form "NAME G D X X X X X X X X X X"
* NAME represents the member's name
* G represents the gender of the current user.
* D represents the requested gender of the potential mate.
* Each X indicates the member's answer to one of the multiple-choice
questions. The first X is the answer to the first question, the second is the
answer to the second question, et cetera.
- currentUser is the name of the user who made the "Get Best Mates" request.
- sf is an integer representing the similarity factor.

The method returns a String[] consisting of members' names who have at least sf identical answers to currentUser and are of the requested gender. The names should be returned in order from most identical answers to least. If two members have the same number of identical answers as the currentUser, the names should be returned in the same relative order they were inputted.

TopCoder will ensure the validity of the inputs. Inputs are valid if all of the following criteria are met:
- members will have between 1 and 50 elements, inclusive.
- Each element of members will have a length between 7 and 44, inclusive.
- NAME will have a length between 1 and 20, inclusive, and only contain uppercase letters A-Z.
- G can be either an uppercase M or an uppercase F.
- D can be either an uppercase M or an uppercase F.
- Each X is a capital letter (A-D).
- The number of Xs in each element of the members is equal. The number of Xs will be between 1 and 10, inclusive.
- No two elements will have the same NAME.
- Names are case sensitive.
- currentUser consists of between 1 and 20, inclusive, uppercase letters, A-Z, and must be a member.
- sf is an int between 1 and 10, inclusive.
- sf must be less than or equal to the number of answers (Xs) of the members.

NOTES
The currentUser should not be included in the returned list of potential mates.


EXAMPLES

For the following examples, assume members =
{"BETTY F M A A C C",
"TOM M F A D C A",
"SUE F M D D D D",
"ELLEN F M A A C A",
"JOE M F A A C A",
"ED M F A D D A",
"SALLY F M C D A B",
"MARGE F M A A C C"}

If currentUser="BETTY" and sf=2, BETTY and TOM have two identical answers and BETTY and JOE have three identical answers, so the method should return {"JOE","TOM"}.

If currentUser="JOE" and sf=1, the method should return {"ELLEN","BETTY","MARGE"}.

If currentUser="MARGE" and sf=4, the method should return [].



import java.util.*;

public class MatchMaker {

public String[] getBestMatches(String[] members, String currentUser, int sf){
String[] names = new String[members.length];
String[] gen = new String[members.length];
String[] pre = new String[members.length];
String[][] ans= new String[members.length][];
int index=-1;
for (int i=0;i<members.length;i++){
String[] spls = members[i].split(" ");
names[i]=spls[0];
gen[i]=spls[1];
pre[i]=spls[2];
ans[i]= new String[spls.length-3];
for (int j=3;j<spls.length;j++){
ans[i][j-3]=spls[j];
}
if (spls[0].equals(currentUser)){
index=i;
}
}
List<String> l = new ArrayList<String>();
for (int i=0;i<members.length;i++){
if (!(names[i].equals(currentUser)) && gen[i].equals(pre[index]) && pre[i].equals(gen[index])){
int count=0;
for (int j=0;j<ans[i].length;j++){
if (ans[i][j].equals(ans[index][j])){
count++;
}
}
if (count>=sf) {
l.add(names[i]);
}
}
}
return l.toArray(new String[0]);
}

public static void main(String[] args){
MatchMaker mm = new MatchMaker();
String[] l = new String[] {
"BETTY F M A A C C",
"TOM M F A D C A",
"SUE F M D D D D",
"ELLEN F M A A C A",
"JOE M F A A C A",
"ED M F A D D A",
"SALLY F M C D A B",
"MARGE F M A A C C"};
System.out.println(Arrays.asList(mm.getBestMatches(l,"BETTY",2)));
System.out.println(Arrays.asList(mm.getBestMatches(l,"JOE",1)));
System.out.println(Arrays.asList(mm.getBestMatches(l,"MARGE",4)));

}
}


Problem: BitFlipper

URL:

http://www.topcoder.com/tc?module=Static&d1=help&d2=sampleProblems

Problem Statement:

Binary strings, as most of us know, are composed solely of 0's and 1's. Sometimes it is necessary to turn all the bits either on (1) or off (0). However, sometimes it is not possible to just pick and flip individual bits. In this hypothetical scenario, it is only possible to flip bits in a contiguous segment which is a subset of the contiguous segment which was flipped immediately prior to it. For example, if bits 2-4 are flipped, it is not legal to flip bits 3-5 next, or bits 1-3. However, bits 3-4 or bits 2-3 would be legal. The first segment to be flipped can be located anywhere in the sequence.

Create a class BitFlipper which contains a method minFlip which determines the minimum number of bits that must be flipped under the above restriction in order to get all the bits set to 0. For purposes of this problem, to flip a bit means to change it from 0 to 1 or from 1 to 0.

DEFINITION

Class: BitFlipper
Method: minFlip
Parameters: String
Returns: int

Method signature (be sure it is declared public): int minFlip (String bits);

TopCoder will ensure the validity of the inputs. Inputs are valid if all of the following criteria are met:
* bits will be between 0 and 50 characters in length, inclusive
* bits will contain only 1's and 0's.

EXAMPLES

Example 1:
bits = "00110".
By flipping bits 3-4, we get "00000". Method returns 2.

Example 2:
bits = "10110"
If we flip bits 1-4, we get "01000". Now we flip bit 2 and get "00000".
Method returns 4 + 1 = 5.

Example 3:
bits = "1001110001"
Flipping bits 1-10 yields "0110001110"
Now, flipping bits 2-9 yields "0001110000"
Again, flipping bits 4-6 yields "0000000000"
Method returns 10 + 8 + 3 = 21.

Example 4:
bits = "10001"
Method returns 8.

Example 5:
bits = "101010101"
Method returns 25.

Example 6:
bits = ""
Method returns 0.


Solution:

public class BitFlipper{

public int minFlip (String bits){
int flip=0;
while (!"".equals(bits))
{
bits=bits.replaceAll("^[0]*","");
bits=bits.replaceAll("[0]*$","");
flip+=bits.length();
StringBuffer sb = new StringBuffer();
for (int i=0;i<bits.length();i++){
String cur = bits.substring(i,i+1);
if ("0".equals(cur)) {
sb.append("1");
} else {
sb.append("0");
}
}
bits=sb.toString();
}
return flip;
}

public static void main(String[] args){
BitFlipper bf = new BitFlipper();
System.out.println(bf.minFlip("00110"));
System.out.println(bf.minFlip("10110"));
System.out.println(bf.minFlip("1001110001"));
System.out.println(bf.minFlip("10001"));
System.out.println(bf.minFlip("101010101"));
System.out.println(bf.minFlip(""));
}
}

TopCoder problem: Palindrome

URL: http://www.topcoder.com/tc?module=Static&d1=help&d2=sampleProblems

Problem Statement
A palindrome is a number that is the same whether it is read from left-to-right or right-to-left. For example, 121 and 34543 are both palindromes. It turns out that nearly every integer can be transformed into a palindrome by reversing its digits and adding it to the original number. If that does not create a palindrome, add the reverse of the new number to itself. A palindrome is created by repeating the process of reversing the number and adding it to itself until the number is a palindrome.

Create a class Transform that contains the method palindrome, which takes a number N that is to be transformed and returns a number that is the resultant palindrome from this process. Of course if N is already a palindrome, return it without changing it. Though it is theorized that all numbers can be transformed to palindromes in this way, some numbers do not converge in a reasonable amount of time. For instance, 196 has been carried out to 26,000 digits without finding a palindrome. So if the method finds that the resultant palindrome must be greater than 1,000,000,000, return the special value -1 instead.

DEFINITION
Class: Transform
Method: palindrome
Parameters: int
Returns: int
Method signature (be sure your method is public): int palindrome(int N);

NOTES
- Leading zeroes are never considered part of a number when it is reversed. For instance, 12's reverse will always be 21 regardless of whether it is represented as 12, 012, or 0012. Examples with leading zeroes use the leading zeroes for clarity only.

TopCoder will ensure the validity of the inputs. Inputs are valid if all of the following criteria are met:
- N will be between 1 and 10000 inclusive.

EXAMPLES
Worked examples:
Example 1: N = 28
28 + 82 = 110
110 + 011 = 121, a palindrome. Return 121

Example 2: N = 51
51 + 15 = 66, a palindrome. Return 66

Further examples:
Example 3: N = 11, return 11
Example 4: N = 607, return 4444
Example 5: N = 196, return -1

Solution:




public class Transform{

public int palindrome(int input){
int max= 1000000000;
if (isP(input)){
return input;
}
while (input<max){
input=input+new Integer(new StringBuffer(""+input).reverse().toString());
if (isP(input)){
return input;
}
}
return -1;
}

public boolean isP(int in){
StringBuffer inp = new StringBuffer(""+in);
return inp.reverse().toString().equals(""+in);
}

public static void main(String[] args){
Transform t = new Transform();
System.out.println(t.palindrome(28));
System.out.println(t.palindrome(51));
System.out.println(t.palindrome(11));
System.out.println(t.palindrome(607));
System.out.println(t.palindrome(196));
}
}

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();
}
}