diff --git a/.gitignore b/.gitignore index 32858aa..628792e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,10 @@ # Mobile Tools for Java (J2ME) .mtj.tmp/ +build/* +.gradle/* +*.iml + # Package Files # *.jar *.war diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..c33546c --- /dev/null +++ b/build.gradle @@ -0,0 +1,14 @@ +group 'org' +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +repositories { + mavenCentral() +} + +dependencies { + compile 'org.jetbrains:annotations:15.0' + compile 'com.googlecode.json-simple:json-simple:1.1' + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..0c19db4 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Feb 14 15:03:16 MSK 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-bin.zip diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..91a7e26 --- /dev/null +++ b/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..aec9973 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..bd29227 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'hw02' + diff --git a/src/main/java/sp/StreamSerializable.java b/src/main/java/sp/StreamSerializable.java new file mode 100644 index 0000000..4ea7dcb --- /dev/null +++ b/src/main/java/sp/StreamSerializable.java @@ -0,0 +1,15 @@ +package sp; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +public interface StreamSerializable { + + void serialize(OutputStream out) throws IOException; + + /** + * Replace current state with data from input stream + */ + void deserialize(InputStream in) throws IOException; +} \ No newline at end of file diff --git a/src/main/java/sp/Trie.java b/src/main/java/sp/Trie.java new file mode 100644 index 0000000..4ebfd31 --- /dev/null +++ b/src/main/java/sp/Trie.java @@ -0,0 +1,32 @@ +package sp; + +public interface Trie { + + /** + * Expected complexity: O(|element|) + * @return true if this set did not already contain the specified + * element + */ + boolean add(String element); + + /** + * Expected complexity: O(|element|) + */ + boolean contains(String element); + + /** + * Expected complexity: O(|element|) + * @return true if this set contained the specified element + */ + boolean remove(String element); + + /** + * Expected complexity: O(1) + */ + int size(); + + /** + * Expected complexity: O(|prefix|) + */ + int howManyStartsWithPrefix(String prefix); +} \ No newline at end of file diff --git a/src/main/java/sp/TrieImpl.java b/src/main/java/sp/TrieImpl.java new file mode 100644 index 0000000..9ea972d --- /dev/null +++ b/src/main/java/sp/TrieImpl.java @@ -0,0 +1,208 @@ +package sp; + +import java.io.*; +import java.lang.Character; +import java.lang.ref.WeakReference; +import java.util.HashMap; +import java.util.Map; + +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; + +public class TrieImpl implements Trie, StreamSerializable { + + private final Node root = new Node(); + + @Override + public boolean add(String element) { + Node node = root; + for (char c : element.toCharArray()) { + node = node.getNextNodeOrCreateIfNotExists(c); + } + return changeLeafState(node, true); + } + + @Override + public boolean contains(String element) { + Node node = findNode(element); + return node != null && node.isLeaf(); + } + + @Override + public boolean remove(String element) { + Node node = findNode(element); + return node != null && changeLeafState(node, false); + } + + @Override + public int size() { + return root.getSize(); + } + + @Override + public int howManyStartsWithPrefix(String prefix) { + Node node = findNode(prefix); + return node == null ? 0 : node.getSize(); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof TrieImpl && root.equals(((TrieImpl) obj).root); + } + + @Override + public int hashCode() { + return root.hashCode(); + } + + @Override + public void serialize(OutputStream out) throws IOException { + JSONObject obj = root.toJson(); + out.write(obj.toJSONString().getBytes()); + } + + @Override + public void deserialize(InputStream in) throws IOException { + try { + JSONObject obj = (JSONObject) JSONValue.parseWithException(new InputStreamReader(in)); + root.fromJson(obj, null); + } catch (Exception e) { + throw new IOException("can't parse json", e); + } + } + + private Node findNode(String element) { + Node node = root; + for (char c : element.toCharArray()) { + if (!node.containsKey(c)) return null; + node = node.get(c); + } + return node; + } + + private boolean changeLeafState(Node node, boolean value) { + if (node.isLeaf() == value) return false; + node.setLeaf(value); + + int delta = value ? 1 : -1; + for (Node prev = null; node != null; node = node.getParent()) { + if (prev != null && prev.getSize() == 0) { + node.remove(prev.character); + } + node.setSize(node.getSize() + delta); + prev = node; + } + + return true; + } + + private static class Node { + + private int wordCount = 0; + private boolean isLeaf = false; + private char character = '\n'; + private WeakReference parent = null; + private Map nextNodes = new HashMap<>(); + + public static final String WORD_COUNT = "wordCount"; + public static final String CHARACTER = "character"; + public static final String IS_LEAF = "isLeaf"; + public static final String OTHER = "other"; + + public Node() { + } + + private Node(Node prev, char c) { + parent = new WeakReference<>(prev); + character = c; + } + + public Node get(char key) { + return nextNodes.get(key); + } + + public Node remove(char key) { + return nextNodes.remove(key); + } + + public boolean containsKey(char key) { + return nextNodes.containsKey(key); + } + + public void put(char key, Node value) { + nextNodes.put(key, value); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof Node)) return false; + Node other = (Node) o; + return wordCount == other.wordCount && + isLeaf == other.isLeaf && + character == other.character && + nextNodes.keySet().equals(other.nextNodes.keySet()) && + nextNodes.equals(other.nextNodes); + } + + @Override + public int hashCode() { + return nextNodes.hashCode() + (isLeaf ? 1 : 0); + } + + public void fromJson(JSONObject obj, Node prev) throws Exception { + parent = prev == null ? null : new WeakReference<>(prev); + wordCount = ((Long) obj.get(WORD_COUNT)).intValue(); + isLeaf = (Boolean) obj.get(IS_LEAF); + character = ((String) obj.get(CHARACTER)).charAt(0); + JSONObject other = (JSONObject) obj.get(OTHER); + nextNodes.clear(); + for (Object key : other.keySet()) { + Node node = new Node(); + node.fromJson((JSONObject) other.get(key), this); + put(node.character, node); + } + } + + @SuppressWarnings("unchecked") + public JSONObject toJson() { + JSONObject obj = new JSONObject(); + obj.put(WORD_COUNT, wordCount); + obj.put(IS_LEAF, isLeaf); + obj.put(CHARACTER, Character.toString(character)); + JSONObject other = new JSONObject(); + for (Map.Entry entry : nextNodes.entrySet()) { + other.put(entry.getKey(), entry.getValue().toJson()); + } + obj.put(OTHER, other); + return obj; + } + + public Node getNextNodeOrCreateIfNotExists(char key) { + if (!containsKey(key)) { + put(key, new Node(this, key)); + } + return get(key); + } + + public int getSize() { + return wordCount; + } + + public void setSize(int count) { + wordCount = count; + } + + public Node getParent() { + return parent == null ? null : parent.get(); + } + + public boolean isLeaf() { + return isLeaf; + } + + public void setLeaf(boolean value) { + isLeaf = value; + } + + } +} \ No newline at end of file diff --git a/src/test/java/sp/TrieTest.java b/src/test/java/sp/TrieTest.java new file mode 100644 index 0000000..78f1749 --- /dev/null +++ b/src/test/java/sp/TrieTest.java @@ -0,0 +1,232 @@ +package sp; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; + +import static org.junit.Assert.*; + +public class TrieTest { + + @org.junit.Test + public void testSerialize() throws Exception { + TrieImpl trie = new TrieImpl(); + TrieImpl other = new TrieImpl(); + + other.add(""); + other.add("aa"); + + trie.add(""); + trie.add("aa"); + + assertTrue(trie.equals(other)); + + trie.add("a"); + trie.add("aaa"); + trie.add("aab"); + trie.add("aac"); + trie.add("ab"); + + assertFalse(trie.equals(other)); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + trie.serialize(out); + InputStream in = new ByteArrayInputStream(out.toByteArray()); + other.deserialize(in); + + + assertTrue(trie.equals(other)); + + } + + @org.junit.Test + public void testAdd() throws Exception { + Trie trie = new TrieImpl(); + + assertTrue(trie.add("")); + assertTrue(trie.add("aa")); + assertTrue(trie.add("a")); + assertTrue(trie.add("aaa")); + assertTrue(trie.add("aab")); + assertTrue(trie.add("aac")); + assertTrue(trie.add("ab")); + + assertFalse(trie.add("")); + assertFalse(trie.add("aa")); + assertFalse(trie.add("a")); + assertFalse(trie.add("aaa")); + assertFalse(trie.add("aab")); + assertFalse(trie.add("aac")); + assertFalse(trie.add("ab")); + + trie.remove(""); + trie.remove("aab"); + + assertTrue(trie.add("aaaa")); + assertFalse(trie.add("aaaa")); + + trie.remove("a"); + trie.remove("aa"); + trie.remove("aaa"); + trie.remove("aac"); + trie.remove("ab"); + } + + @org.junit.Test + public void testRemove() throws Exception { + Trie trie = new TrieImpl(); + assertFalse(trie.contains("")); + trie.add(""); + trie.add("aa"); + trie.add("a"); + trie.add("aaa"); + trie.add("aab"); + trie.add("aac"); + trie.add("ab"); + assertTrue(trie.remove("")); + assertTrue(trie.remove("aab")); + trie.add("aaaa"); + assertTrue(trie.remove("a")); + assertTrue(trie.remove("aa")); + assertTrue(trie.remove("aaa")); + assertTrue(trie.remove("aac")); + assertTrue(trie.remove("ab")); + + assertFalse(trie.remove("")); + assertFalse(trie.remove("aab")); + assertFalse(trie.remove("")); + assertFalse(trie.remove("aab")); + assertFalse(trie.remove("a")); + assertFalse(trie.remove("aa")); + assertFalse(trie.remove("aaa")); + assertFalse(trie.remove("aac")); + assertFalse(trie.remove("ab")); + } + + @org.junit.Test + public void testContains() throws Exception { + Trie trie = new TrieImpl(); + assertFalse(trie.contains("")); + trie.add(""); + trie.add("aa"); + trie.add("a"); + trie.add("aaa"); + trie.add("aab"); + trie.add("aac"); + trie.add("ab"); + + assertTrue(trie.contains("")); + assertTrue(trie.contains("aa")); + assertTrue(trie.contains("a")); + assertTrue(trie.contains("aaa")); + assertTrue(trie.contains("aab")); + assertTrue(trie.contains("aac")); + assertTrue(trie.contains("ab")); + + trie.remove(""); + trie.remove("aab"); + + assertFalse(trie.contains("")); + assertTrue(trie.contains("aa")); + assertTrue(trie.contains("a")); + assertTrue(trie.contains("aaa")); + assertFalse(trie.contains("aab")); + assertTrue(trie.contains("aac")); + assertTrue(trie.contains("ab")); + + trie.add("aaaa"); + trie.remove("a"); + trie.remove("aa"); + trie.remove("aaa"); + trie.remove("aac"); + trie.remove("ab"); + + assertFalse(trie.contains("")); + assertFalse(trie.contains("aa")); + assertFalse(trie.contains("a")); + assertFalse(trie.contains("aaa")); + assertFalse(trie.contains("aab")); + assertFalse(trie.contains("aac")); + assertFalse(trie.contains("ab")); + assertTrue(trie.contains("aaaa")); + } + + @org.junit.Test + public void testSize() throws Exception { + Trie trie = new TrieImpl(); + + assertEquals(trie.size(), 0); + trie.add(""); + assertEquals(trie.size(), 1); + trie.add("aa"); + trie.add("a"); + trie.add("aaa"); + assertEquals(trie.size(), 4); + trie.add("aab"); + trie.add("aac"); + trie.add("ab"); + assertEquals(trie.size(), 7); + + trie.remove(""); + trie.remove("aab"); + assertEquals(trie.size(), 5); + + trie.add("aaaa"); + assertEquals(trie.size(), 6); + + trie.remove("a"); + trie.remove("aa"); + trie.remove("aaa"); + assertEquals(trie.size(), 3); + trie.remove("aac"); + trie.remove("ab"); + assertEquals(trie.size(), 1); + + } + + @org.junit.Test + public void testHowManyStartsWithPrefix() throws Exception { + Trie trie = new TrieImpl(); + + assertEquals(trie.howManyStartsWithPrefix(""), 0); + assertEquals(trie.howManyStartsWithPrefix("a"), 0); + assertEquals(trie.howManyStartsWithPrefix("aa"), 0); + assertEquals(trie.howManyStartsWithPrefix("aaa"), 0); + + trie.add(""); + trie.add("aa"); + trie.add("a"); + trie.add("aaa"); + trie.add("aab"); + trie.add("aac"); + trie.add("ab"); + + assertEquals(trie.howManyStartsWithPrefix(""), 7); + assertEquals(trie.howManyStartsWithPrefix("a"), 6); + assertEquals(trie.howManyStartsWithPrefix("aa"), 4); + assertEquals(trie.howManyStartsWithPrefix("aaa"), 1); + + trie.remove(""); + trie.remove("aab"); + + trie.add("aaaa"); + + assertEquals(trie.howManyStartsWithPrefix(""), 6); + assertEquals(trie.howManyStartsWithPrefix("a"), 6); + assertEquals(trie.howManyStartsWithPrefix("aa"), 4); + assertEquals(trie.howManyStartsWithPrefix("aaa"), 2); + + trie.remove("a"); + trie.remove("aa"); + trie.remove("aaa"); + trie.remove("aac"); + trie.remove("ab"); + + assertEquals(trie.howManyStartsWithPrefix(""), 1); + assertEquals(trie.howManyStartsWithPrefix("a"), 1); + assertEquals(trie.howManyStartsWithPrefix("aa"), 1); + assertEquals(trie.howManyStartsWithPrefix("aaa"), 1); + } + + +} \ No newline at end of file