UNB/ CS/ David Bremner/ teaching/ old/ cs1083/ java/ RunLength.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.Scanner;

public class RunLength {
    private int[][] bits;
    private int rows,columns;
    RunLength() throws IOException{
        Scanner sc =
            new Scanner(System.in);
        if (!sc.next().equals("P1"))
            throw new IOException("Format error");
        columns=sc.nextInt();
        rows=sc.nextInt();
        bits=new int[rows][columns];
        for (int i=0; i< rows; i++){
            String line=sc.next();
            for (int j=0; j<columns; j++)
                bits[i][j]=line.charAt(j)-'0';
        }
    }
    public void encode(){
        for (int i=0; i< rows; i++){
            int start=0;
            System.out.print(bits[i][0]);
            while (start<columns){
                int end=findRun(i,start);
                System.out.print(" "+(end-start+1));
                start=end+1;
            }
            System.out.println();
        }
    }
    private int findRun(int inRow, int startCol){
        int value=bits[inRow][startCol];
        int cursor=startCol;

        while(cursor<columns &&
              bits[inRow][cursor] == value)
            cursor++;

        return cursor-1;
    }
    public String toString(){
        String result="";
        for (int i=0; i< rows; i++){
            for (int j=0; j<columns; j++){
                if (bits[i][j]==1)
                    result += "*";
                else
                    result += " ";
            }
            result +="\n";
        }
        return result;

    }
    public static void main(String [] args) throws IOException{

        RunLength rl = new RunLength();
        //      System.out.println(rl);
        rl.encode();
    }
}
//@keywords: array, 2D array, bitmap, file, image processing