J : Game of Elves

10Dec13

I recently participated in the Advent Programming Contest 2013 organised by the IEEE Student Branch Klagenfurt (with support from Alpen-Adria-Universität Klagenfurt), wherein – as I’d recently received from Udacity a certificate for Introduction to Programming : Problem Solving with Java (CS046) – I challenged myself to program my solutions to the problems posed by the contest using only Java (I’d used C and C++ when I’d participated in the contest in 2012); I solved eighteen of the problems posed by the contest, achieving a rank of 10th (out of 155 participants).

As submissions of solutions to the contest are now closed, I’m posting here the solutions I submitted to the contest.

Problem (J; easy difficulty):

Game of Elves

When the elves are bored, they play the following game:

  • one elf starts with a sequence of decimal digits, e.g., “122156222”
  • the other elf reads the sequence aloud as “one 1, two 2s, one 1, one 5,one 6, three 2s” and writes down the result as a new number sequence: “112211151632”
  • then the first elf does the same to the sequence provided by the second elf
  • this goes on until at least one elf is bored of the game

Problem

Implement a program that does one iteration in this game. The first line shall given the number of sequences to process followed by exactly this number of lines, each with a sequence of digits to be iterated. Calculate and print the next state for each sequence.

Example

Input

2
1234
11114444

Output

11121314
4144

Solution (J.java):

import java.util.Scanner;

public class J
{
  public static void main( String p[] )
  {
    Scanner s = new Scanner( System.in );
    final int K = s.nextInt();
    s.nextLine();
    for( int i = 0; i < K; i ++ )
      System.out.println( nextSequence( s.nextLine()));
  }

  private static String nextSequence( String p )
  {
    String s = "";
    int k = 1;
    char c = p.charAt( 0 );
    for( int i = 1; i < p.length(); i ++ )
      if( c == p.charAt( i ))
        k ++;
      else
      {
        s += k;
        k = 1;
        s += c;
        c = p.charAt( i );
      }
    s += k;
    s += c;
    return s;
  }
}

Testing:

2
1234
11121314
11114444
4144
Advertisements


No Responses Yet to “J : Game of Elves”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: