Count and Say


/*Lets write an algorithm that, given an initial value, will produce the next 'count and say' sequence:
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, …
*/

public class CountAndSay{

  public static void main(String[] args){

     System.out.println("Count and Say algorithm");

     System.out.println("next sequence is: " + countAndSay(args[0].toString()));

  }

  public static String countAndSay(String input){

     Boolean change=false;
     String output="";
     int count=1;

     char[] str = input.toCharArray();

     System.out.println("Input is: " + input);

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

       if (i+1<str.length && str[i]==str[i+1]){
          count++;
       }
       else{
          output = output + count + str[i];
          count=1;
       }

     }

     return output;

  }

}

 

 

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 )

Facebook photo

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

Connecting to %s