Skip to content

Instantly share code, notes, and snippets.

@kyktommy
Last active December 13, 2015 18:59
Show Gist options
  • Save kyktommy/4959716 to your computer and use it in GitHub Desktop.
Save kyktommy/4959716 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class menu {
public static void main(String[] args) {
HDC hdc = new HDC();
Scanner scanner = new Scanner(System.in);
System.out.print( "Input to encode > " );
String input = scanner.nextLine();
int c = 0;
do {
System.out.println( "------------------------------" );
System.out.println( " 1. Run in one-step-only" );
System.out.println( " 2. Exit" );
System.out.println( "------------------------------" );
System.out.println( "Please input your choice (1-2):" );
c = scanner.nextInt();
if( c == 1 ) {
String encoded = hdc.compress(input);
System.out.println( "The encoded result:" );
System.out.println( encoded );
hdc.echoNodes();
System.out.println( "Statistic" );
System.out.println( "size of input: " + input.length() );
System.out.println( "size of output: " + encoded.length() );
System.out.println( "compression ratio: " + ((float)input.length() - (float)encoded.length())/(float)input.length() + "%");
System.out.println( "average code length: " + (float)encoded.length()/(float)hdc.encodedNodes.size());
System.out.println( "entropy: ");
}
} while( c != 2 );
}
}
class HDC {
List<String> encodedNodes= new ArrayList<String>();
public String compress(String str) {
String result = "";
List<String> nodes= new ArrayList<String>();
Pattern pattern = Pattern.compile("(.)\\1{1,}");
Matcher m = pattern.matcher(str);
int offset = 0;
while( m.find() ) {
int start = m.start();
int end = m.end();
// Ouput non repeat
if( offset < start ) {
nodes.add(str.substring(offset, start));
}
nodes.add(str.substring(start, end));
offset = end;
}
if( offset == 0 ) {
nodes.add(str);
} else if( offset != str.length() ) {
nodes.add(str.substring(offset, str.length()));
}
for( String s : nodes ) {
if(s.isEmpty()) continue;
if(s.length() == 1 || s.charAt(0) != s.charAt(1)) {
String e = "n" + s.length() + s;
result += e;
this.encodedNodes.add(e);
}
else {
String e = "r" + s.length() + s.charAt(0);
result += e;
this.encodedNodes.add(e);
}
};
return result;
}
public void echoNodes() {
System.out.println( "Where" );
for( String s : encodedNodes) {
String code = "";
int number = Integer.parseInt(String.valueOf(s.charAt(1)));
if( s.charAt(0) == 'r' ) {
for( int i = 0; i < number; ++i ) {
code += s.charAt(2);
}
} else if (s.charAt(0) == 'n') {
for( int i = 0; i < number; ++i ) {
code += s.charAt(number + 1);
}
}
System.out.println( s + ":" + code );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment