RunLengthEncoder.java


Below is the syntax highlighted version of RunLengthEncoder.java from §1.5 Input and Output.


/******************************************************************************
 *  Compilation:  javac RunLengthEncoder.java
 *  Execution:    java RunLengthEncoder < data.txt
 *  Dependencies: StdIn.java StdOut.java
 *
 *  Reads in a sequence of 0's and 1's and encodes using RLE.
 *
 *  % java RunLengthEncoder
 *  00001111000011111
 *  4 4 4 5
 *
 ******************************************************************************/

public class RunLengthEncoder {

    public static void main(String[] args) {
        char last = '0';
        int count = 0;

        while (!StdIn.isEmpty()) {
            char c = StdIn.readChar();

            // new line
            if (c == '\n') {
                StdOut.println("" + count);
                count = 0;
                last = '0';
            }

            // validate input
            else if ((c != '0') && (c != '1'))
                throw new RuntimeException("Invalid input");

            // repeated character
            else if (c == last) count++;

            // changes from 0 to 1 or from 1 to 0
            else {
                StdOut.print(count + " ");
                count = 1;
                last = c;
            }
        }
        StdOut.println(count);
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:14:17 EDT 2022.