Idea

- get sequence_number of a alien_number in source alien_language
- by a sequence_number get alien_number in target alien_language

My solution is published below.

Main function is solve.

public class AlienNumbers {

private Scanner scanner;

private PrintWriter writer;

...

public AlienNumbers(InputStream is, OutputStream os) {

scanner = new Scanner(is);

writer = new PrintWriter(os);

}

...

/**

* Solve the problem

*/

public void solve() {

int n = scanner.nextInt();

for (int i = 1; i <= n; i++) {

writer.print("Case #");

writer.print(i + ": ");

char[] alienNumber = scanner.next().toCharArray();

char[] sourceLanguage = scanner.next().toCharArray();

char[] targetLanguage = scanner.next().toCharArray();

// long is enough to store sequence number

// see Long.MAX_VALUE (9223372036854775807 ~ 10^19)

long sequenceNumber = getSequenceNumber(alienNumber, sourceLanguage);

char target[] = getAlienNumber(sequenceNumber, targetLanguage);

writer.println(target);

}

}

/**

* Gets sequence number of a alien_number in alien language

*

* @param alienNumber alien number

* @param alienLanguage alien language

* @return sequence number

*/

private long getSequenceNumber(char[] alienNumber, char[] alienLanguage) {

long result = 0;

for (int i = 0; i < alienNumber.length; i++) {

for (int j = 0; j < alienLanguage.length; j++) {

if (alienNumber[alienNumber.length - i - 1] == alienLanguage[j]) {

result += (long) Math.pow(alienLanguage.length, i) * j;

break;

}

}

}

return result;

}

/**

* Gets alien_number by a sequence number in alien language

*

* @param sequenceNumber sequence number

* @param alienLanguage alien language

* @return alien number

*/

private char[] getAlienNumber(long sequenceNumber, char[] alienLanguage) {

StringBuilder alienNumber = new StringBuilder();

for (int i = (int) log(sequenceNumber, alienLanguage.length); i >= 0; i--) {

long power = (long) Math.pow(alienLanguage.length, i);

int index = (int) (sequenceNumber / power);

alienNumber.append(alienLanguage[index]);

sequenceNumber -= index * power;

}

return alienNumber.toString().toCharArray();

}

/**

* Base based logarithm of number

*

* @param number number

* @param base base

* @return logarithm

*/

private long log(long number, long base) {

return (long) (Math.log(number) / Math.log(base));

}

}

See also other posts in Code Jam

## No comments:

Post a Comment