Dashboard - Qualification Round 2009 - Google Code Jam
Once the dictionary of all the words in the alien language was built, the next breakthrough was to discover that the aliens have been transmitting messages to Earth for the past decade. Unfortunately, these signals are weakened due to the distance between our two planets and some of the words may be misinterpreted. In order to help them decipher these messages, the scientists have asked you to devise an algorithm that will determine the number of possible interpretations for a given pattern.
A pattern consists of exactly L tokens. Each token is either a single lowercase letter (the scientists are very sure that this is the letter) or a group of unique lowercase letters surrounded by parenthesis ( and ). For example: (ab)d(dc) means the first letter is either a or b, the second letter is definitely d and the last letter is either d or c. Therefore, the pattern (ab)d(dc) can stand for either one of these 4 possibilities: add, adc, bdd, bdc.
X. Using regulare expression:
http://anuj-mehta.blogspot.com/2010/04/code-jam-alien-language-solution.html
http://stevekrenzel.com/articles/alien-language
First we store all the words in a 2 dimensional array.
After that, we read each pattern, parse it, and count how many words match.
One possible way of storing a pattern is a 2 dimensional array P[15][26]. P[i][j] is True only if the i-th token contains the j-th letter of the alphabet, otherwise False. In other words, P[i] is a bitmap of the letters contained by the i-th token.
Parsing can be done like this:
- read one character c
- if c is '(', read characters until we hit ')'. The characters read are the token.
else the token is the character c
- populate P[i] for the characters in the token
To count how many words match, we make sure that each letter i from the word is contained in the bitmap P[i].
Total complexity is O(N * L * D).
http://blog.csdn.net/u013301594/article/details/17623077
http://codecrack52.blogspot.com/2015/03/google-code-jam-alien-language.html
public void solve() throws Exception {
int len = iread();
int n = iread();
int tests = iread();
String words[] = new String[n];
for( int i = 0; i < n; i++) {
words[i] = readword();
}
for( int i = 0; i < tests; i++) {
boolean cand[] = new boolean[n];
Arrays.fill(cand,true);
String pat = readword();
int curPos = 0;
for( int j = 0; j < len; j++) {
String match = "";
if( pat.charAt(curPos) == '(') {
int temp = curPos + 1;
while( pat.charAt(temp) != ')') {
temp++;
}
match = pat.substring(curPos+1, temp);
curPos = temp + 1;
} else {
match = "" + pat.charAt(curPos);
curPos++;
}
for( int t = 0; t < n; t++) {
boolean flag = false;
for( int k = 0; k < match.length(); k++) {
if( words[t].charAt(j) == match.charAt(k)) flag = true;
}
cand[t] = cand[t] & flag;
}
}
int result = 0;
for( int j = 0; j < words.length; j++) {
if( cand[j] ) result++;
}
out.write("Case #" + (i+1) + ": " + result + "\n");
}
}
private void solve() {
int l = nextInt();
int d = nextInt();
int n = nextInt();
String[] words = new String[d];
for (int i = 0; i < d; i++) {
words[i] = nextToken();
}
for (int k = 0; k < n; k++) {
char[] chars = nextToken().toCharArray();
StringBuilder pattern = new StringBuilder();
pattern.append('^');
for (char c : chars) {
if (c == '(') {
pattern.append('[');
} else if (c == ')') {
pattern.append(']');
} else {
pattern.append(c);
}
}
pattern.append('$');
int result = 0;
Pattern p = Pattern.compile(pattern.toString());
for (int i = 0; i < d; i++) {
if (p.matcher(words[i]).matches()) {
result++;
}
}
out.println("Case #" + (k + 1) + ": " + result);
}
}
}
Read full article from Dashboard - Qualification Round 2009 - Google Code Jam
Problem
After years of study, scientists at Google Labs have discovered an alien language transmitted from a faraway planet. The alien language is very unique in that every word consists of exactly L lowercase letters. Also, there are exactly D words in this language.Once the dictionary of all the words in the alien language was built, the next breakthrough was to discover that the aliens have been transmitting messages to Earth for the past decade. Unfortunately, these signals are weakened due to the distance between our two planets and some of the words may be misinterpreted. In order to help them decipher these messages, the scientists have asked you to devise an algorithm that will determine the number of possible interpretations for a given pattern.
A pattern consists of exactly L tokens. Each token is either a single lowercase letter (the scientists are very sure that this is the letter) or a group of unique lowercase letters surrounded by parenthesis ( and ). For example: (ab)d(dc) means the first letter is either a or b, the second letter is definitely d and the last letter is either d or c. Therefore, the pattern (ab)d(dc) can stand for either one of these 4 possibilities: add, adc, bdd, bdc.
Input
The first line of input contains 3 integers, L, D and N separated by a space. D lines follow, each containing one word of length L. These are the words that are known to exist in the alien language. N test cases then follow, each on its own line and each consisting of a pattern as described above. You may assume that all known words provided are unique.Input | Output |
3 5 4 | Case #1: 2 |
X. Using regulare expression:
http://anuj-mehta.blogspot.com/2010/04/code-jam-alien-language-solution.html
- public static void main(String[] args) {
- try {
- BufferedReader br = new BufferedReader(new FileReader("Test.txt"));
- String[] arr = br.readLine().split(" ");
- int numOfWords = Integer.parseInt(arr[1]);
- int numOfPatterns = Integer.parseInt(arr[2]);
- List<string> wordList = new ArrayList<string>();
- for(int i =0; i < numOfWords; i++)
- wordList.add(br.readLine());
- List<pattern> patternList = new ArrayList<pattern>();
- for(int i =0; i < numOfPatterns; i++)
- patternList.add(Pattern.compile( br.readLine().replace('(', '[').replace(')', ']')));
- int index = 0;
- for(Pattern p : patternList)
- {
- index++;
- int count = 0;
- for(String word : wordList)
- {
- Matcher m = p.matcher(word);
- if(m.matches())
- count++;
- }
- System.out.println("Case " + index + ": " + count);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
public int checkPattern(ArrayList wordsAL, String pattern) { int res = 0; | |
for(int i=0;i<wordsAL.size();i++) { | |
if(((String) wordsAL.get(i)).matches(pattern.replaceAll("[(]","[").replaceAll("[)]","]"))) res++; | |
} | |
return res; | |
} |
from string import maketrans from sys import stdin from re import findall length = int(stdin.readline().split()[1]) lang = "".join(stdin.readline() for i in range(length)) for i, test in enumerate(stdin.readlines()): test = test.translate(maketrans("()", "[]")) print "Case #%d: %d"%(i, len(findall(test, lang)))X. Official Analysis: https://code.google.com/codejam/contest/90101/dashboard#s=a&a=0
First we store all the words in a 2 dimensional array.
After that, we read each pattern, parse it, and count how many words match.
One possible way of storing a pattern is a 2 dimensional array P[15][26]. P[i][j] is True only if the i-th token contains the j-th letter of the alphabet, otherwise False. In other words, P[i] is a bitmap of the letters contained by the i-th token.
Parsing can be done like this:
- read one character c
- if c is '(', read characters until we hit ')'. The characters read are the token.
else the token is the character c
- populate P[i] for the characters in the token
To count how many words match, we make sure that each letter i from the word is contained in the bitmap P[i].
Total complexity is O(N * L * D).
http://blog.csdn.net/u013301594/article/details/17623077
String[] st = new String(in.readLine()).split("\\s"); int L = new Integer(st[0]); int D = new Integer(st[1]); int N = new Integer(st[2]); char words[][] = new char[D][L]; for (int i = 0; i < D; i++) { words[i] = new String(in.readLine()).toCharArray(); } for (int cases = 1; cases <= N; cases++) { char[] pattern = new String(in.readLine()).toCharArray(); boolean[][] P = new boolean[15][26]; int foundLetter = 0; int pos = 0; while (foundLetter < L) { if (pattern[pos] != '(') { P[foundLetter][pattern[pos] - 'a'] = true; foundLetter++; pos++; } else { while (pattern[++pos] != ')') { P[foundLetter][pattern[pos] - 'a'] = true; } foundLetter++; pos++; } } int result = 0; for (int i = 0; i < D; i++) { boolean match = true; for (int j = 0; j < L; j++) { if (!P[j][words[i][j] - 'a']) { match = false; } } if (match) { result++; } } out.write("Case #" + cases + ": " + result + "\n"); }http://www.andrewnoske.com/wiki/Google_code_jam#GCJ_2009:_Qual_Round_1A._.22Alien_Language.22
const int NUM_LETTERS = 26; const int MAX_CHARS = 50; inline int charToInt(char ch) { // Used to quickly convert our letters (a-z) into an int (0-26). return ((int)ch - int('a')); } int main() { int L, D, N; string line; cin >> L; cin >> D; cin >> N; // Read in first line. //## CREATE DICTIONARY AS A SIMPLE VECTOR: vector<string> dict(D); // Stores our dictionary of valid words... to avoid later "charToInt" calls we could // instead store each as array of bytes (where a=0), but it wouldn't be a huge speedup. for(int d=0; d<D; d++) // Read all dictionary words into vector. cin >> dict[d]; //## CREATE AND ANALYZE UNKNOWN WORD USING A //## BIT ARRAY OF POSSIBLE VALUES FOR EACH LETTER: bool letterOpts[MAX_CHARS][NUM_LETTERS]; // Represents a bit vector of 26 on/off values for each letter position. for(int c=0; c<N; c++) // For each unknown word: { cin >> line; // Read it in as a string. for(int i=0;i<L;i++) // Reset all our letterOpts values to 0. for(int j=0;j<NUM_LETTERS;j++) letterOpts[i][j] = false; //## PROCESS UNKNOWN WORD STRING INTO AN BIT VECTOR OF LETTER OPTIONS: int letterIdx = 0; // Keep track of which letter we're up to. bool insideBracket = false; // Need to keep track of weather we're inside a bracket. for(int i=0; i<line.length(); i++) // For each character in our encoded string (eg: "(ab)c(de)"). { if(line[i] == '(') { // If start bracket: insideBracket = true; } else if(line[i] == ')') { // If end bracket: insideBracket = false; letterIdx++; } else { // If its a letter: int charVal = charToInt(line[i]); letterOpts[letterIdx][charVal] = true; // Turn on the matching value. if(!insideBracket) letterIdx++; } } //## FOR EACH DICTIONARY WORD: CHECK AGAINST OUR LETTER OPTIONS int numPossWords = 0; int i; // Stores the number of valid words matched. for(int d=0; d<D; d++) // For each word in our dictionary: { for(i=0; i<L; i++) { // For each letter in this word: int charVal = charToInt(dict[d][i]); if(letterOpts[i][charVal]==false) // If it doesn't match a possible letter option for this position: break; // break. } if(i==L) // If all letters matched: numPossWords++; // Increment our count. } cout<<"Case #"<<c+1<<": "<<numPossWords<<endl; // Write out result. } return 0; }
http://codecrack52.blogspot.com/2015/03/google-code-jam-alien-language.html
public void solve() throws Exception {
int len = iread();
int n = iread();
int tests = iread();
String words[] = new String[n];
for( int i = 0; i < n; i++) {
words[i] = readword();
}
for( int i = 0; i < tests; i++) {
boolean cand[] = new boolean[n];
Arrays.fill(cand,true);
String pat = readword();
int curPos = 0;
for( int j = 0; j < len; j++) {
String match = "";
if( pat.charAt(curPos) == '(') {
int temp = curPos + 1;
while( pat.charAt(temp) != ')') {
temp++;
}
match = pat.substring(curPos+1, temp);
curPos = temp + 1;
} else {
match = "" + pat.charAt(curPos);
curPos++;
}
for( int t = 0; t < n; t++) {
boolean flag = false;
for( int k = 0; k < match.length(); k++) {
if( words[t].charAt(j) == match.charAt(k)) flag = true;
}
cand[t] = cand[t] & flag;
}
}
int result = 0;
for( int j = 0; j < words.length; j++) {
if( cand[j] ) result++;
}
out.write("Case #" + (i+1) + ": " + result + "\n");
}
}
private void solve() {
int l = nextInt();
int d = nextInt();
int n = nextInt();
String[] words = new String[d];
for (int i = 0; i < d; i++) {
words[i] = nextToken();
}
for (int k = 0; k < n; k++) {
char[] chars = nextToken().toCharArray();
StringBuilder pattern = new StringBuilder();
pattern.append('^');
for (char c : chars) {
if (c == '(') {
pattern.append('[');
} else if (c == ')') {
pattern.append(']');
} else {
pattern.append(c);
}
}
pattern.append('$');
int result = 0;
Pattern p = Pattern.compile(pattern.toString());
for (int i = 0; i < d; i++) {
if (p.matcher(words[i]).matches()) {
result++;
}
}
out.println("Case #" + (k + 1) + ": " + result);
}
}
}
Read full article from Dashboard - Qualification Round 2009 - Google Code Jam