This is the syntax highlighted version of RunLengthEncoder.java.
/*************************************************************************
* Compilation: javac RunLengthEncoder.java CharStdIn.java
* Execution: java RunLengthEncoder < data.txt
*
* Reads in a sequence of 0's and 1's and encodes using RLE.
*
*************************************************************************/
public class RunLengthEncoder {
public static void main(String[] args) {
char last = '0';
int count = 0;
char c;
while (!CharStdIn.isEmpty()) {
c = CharStdIn.readChar();
// new line
if (c == '\n') {
System.out.println("" + count);
count = 0;
last = '0';
}
// validate input
else if ((c != '0') && (c != '1')) {
System.out.println("Invalid input.");
return;
}
// repeated character
else if (c == last) count++;
// changes from 0 to 1 or from 1 to 0
else {
System.out.print(count + " ");
count = 1;
last = c;
}
}
}
}
Last updated: Wed Feb 11 18:05:27 EST 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.