Wednesday, March 9, 2016

Look and say sequence algorithm


/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
 public static String looksay(String s){
  String a = "";
  int count = 0;
  for(int i=0;i<s.length();i++){
   char current = s.charAt(i);
   if(i==0){
    count++;
   }
   else {
    char prev = s.charAt(i-1);
    if(prev == current){
     count++;
    }else {
     a+=count;
     a=a+prev;
     count=1;
     prev=current;
    }
   }
  }
        a+=count;
        a=a+(char)s.charAt(s.length()-1);
  return a;
 }
 
 public static void main (String[] args) throws java.lang.Exception
 {
     String s="1";
     for(int i=0;i<100;i++){
         s=looksay(s);
         System.out.println(s);
     }
 }
}

No comments:

Post a Comment