From 6629540ca95314ac0988ce0058f72607cb0e0068 Mon Sep 17 00:00:00 2001 From: boshen Date: Wed, 7 Sep 2016 16:45:45 +0800 Subject: [PATCH] add algorithm from ibm pc --- Algorithms/.classpath | 6 + Algorithms/.project | 17 + .../.settings/org.eclipse.jdt.core.prefs | 11 + Algorithms/src/NaiveStringMatching.java | 70 ++ Algorithms/src/WordWrapper.java | 115 +++ Algorithms/src/basic/Bag.java | 85 +++ Algorithms/src/basic/In.java | 694 ++++++++++++++++++ Algorithms/src/basic/Stack.java | 187 +++++ Algorithms/src/basic/StdIn.java | 565 ++++++++++++++ Algorithms/src/basic/StdOut.java | 320 ++++++++ Algorithms/src/basic/StdRandom.java | 534 ++++++++++++++ Algorithms/src/graph/Edge.java | 101 +++ .../EdgeWeightedGraph.java | 209 ++++++ NaiveStringMatching.java | 43 ++ 14 files changed, 2957 insertions(+) create mode 100644 Algorithms/.classpath create mode 100644 Algorithms/.project create mode 100644 Algorithms/.settings/org.eclipse.jdt.core.prefs create mode 100644 Algorithms/src/NaiveStringMatching.java create mode 100644 Algorithms/src/WordWrapper.java create mode 100644 Algorithms/src/basic/Bag.java create mode 100644 Algorithms/src/basic/In.java create mode 100644 Algorithms/src/basic/Stack.java create mode 100644 Algorithms/src/basic/StdIn.java create mode 100644 Algorithms/src/basic/StdOut.java create mode 100644 Algorithms/src/basic/StdRandom.java create mode 100644 Algorithms/src/graph/Edge.java create mode 100644 Algorithms/src/minimalSpanningTree/EdgeWeightedGraph.java create mode 100644 NaiveStringMatching.java diff --git a/Algorithms/.classpath b/Algorithms/.classpath new file mode 100644 index 0000000..fb565a5 --- /dev/null +++ b/Algorithms/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/Algorithms/.project b/Algorithms/.project new file mode 100644 index 0000000..863d6ff --- /dev/null +++ b/Algorithms/.project @@ -0,0 +1,17 @@ + + + Algorithms + + + + + + org.eclipse.jdt.core.javabuilder + + + + + + org.eclipse.jdt.core.javanature + + diff --git a/Algorithms/.settings/org.eclipse.jdt.core.prefs b/Algorithms/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..7341ab1 --- /dev/null +++ b/Algorithms/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,11 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/Algorithms/src/NaiveStringMatching.java b/Algorithms/src/NaiveStringMatching.java new file mode 100644 index 0000000..a078f38 --- /dev/null +++ b/Algorithms/src/NaiveStringMatching.java @@ -0,0 +1,70 @@ +import java.util.ArrayList; + + +public class NaiveStringMatching{ + + public static ArrayList nativeStringMatching(String mother, String son){ + ArrayList index = new ArrayList(); + if (mother.isEmpty() || son.isEmpty()||son.length()> mother.length()){ + index.add(-1); + return index; + } + + int m = mother.length(); + int n = son.length(); + + for(int i=0;i nativeStringMatching_PatternHasDifferentChar(String mother, String son){ + ArrayList index = new ArrayList(); + if (mother.isEmpty() || son.isEmpty()||son.length()> mother.length()){ + index.add(-1); + return index; + } + + int m = mother.length(); + int n = son.length(); + int step=0; + for(int i=0;i result = nativeStringMatching(mother, son); + for(int i:result){ + System.out.println(i); + } + +} + +} + + diff --git a/Algorithms/src/WordWrapper.java b/Algorithms/src/WordWrapper.java new file mode 100644 index 0000000..dee10b5 --- /dev/null +++ b/Algorithms/src/WordWrapper.java @@ -0,0 +1,115 @@ +import java.util.ArrayList; + +// input String[], line length n +// output lines + +public class WordWrapper{ + + private String[] sentense; + private int n; + private ArrayList> context = new ArrayList>(); + + + public WordWrapper(String[] input, int len){ + sentense = input; + n = len; + System.out.println("Input String array is " + sentense); + System.out.println("Input each line length is " + n); + } + + + + + public ArrayList> dp(){ + // minimal raggedness + context = new ArrayList>(); + return context; + } + + + + + + + + + + + + + + + + + public ArrayList> greedy(){ + // minimal number of lines; + context = new ArrayList>(); + System.out.println("Using greedy method to assign each line: "); + if ((sentense.length==0)||(sentense==null)){ + return context; + } + + int n_words=0; + + // while there are words left + while(n_words newLine = new ArrayList(); + + // assemble new words in each line + while(++current_len + sentense[n_words].length() sentense : context){ + int cur_len=-1; + int count = 0; + for(String word : sentense){ + cur_len++; + count++; + System.out.print(word); + cur_len+=word.length(); + if (count==sentense.size()){ + if(cur_len==n){ + break; + } + else{ + for(int i=0;i implements Iterable { + + private Node first; //first element + private int n; //number + + private static class Node{ + private Item item; + private Node next; + } + + public Bag(){ + n = 0; + first = null; + } + + public boolean isEmpty(){ + return first== null; + } + + + public int size(){ + return n; + } + + + public void add(Item item){ + Node oldfirst = first; + first = new Node(); + first.next = oldfirst; + first.item = item; + n++; + } + @Override + public Iterator iterator() { + + return new ListIterator(first); + } + + + private class ListIterator implements Iterator{ + + private Node current; + public ListIterator(Node first){ + current = first; + } + @Override + public boolean hasNext() { + + return current!=null; + } + + @Override + public Item next() { + if(!hasNext()){throw new NoSuchElementException();} + Item item = current.item; + current = current.next; + return item; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + } + + public static void main(String[] args){ + + Bag bag = new Bag(); + while(!StdIn.isEmpty()){ + String item = StdIn.readString(); + bag.add(item); + } + StdOut.println("size of bag = " + bag.size()); + for(String s : bag){ + StdOut.println(s); + } + } + +} diff --git a/Algorithms/src/basic/In.java b/Algorithms/src/basic/In.java new file mode 100644 index 0000000..59fdf7e --- /dev/null +++ b/Algorithms/src/basic/In.java @@ -0,0 +1,694 @@ +package basic; + + +/****************************************************************************** + * Compilation: javac In.java + * Execution: java In (basic test --- see source for required files) + * Dependencies: none + * + * Reads in data of various types from standard input, files, and URLs. + * + ******************************************************************************/ + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.Socket; +// import java.net.HttpURLConnection; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.InputMismatchException; +import java.util.Locale; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.regex.Pattern; + +/** + * Input. This class provides methods for reading strings + * and numbers from standard input, file input, URLs, and sockets. + *

+ * The Locale used is: language = English, country = US. This is consistent + * with the formatting conventions with Java floating-point literals, + * command-line arguments (via {@link Double#parseDouble(String)}) + * and standard output. + *

+ * For additional documentation, see + * Section 3.1 of + * Introduction to Programming in Java: An Interdisciplinary Approach + * by Robert Sedgewick and Kevin Wayne. + *

+ * Like {@link Scanner}, reading a token also consumes preceding Java + * whitespace, reading a full line consumes + * the following end-of-line delimeter, while reading a character consumes + * nothing extra. + *

+ * Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines + * consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085; + * see + * Scanner.java (NB: Java 6u23 and earlier uses only \r, \r, \r\n). + * + * @author David Pritchard + * @author Robert Sedgewick + * @author Kevin Wayne + */ +public final class In { + + ///// begin: section (1 of 2) of code duplicated from In to StdIn. + + // assume Unicode UTF-8 encoding + private static final String CHARSET_NAME = "UTF-8"; + + // assume language = English, country = US for consistency with System.out. + private static final Locale LOCALE = Locale.US; + + // the default token separator; we maintain the invariant that this value + // is held by the scanner's delimiter between calls + private static final Pattern WHITESPACE_PATTERN + = Pattern.compile("\\p{javaWhitespace}+"); + + // makes whitespace characters significant + private static final Pattern EMPTY_PATTERN + = Pattern.compile(""); + + // used to read the entire input. source: + // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html + private static final Pattern EVERYTHING_PATTERN + = Pattern.compile("\\A"); + + //// end: section (1 of 2) of code duplicated from In to StdIn. + + private Scanner scanner; + + /** + * Initializes an input stream from standard input. + */ + public In() { + scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME); + scanner.useLocale(LOCALE); + } + + /** + * Initializes an input stream from a socket. + * + * @param socket the socket + * @throws IllegalArgumentException if cannot open {@code socket} + * @throws NullPointerException if {@code socket} is {@code null} + */ + public In(Socket socket) { + if (socket == null) throw new NullPointerException("argument is null"); + try { + InputStream is = socket.getInputStream(); + scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME); + scanner.useLocale(LOCALE); + } + catch (IOException ioe) { + throw new IllegalArgumentException("Could not open " + socket); + } + } + + /** + * Initializes an input stream from a URL. + * + * @param url the URL + * @throws IllegalArgumentException if cannot open {@code url} + * @throws NullPointerException if {@code url} is {@code null} + */ + public In(URL url) { + if (url == null) throw new NullPointerException("argument is null"); + try { + URLConnection site = url.openConnection(); + InputStream is = site.getInputStream(); + scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME); + scanner.useLocale(LOCALE); + } + catch (IOException ioe) { + throw new IllegalArgumentException("Could not open " + url); + } + } + + /** + * Initializes an input stream from a file. + * + * @param file the file + * @throws IllegalArgumentException if cannot open {@code file} + * @throws NullPointerException if {@code file} is {@code null} + */ + public In(File file) { + if (file == null) throw new NullPointerException("argument is null"); + try { + // for consistency with StdIn, wrap with BufferedInputStream instead of use + // file as argument to Scanner + FileInputStream fis = new FileInputStream(file); + scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME); + scanner.useLocale(LOCALE); + } + catch (IOException ioe) { + throw new IllegalArgumentException("Could not open " + file); + } + } + + + /** + * Initializes an input stream from a filename or web page name. + * + * @param name the filename or web page name + * @throws IllegalArgumentException if cannot open {@code name} as + * a file or URL + * @throws NullPointerException if {@code name} is {@code null} + */ + public In(String name) { + if (name == null) throw new NullPointerException("argument is null"); + try { + // first try to read file from local file system + File file = new File(name); + if (file.exists()) { + // for consistency with StdIn, wrap with BufferedInputStream instead of use + // file as argument to Scanner + FileInputStream fis = new FileInputStream(file); + scanner = new Scanner(new BufferedInputStream(fis), CHARSET_NAME); + scanner.useLocale(LOCALE); + return; + } + + // next try for files included in jar + URL url = getClass().getResource(name); + + // or URL from web + if (url == null) { + url = new URL(name); + } + + URLConnection site = url.openConnection(); + + // in order to set User-Agent, replace above line with these two + // HttpURLConnection site = (HttpURLConnection) url.openConnection(); + // site.addRequestProperty("User-Agent", "Mozilla/4.76"); + + InputStream is = site.getInputStream(); + scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME); + scanner.useLocale(LOCALE); + } + catch (IOException ioe) { + throw new IllegalArgumentException("Could not open " + name); + } + } + + /** + * Initializes an input stream from a given {@link Scanner} source; use with + * {@code new Scanner(String)} to read from a string. + *

+ * Note that this does not create a defensive copy, so the + * scanner will be mutated as you read on. + * + * @param scanner the scanner + * @throws NullPointerException if {@code scanner} is {@code null} + */ + public In(Scanner scanner) { + if (scanner == null) throw new NullPointerException("argument is null"); + this.scanner = scanner; + } + + /** + * Returns true if this input stream exists. + * + * @return {@code true} if this input stream exists; {@code false} otherwise + */ + public boolean exists() { + return scanner != null; + } + + //// begin: section (2 of 2) of code duplicated from In to StdIn, + //// with all methods changed from "public" to "public static". + + /** + * Returns true if input stream is empty (except possibly whitespace). + * Use this to know whether the next call to {@link #readString()}, + * {@link #readDouble()}, etc will succeed. + * + * @return {@code true} if this input stream is empty (except possibly whitespace); + * {@code false} otherwise + */ + public boolean isEmpty() { + return !scanner.hasNext(); + } + + /** + * Returns true if this input stream has a next line. + * Use this method to know whether the + * next call to {@link #readLine()} will succeed. + * This method is functionally equivalent to {@link #hasNextChar()}. + * + * @return {@code true} if this input stream is empty; + * {@code false} otherwise + */ + public boolean hasNextLine() { + return scanner.hasNextLine(); + } + + /** + * Returns true if this input stream has more inputy (including whitespace). + * Use this method to know whether the next call to {@link #readChar()} will succeed. + * This method is functionally equivalent to {@link #hasNextLine()}. + * + * @return {@code true} if this input stream has more input (including whitespace); + * {@code false} otherwise + */ + public boolean hasNextChar() { + scanner.useDelimiter(EMPTY_PATTERN); + boolean result = scanner.hasNext(); + scanner.useDelimiter(WHITESPACE_PATTERN); + return result; + } + + + /** + * Reads and returns the next line in this input stream. + * + * @return the next line in this input stream; {@code null} if no such line + */ + public String readLine() { + String line; + try { + line = scanner.nextLine(); + } + catch (NoSuchElementException e) { + line = null; + } + return line; + } + + /** + * Reads and returns the next character in this input stream. + * + * @return the next character in this input stream + */ + public char readChar() { + scanner.useDelimiter(EMPTY_PATTERN); + String ch = scanner.next(); + assert ch.length() == 1 : "Internal (Std)In.readChar() error!" + + " Please contact the authors."; + scanner.useDelimiter(WHITESPACE_PATTERN); + return ch.charAt(0); + } + + + /** + * Reads and returns the remainder of this input stream, as a string. + * + * @return the remainder of this input stream, as a string + */ + public String readAll() { + if (!scanner.hasNextLine()) + return ""; + + String result = scanner.useDelimiter(EVERYTHING_PATTERN).next(); + // not that important to reset delimeter, since now scanner is empty + scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway + return result; + } + + + /** + * Reads the next token from this input stream and returns it as a {@code String}. + * + * @return the next {@code String} in this input stream + */ + public String readString() { + return scanner.next(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code int}, + * and returns the {@code int}. + * + * @return the next {@code int} in this input stream + */ + public int readInt() { + return scanner.nextInt(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code double}, + * and returns the {@code double}. + * + * @return the next {@code double} in this input stream + */ + public double readDouble() { + return scanner.nextDouble(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code float}, + * and returns the {@code float}. + * + * @return the next {@code float} in this input stream + */ + public float readFloat() { + return scanner.nextFloat(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code long}, + * and returns the {@code long}. + * + * @return the next {@code long} in this input stream + */ + public long readLong() { + return scanner.nextLong(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code short}, + * and returns the {@code short}. + * + * @return the next {@code short} in this input stream + */ + public short readShort() { + return scanner.nextShort(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code byte}, + * and returns the {@code byte}. + *

+ * To read binary data, use {@link BinaryIn}. + * + * @return the next {@code byte} in this input stream + */ + public byte readByte() { + return scanner.nextByte(); + } + + /** + * Reads the next token from this input stream, parses it as a {@code boolean} + * (interpreting either {@code "true"} or {@code "1"} as {@code true}, + * and either {@code "false"} or {@code "0"} as {@code false}). + * + * @return the next {@code boolean} in this input stream + */ + public boolean readBoolean() { + String s = readString(); + if (s.equalsIgnoreCase("true")) return true; + if (s.equalsIgnoreCase("false")) return false; + if (s.equals("1")) return true; + if (s.equals("0")) return false; + throw new InputMismatchException(); + } + + /** + * Reads all remaining tokens from this input stream and returns them as + * an array of strings. + * + * @return all remaining tokens in this input stream, as an array of strings + */ + public String[] readAllStrings() { + // we could use readAll.trim().split(), but that's not consistent + // since trim() uses characters 0x00..0x20 as whitespace + String[] tokens = WHITESPACE_PATTERN.split(readAll()); + if (tokens.length == 0 || tokens[0].length() > 0) + return tokens; + String[] decapitokens = new String[tokens.length-1]; + for (int i = 0; i < tokens.length-1; i++) + decapitokens[i] = tokens[i+1]; + return decapitokens; + } + + /** + * Reads all remaining lines from this input stream and returns them as + * an array of strings. + * + * @return all remaining lines in this input stream, as an array of strings + */ + public String[] readAllLines() { + ArrayList lines = new ArrayList(); + while (hasNextLine()) { + lines.add(readLine()); + } + return lines.toArray(new String[0]); + } + + + /** + * Reads all remaining tokens from this input stream, parses them as integers, + * and returns them as an array of integers. + * + * @return all remaining lines in this input stream, as an array of integers + */ + public int[] readAllInts() { + String[] fields = readAllStrings(); + int[] vals = new int[fields.length]; + for (int i = 0; i < fields.length; i++) + vals[i] = Integer.parseInt(fields[i]); + return vals; + } + + /** + * Reads all remaining tokens from this input stream, parses them as longs, + * and returns them as an array of longs. + * + * @return all remaining lines in this input stream, as an array of longs + */ + public long[] readAllLongs() { + String[] fields = readAllStrings(); + long[] vals = new long[fields.length]; + for (int i = 0; i < fields.length; i++) + vals[i] = Long.parseLong(fields[i]); + return vals; + } + + /** + * Reads all remaining tokens from this input stream, parses them as doubles, + * and returns them as an array of doubles. + * + * @return all remaining lines in this input stream, as an array of doubles + */ + public double[] readAllDoubles() { + String[] fields = readAllStrings(); + double[] vals = new double[fields.length]; + for (int i = 0; i < fields.length; i++) + vals[i] = Double.parseDouble(fields[i]); + return vals; + } + + ///// end: section (2 of 2) of code duplicated from In to StdIn */ + + /** + * Closes this input stream. + */ + public void close() { + scanner.close(); + } + + /** + * Reads all integers from a file and returns them as + * an array of integers. + * + * @param filename the name of the file + * @return the integers in the file + * @deprecated Replaced by {@code new In(filename)}.{@link #readAllInts()}. + */ + @Deprecated + public static int[] readInts(String filename) { + return new In(filename).readAllInts(); + } + + /** + * Reads all doubles from a file and returns them as + * an array of doubles. + * + * @param filename the name of the file + * @return the doubles in the file + * @deprecated Replaced by {@code new In(filename)}.{@link #readAllDoubles()}. + */ + @Deprecated + public static double[] readDoubles(String filename) { + return new In(filename).readAllDoubles(); + } + + /** + * Reads all strings from a file and returns them as + * an array of strings. + * + * @param filename the name of the file + * @return the strings in the file + * @deprecated Replaced by {@code new In(filename)}.{@link #readAllStrings()}. + */ + @Deprecated + public static String[] readStrings(String filename) { + return new In(filename).readAllStrings(); + } + + /** + * Reads all integers from standard input and returns them + * an array of integers. + * + * @return the integers on standard input + * @deprecated Replaced by {@link StdIn#readAllInts()}. + */ + @Deprecated + public static int[] readInts() { + return new In().readAllInts(); + } + + /** + * Reads all doubles from standard input and returns them as + * an array of doubles. + * + * @return the doubles on standard input + * @deprecated Replaced by {@link StdIn#readAllDoubles()}. + */ + @Deprecated + public static double[] readDoubles() { + return new In().readAllDoubles(); + } + + /** + * Reads all strings from standard input and returns them as + * an array of strings. + * + * @return the strings on standard input + * @deprecated Replaced by {@link StdIn#readAllStrings()}. + */ + @Deprecated + public static String[] readStrings() { + return new In().readAllStrings(); + } + + /** + * Unit tests the {@code In} data type. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + In in; + String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt"; + + // read from a URL + System.out.println("readAll() from URL " + urlName); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In(urlName); + System.out.println(in.readAll()); + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + // read one line at a time from URL + System.out.println("readLine() from URL " + urlName); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In(urlName); + while (!in.isEmpty()) { + String s = in.readLine(); + System.out.println(s); + } + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + // read one string at a time from URL + System.out.println("readString() from URL " + urlName); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In(urlName); + while (!in.isEmpty()) { + String s = in.readString(); + System.out.println(s); + } + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + + // read one line at a time from file in current directory + System.out.println("readLine() from current directory"); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In("./InTest.txt"); + while (!in.isEmpty()) { + String s = in.readLine(); + System.out.println(s); + } + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + + // read one line at a time from file using relative path + System.out.println("readLine() from relative path"); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In("../stdlib/InTest.txt"); + while (!in.isEmpty()) { + String s = in.readLine(); + System.out.println(s); + } + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + // read one char at a time + System.out.println("readChar() from file"); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In("InTest.txt"); + while (!in.isEmpty()) { + char c = in.readChar(); + System.out.print(c); + } + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + System.out.println(); + + // read one line at a time from absolute OS X / Linux path + System.out.println("readLine() from absolute OS X / Linux path"); + System.out.println("---------------------------------------------------------------------------"); + in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt"); + try { + while (!in.isEmpty()) { + String s = in.readLine(); + System.out.println(s); + } + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + + // read one line at a time from absolute Windows path + System.out.println("readLine() from absolute Windows path"); + System.out.println("---------------------------------------------------------------------------"); + try { + in = new In("G:\\www\\introcs\\stdlib\\InTest.txt"); + while (!in.isEmpty()) { + String s = in.readLine(); + System.out.println(s); + } + System.out.println(); + } + catch (Exception e) { + System.out.println(e); + } + System.out.println(); + + } + +} + diff --git a/Algorithms/src/basic/Stack.java b/Algorithms/src/basic/Stack.java new file mode 100644 index 0000000..b5655ef --- /dev/null +++ b/Algorithms/src/basic/Stack.java @@ -0,0 +1,187 @@ +package basic; + +/****************************************************************************** + * Compilation: javac Stack.java + * Execution: java Stack < input.txt + * Dependencies: StdIn.java StdOut.java + * Data files: http://algs4.cs.princeton.edu/13stacks/tobe.txt + * + * A generic stack, implemented using a singly-linked list. + * Each stack element is of type Item. + * + * This version uses a static nested class Node (to save 8 bytes per + * Node), whereas the version in the textbook uses a non-static nested + * class (for simplicity). + * + * % more tobe.txt + * to be or not to - be - - that - - - is + * + * % java Stack < tobe.txt + * to be not that or be (2 left on stack) + * + ******************************************************************************/ + +import java.util.Iterator; +import java.util.NoSuchElementException; + + +/** + * The {@code Stack} class represents a last-in-first-out (LIFO) stack of generic items. + * It supports the usual push and pop operations, along with methods + * for peeking at the top item, testing if the stack is empty, and iterating through + * the items in LIFO order. + *

+ * This implementation uses a singly-linked list with a static nested class for + * linked-list nodes. See {@link LinkedStack} for the version from the + * textbook that uses a non-static nested class. + * The push, pop, peek, size, and is-empty + * operations all take constant time in the worst case. + *

+ * For additional documentation, + * see Section 1.3 of + * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. + * + * @author Robert Sedgewick + * @author Kevin Wayne + * + * @param the generic type of an item in this stack + */ +public class Stack implements Iterable { + private Node first; // top of stack + private int n; // size of the stack + + // helper linked list class + private static class Node { + private Item item; + private Node next; + } + + /** + * Initializes an empty stack. + */ + public Stack() { + first = null; + n = 0; + } + + /** + * Returns true if this stack is empty. + * + * @return true if this stack is empty; false otherwise + */ + public boolean isEmpty() { + return first == null; + } + + /** + * Returns the number of items in this stack. + * + * @return the number of items in this stack + */ + public int size() { + return n; + } + + /** + * Adds the item to this stack. + * + * @param item the item to add + */ + public void push(Item item) { + Node oldfirst = first; + first = new Node(); + first.item = item; + first.next = oldfirst; + n++; + } + + /** + * Removes and returns the item most recently added to this stack. + * + * @return the item most recently added + * @throws NoSuchElementException if this stack is empty + */ + public Item pop() { + if (isEmpty()) throw new NoSuchElementException("Stack underflow"); + Item item = first.item; // save item to return + first = first.next; // delete first node + n--; + return item; // return the saved item + } + + + /** + * Returns (but does not remove) the item most recently added to this stack. + * + * @return the item most recently added to this stack + * @throws NoSuchElementException if this stack is empty + */ + public Item peek() { + if (isEmpty()) throw new NoSuchElementException("Stack underflow"); + return first.item; + } + + /** + * Returns a string representation of this stack. + * + * @return the sequence of items in this stack in LIFO order, separated by spaces + */ + public String toString() { + StringBuilder s = new StringBuilder(); + for (Item item : this) + s.append(item + " "); + return s.toString(); + } + + + /** + * Returns an iterator to this stack that iterates through the items in LIFO order. + * + * @return an iterator to this stack that iterates through the items in LIFO order + */ + public Iterator iterator() { + return new ListIterator(first); + } + + // an iterator, doesn't implement remove() since it's optional + private class ListIterator implements Iterator { + private Node current; + + public ListIterator(Node first) { + current = first; + } + + public boolean hasNext() { + return current != null; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + public Item next() { + if (!hasNext()) throw new NoSuchElementException(); + Item item = current.item; + current = current.next; + return item; + } + } + + + /** + * Unit tests the {@code Stack} data type. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + Stack stack = new Stack(); + while (!StdIn.isEmpty()) { + String item = StdIn.readString(); + if (!item.equals("-")) + stack.push(item); + else if (!stack.isEmpty()) + StdOut.print(stack.pop() + " "); + } + StdOut.println("(" + stack.size() + " left on stack)"); + } +} diff --git a/Algorithms/src/basic/StdIn.java b/Algorithms/src/basic/StdIn.java new file mode 100644 index 0000000..85ef4d7 --- /dev/null +++ b/Algorithms/src/basic/StdIn.java @@ -0,0 +1,565 @@ +package basic; +/****************************************************************************** + * Compilation: javac StdIn.java + * Execution: java StdIn (interactive test of basic functionality) + * Dependencies: none + * + * Reads in data of various types from standard input. + * + ******************************************************************************/ + +import java.util.ArrayList; +import java.util.InputMismatchException; +import java.util.Locale; +import java.util.NoSuchElementException; +import java.util.Scanner; +import java.util.regex.Pattern; + +/** + * The {@code StdIn} class provides static methods for reading strings + * and numbers from standard input. + * These functions fall into one of four categories: + *

    + *
  • those for reading individual tokens from standard input, one at a time, + * and converting each to a number, string, or boolean + *
  • those for reading characters from standard input, one at a time + *
  • those for reading lines from standard input, one at a time + *
  • those for reading a sequence of values of the same type from standard input, + * and returning the values in an array + *
+ *

+ * Generally, it is best not to mix functions from the different + * categories in the same program. + *

+ * Reading tokens from standard input one at a time, + * and converting to numbers and strings. + * You can use the following methods to read numbers, strings, and booleans + * from standard input: + *

    + *
  • {@link #readInt()} + *
  • {@link #readDouble()} + *
  • {@link #readString()} + *
  • {@link #readBoolean()} + *
  • {@link #readShort()} + *
  • {@link #readLong()} + *
  • {@link #readFloat()} + *
  • {@link #readByte()} + *
+ *

+ * Each method skips over any input that is whitespace. Then, it reads + * the next token and attempts to convert it into a value of the specified + * type. If it succeeds, it returns that value; otherwise, it + * throws a {@link InputMismatchException}. + *

+ * Whitespace includes spaces, tabs, and newlines; the full definition + * is inherited from {@link Character#isWhitespace(char)}. + * A token is a maximal sequence of non-whitespace characters. + * The precise rules for describing which tokens can be converted to + * integers and floating-point numbers are inherited from + * Scanner, + * using the locale {@link Locale#US}; the rules + * for floating-point numbers are slightly different + * from those in {@link Double#valueOf(String)}, + * but unlikely to be of concern to most programmers. + *

+ * Reading characters from standard input, one at a time. + * You can use the following two methods to read characters from standard input: + *

    + *
  • {@link #hasNextChar()} + *
  • {@link #readChar()} + *
+ *

+ * The first method returns true if standard input has more input (including whitespace). + * The second method reads and returns the next character of input on standard + * input (possibly a whitespace character). + *

+ * As an example, the following code fragment reads characters from standard input, + * one character at a time, and prints it to standard output. + *

+ *  while (!StdIn.hasNextChar()) {
+ *      char c = StdIn.readChar();
+ *      StdOut.print(c);
+ *  }
+ *  
+ *

+ * Reading lines from standard input, one at a time. + * You can use the following two methods to read lines from standard input: + *

    + *
  • {@link #hasNextLine()} + *
  • {@link #readLine()} + *
+ *

+ * The first method returns true if standard input has more input (including whitespace). + * The second method reads and returns the remaining portion of + * the next line of input on standard input (possibly whitespace), + * discarding the trailing line separator. + *

+ * A line separator is defined to be one of the following strings: + * {@code \n} (Linux), {@code \r} (old Macintosh), + * {@code \r\n} (Windows), + * {@code \u2028}, {@code \u2029}, or {@code \u0085}. + *

+ * As an example, the following code fragment reads text from standard input, + * one line at a time, and prints it to standard output. + *

+ *  while (StdIn.hasNextLine()) {
+ *      String line = StdIn.readLine();
+ *      StdOut.println(line);
+ *  }
+ *  
+ *

+ * Reading a sequence of values of the same type from standard input. + * You can use the following methods to read a sequence numbers, strings, + * or booleans (all of the same type) from standard input: + *

    + *
  • {@link #readAllDoubles()} + *
  • {@link #readAllInts()} + *
  • {@link #readAllLongs()} + *
  • {@link #readAllStrings()} + *
  • {@link #readAllLines()} + *
  • {@link #readAll()} + *
+ *

+ * The first three methods read of all of remaining token on standard input + * and dconverts the tokens to values of + * the specified type, as in the corresponding + * {@code readDouble}, {@code readInt}, and {@code readString()} methods. + * The {@code readAllLines()} method reads all remaining lines on standard + * input and returns them as an array of strings. + * The {@code readAll()} method reads all remaining input on standard + * input and returns it as a string. + *

+ * As an example, the following code fragment reads all of the remaining + * tokens from standard input and returns them as an array of strings. + *

+ *  String[] words = StdIn.readAllStrings();
+ *  
+ *

+ * Differences with Scanner. + * {@code StdIn} and {@link Scanner} are both designed to parse + * tokens and convert them to primitive types and strings. + * Some of the main differences are summarized below: + *

    + *
  • {@code StdIn} is a set of static methods and reads + * reads input from only standard input. It is suitable for use before + * a programmer knows about objects. + * See {@link In} for an object-oriented version that handles + * input from files, URLs, + * and sockets. + *
  • {@code StdIn} uses whitespace as the delimiter between tokens. + *
  • {@code StdIn} coerces the character-set encoding to UTF-8, + * which is a standard character encoding for Unicode. + *
  • {@code StdIn} coerces the locale to {@link Locale#US}, + * for consistency with {@link StdOut}, {@link Double#parseDouble(String)}, + * and floating-point literals. + *
  • {@code StdIn} has convenient methods for reading a single + * character; reading in sequences of integers, doubles, or strings; + * and reading in all of the remaining input. + *
+ *

+ * Historical note: {@code StdIn} preceded {@code Scanner}; when + * {@code Scanner} was introduced, this class was reimplemented to use {@code Scanner}. + *

+ * Using standard input. + * Standard input is fundamental operating system abstraction, on Mac OS X, + * Windows, and Linux. + * The methods in {@code StdIn} are blocking, which means that they + * will wait until you enter input on standard input. + * If your program has a loop that repeats until standard input is empty, + * you must signal that the input is finished. + * To do so, depending on your operating system and IDE, + * use either {@code } or {@code }, on its own line. + * If you are redirecting standard input from a file, you will not need + * to do anything to signal that the input is finished. + *

+ * Known bugs. + * Java's UTF-8 encoding does not recognize the optional + * byte-order mask. + * If the input begins with the optional byte-order mask, {@code StdIn} + * will have an extra character {@code \uFEFF} at the beginning. + *

+ * Reference. + * For additional documentation, + * see Section 1.5 of + * Introduction to Programming in Java: An Interdisciplinary Approach + * by Robert Sedgewick and Kevin Wayne. + * + * @author David Pritchard + * @author Robert Sedgewick + * @author Kevin Wayne + */ +public final class StdIn { + + /*** begin: section (1 of 2) of code duplicated from In to StdIn. */ + + // assume Unicode UTF-8 encoding + private static final String CHARSET_NAME = "UTF-8"; + + // assume language = English, country = US for consistency with System.out. + private static final Locale LOCALE = Locale.US; + + // the default token separator; we maintain the invariant that this value + // is held by the scanner's delimiter between calls + private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\p{javaWhitespace}+"); + + // makes whitespace significant + private static final Pattern EMPTY_PATTERN = Pattern.compile(""); + + // used to read the entire input + private static final Pattern EVERYTHING_PATTERN = Pattern.compile("\\A"); + + /*** end: section (1 of 2) of code duplicated from In to StdIn. */ + + private static Scanner scanner; + + // it doesn't make sense to instantiate this class + private StdIn() { } + + //// begin: section (2 of 2) of code duplicated from In to StdIn, + //// with all methods changed from "public" to "public static" + + /** + * Returns true if standard input is empty (except possibly for whitespace). + * Use this method to know whether the next call to {@link #readString()}, + * {@link #readDouble()}, etc will succeed. + * + * @return {@code true} if standard input is empty (except possibly + * for whitespace); {@code false} otherwise + */ + public static boolean isEmpty() { + return !scanner.hasNext(); + } + + /** + * Returns true if standard input has a next line. + * Use this method to know whether the + * next call to {@link #readLine()} will succeed. + * This method is functionally equivalent to {@link #hasNextChar()}. + * + * @return {@code true} if standard input is empty; + * {@code false} otherwise + */ + public static boolean hasNextLine() { + return scanner.hasNextLine(); + } + + /** + * Returns true if standard input has more inputy (including whitespace). + * Use this method to know whether the next call to {@link #readChar()} will succeed. + * This method is functionally equivalent to {@link #hasNextLine()}. + * + * @return {@code true} if standard input has more input (including whitespace); + * {@code false} otherwise + */ + public static boolean hasNextChar() { + scanner.useDelimiter(EMPTY_PATTERN); + boolean result = scanner.hasNext(); + scanner.useDelimiter(WHITESPACE_PATTERN); + return result; + } + + + /** + * Reads and returns the next line, excluding the line separator if present. + * + * @return the next line, excluding the line separator if present; + * {@code null} if no such line + */ + public static String readLine() { + String line; + try { + line = scanner.nextLine(); + } + catch (NoSuchElementException e) { + line = null; + } + return line; + } + + /** + * Reads and returns the next character. + * + * @return the next character + * @throws NoSuchElementException if standard input is empty + */ + public static char readChar() { + scanner.useDelimiter(EMPTY_PATTERN); + String ch = scanner.next(); + assert ch.length() == 1 : "Internal (Std)In.readChar() error!" + + " Please contact the authors."; + scanner.useDelimiter(WHITESPACE_PATTERN); + return ch.charAt(0); + } + + + /** + * Reads and returns the remainder of the input, as a string. + * + * @return the remainder of the input, as a string + * @throws NoSuchElementException if standard input is empty + */ + public static String readAll() { + if (!scanner.hasNextLine()) + return ""; + + String result = scanner.useDelimiter(EVERYTHING_PATTERN).next(); + // not that important to reset delimeter, since now scanner is empty + scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway + return result; + } + + + /** + * Reads the next token and returns the {@code String}. + * + * @return the next {@code String} + * @throws NoSuchElementException if standard input is empty + */ + public static String readString() { + return scanner.next(); + } + + /** + * Reads the next token from standard input, parses it as an integer, and returns the integer. + * + * @return the next integer on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as an {@code int} + */ + public static int readInt() { + return scanner.nextInt(); + } + + /** + * Reads the next token from standard input, parses it as a double, and returns the double. + * + * @return the next double on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as a {@code double} + */ + public static double readDouble() { + return scanner.nextDouble(); + } + + /** + * Reads the next token from standard input, parses it as a float, and returns the float. + * + * @return the next float on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as a {@code float} + */ + public static float readFloat() { + return scanner.nextFloat(); + } + + /** + * Reads the next token from standard input, parses it as a long integer, and returns the long integer. + * + * @return the next long integer on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as a {@code long} + */ + public static long readLong() { + return scanner.nextLong(); + } + + /** + * Reads the next token from standard input, parses it as a short integer, and returns the short integer. + * + * @return the next short integer on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as a {@code short} + */ + public static short readShort() { + return scanner.nextShort(); + } + + /** + * Reads the next token from standard input, parses it as a byte, and returns the byte. + * + * @return the next byte on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as a {@code byte} + */ + public static byte readByte() { + return scanner.nextByte(); + } + + /** + * Reads the next token from standard input, parses it as a boolean, + * and returns the boolean. + * + * @return the next boolean on standard input + * @throws NoSuchElementException if standard input is empty + * @throws InputMismatchException if the next token cannot be parsed as a {@code boolean}: + * {@code true} or {@code 1} for true, and {@code false} or {@code 0} for false, + * ignoring case + */ + public static boolean readBoolean() { + String s = readString(); + if (s.equalsIgnoreCase("true")) return true; + if (s.equalsIgnoreCase("false")) return false; + if (s.equals("1")) return true; + if (s.equals("0")) return false; + throw new InputMismatchException(); + } + + /** + * Reads all remaining tokens from standard input and returns them as an array of strings. + * + * @return all remaining tokens on standard input, as an array of strings + */ + public static String[] readAllStrings() { + // we could use readAll.trim().split(), but that's not consistent + // because trim() uses characters 0x00..0x20 as whitespace + String[] tokens = WHITESPACE_PATTERN.split(readAll()); + if (tokens.length == 0 || tokens[0].length() > 0) + return tokens; + + // don't include first token if it is leading whitespace + String[] decapitokens = new String[tokens.length-1]; + for (int i = 0; i < tokens.length - 1; i++) + decapitokens[i] = tokens[i+1]; + return decapitokens; + } + + /** + * Reads all remaining lines from standard input and returns them as an array of strings. + * @return all remaining lines on standard input, as an array of strings + */ + public static String[] readAllLines() { + ArrayList lines = new ArrayList(); + while (hasNextLine()) { + lines.add(readLine()); + } + return lines.toArray(new String[0]); + } + + /** + * Reads all remaining tokens from standard input, parses them as integers, and returns + * them as an array of integers. + * @return all remaining integers on standard input, as an array + * @throws InputMismatchException if any token cannot be parsed as an {@code int} + */ + public static int[] readAllInts() { + String[] fields = readAllStrings(); + int[] vals = new int[fields.length]; + for (int i = 0; i < fields.length; i++) + vals[i] = Integer.parseInt(fields[i]); + return vals; + } + + /** + * Reads all remaining tokens from standard input, parses them as longs, and returns + * them as an array of longs. + * @return all remaining longs on standard input, as an array + * @throws InputMismatchException if any token cannot be parsed as a {@code long} + */ + public static long[] readAllLongs() { + String[] fields = readAllStrings(); + long[] vals = new long[fields.length]; + for (int i = 0; i < fields.length; i++) + vals[i] = Long.parseLong(fields[i]); + return vals; + } + + /** + * Reads all remaining tokens from standard input, parses them as doubles, and returns + * them as an array of doubles. + * @return all remaining doubles on standard input, as an array + * @throws InputMismatchException if any token cannot be parsed as a {@code double} + */ + public static double[] readAllDoubles() { + String[] fields = readAllStrings(); + double[] vals = new double[fields.length]; + for (int i = 0; i < fields.length; i++) + vals[i] = Double.parseDouble(fields[i]); + return vals; + } + + //// end: section (2 of 2) of code duplicated from In to StdIn + + + // do this once when StdIn is initialized + static { + resync(); + } + + /** + * If StdIn changes, use this to reinitialize the scanner. + */ + private static void resync() { + setScanner(new Scanner(new java.io.BufferedInputStream(System.in), CHARSET_NAME)); + } + + private static void setScanner(Scanner scanner) { + StdIn.scanner = scanner; + StdIn.scanner.useLocale(LOCALE); + } + + /** + * Reads all remaining tokens, parses them as integers, and returns + * them as an array of integers. + * @return all remaining integers, as an array + * @throws InputMismatchException if any token cannot be parsed as an {@code int} + * @deprecated Replaced by {@link #readAllInts()}. + */ + @Deprecated + public static int[] readInts() { + return readAllInts(); + } + + /** + * Reads all remaining tokens, parses them as doubles, and returns + * them as an array of doubles. + * @return all remaining doubles, as an array + * @throws InputMismatchException if any token cannot be parsed as a {@code double} + * @deprecated Replaced by {@link #readAllDoubles()}. + */ + @Deprecated + public static double[] readDoubles() { + return readAllDoubles(); + } + + /** + * Reads all remaining tokens and returns them as an array of strings. + * @return all remaining tokens, as an array of strings + * @deprecated Replaced by {@link #readAllStrings()}. + */ + @Deprecated + public static String[] readStrings() { + return readAllStrings(); + } + + + /** + * Interactive test of basic functionality. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + + StdOut.print("Type a string: "); + String s = StdIn.readString(); + StdOut.println("Your string was: " + s); + StdOut.println(); + + StdOut.print("Type an int: "); + int a = StdIn.readInt(); + StdOut.println("Your int was: " + a); + StdOut.println(); + + StdOut.print("Type a boolean: "); + boolean b = StdIn.readBoolean(); + StdOut.println("Your boolean was: " + b); + StdOut.println(); + + StdOut.print("Type a double: "); + double c = StdIn.readDouble(); + StdOut.println("Your double was: " + c); + StdOut.println(); + + } + +} + diff --git a/Algorithms/src/basic/StdOut.java b/Algorithms/src/basic/StdOut.java new file mode 100644 index 0000000..aade1ce --- /dev/null +++ b/Algorithms/src/basic/StdOut.java @@ -0,0 +1,320 @@ +package basic; +/****************************************************************************** + * Compilation: javac StdOut.java + * Execution: java StdOut + * Dependencies: none + * + * Writes data of various types to standard output. + * + ******************************************************************************/ + +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.Locale; + +/** + * This class provides methods for printing strings and numbers to standard output. + *

+ * Getting started. + * To use this class, you must have {@code StdOut.class} in your + * Java classpath. If you used our autoinstaller, you should be all set. + * Otherwise, download + * StdOut.java + * and put a copy in your working directory. + *

+ * Here is an example program that uses {@code StdOut}: + *

+ *   public class TestStdOut {
+ *       public static void main(String[] args) {
+ *           int a = 17;
+ *           int b = 23;
+ *           int sum = a + b;
+ *           StdOut.println("Hello, World");
+ *           StdOut.printf("%d + %d = %d\n", a, b, sum);
+ *       }
+ *   }
+ *  
+ *

+ * Differences with System.out. + * The behavior of {@code StdOut} is similar to that of {@link System#out}, + * but there are a few subtle differences: + *

    + *
  • {@code StdOut} coerces the character-set encoding to UTF-8, + * which is a standard character encoding for Unicode. + *
  • {@code StdOut} coerces the locale to {@link Locale#US}, + * for consistency with {@link StdIn}, {@link Double#parseDouble(String)}, + * and floating-point literals. + *
  • {@code StdOut} flushes standard output after each call to + * {@code print()} so that text will appear immediately in the terminal. + *
+ *

+ * Reference. + * For additional documentation, + * see Section 1.5 of + * Introduction to Programming in Java: An Interdisciplinary Approach + * by Robert Sedgewick and Kevin Wayne. + * + * @author Robert Sedgewick + * @author Kevin Wayne + */ +public final class StdOut { + + // force Unicode UTF-8 encoding; otherwise it's system dependent + private static final String CHARSET_NAME = "UTF-8"; + + // assume language = English, country = US for consistency with StdIn + private static final Locale LOCALE = Locale.US; + + // send output here + private static PrintWriter out; + + // this is called before invoking any methods + static { + try { + out = new PrintWriter(new OutputStreamWriter(System.out, CHARSET_NAME), true); + } + catch (UnsupportedEncodingException e) { + System.out.println(e); + } + } + + // don't instantiate + private StdOut() { } + + /** + * Closes standard output. + */ + public static void close() { + out.close(); + } + + /** + * Terminates the current line by printing the line-separator string. + */ + public static void println() { + out.println(); + } + + /** + * Prints an object to this output stream and then terminates the line. + * + * @param x the object to print + */ + public static void println(Object x) { + out.println(x); + } + + /** + * Prints a boolean to standard output and then terminates the line. + * + * @param x the boolean to print + */ + public static void println(boolean x) { + out.println(x); + } + + /** + * Prints a character to standard output and then terminates the line. + * + * @param x the character to print + */ + public static void println(char x) { + out.println(x); + } + + /** + * Prints a double to standard output and then terminates the line. + * + * @param x the double to print + */ + public static void println(double x) { + out.println(x); + } + + /** + * Prints an integer to standard output and then terminates the line. + * + * @param x the integer to print + */ + public static void println(float x) { + out.println(x); + } + + /** + * Prints an integer to standard output and then terminates the line. + * + * @param x the integer to print + */ + public static void println(int x) { + out.println(x); + } + + /** + * Prints a long to standard output and then terminates the line. + * + * @param x the long to print + */ + public static void println(long x) { + out.println(x); + } + + /** + * Prints a short integer to standard output and then terminates the line. + * + * @param x the short to print + */ + public static void println(short x) { + out.println(x); + } + + /** + * Prints a byte to standard output and then terminates the line. + *

+ * To write binary data, see {@link BinaryStdOut}. + * + * @param x the byte to print + */ + public static void println(byte x) { + out.println(x); + } + + /** + * Flushes standard output. + */ + public static void print() { + out.flush(); + } + + /** + * Prints an object to standard output and flushes standard output. + * + * @param x the object to print + */ + public static void print(Object x) { + out.print(x); + out.flush(); + } + + /** + * Prints a boolean to standard output and flushes standard output. + * + * @param x the boolean to print + */ + public static void print(boolean x) { + out.print(x); + out.flush(); + } + + /** + * Prints a character to standard output and flushes standard output. + * + * @param x the character to print + */ + public static void print(char x) { + out.print(x); + out.flush(); + } + + /** + * Prints a double to standard output and flushes standard output. + * + * @param x the double to print + */ + public static void print(double x) { + out.print(x); + out.flush(); + } + + /** + * Prints a float to standard output and flushes standard output. + * + * @param x the float to print + */ + public static void print(float x) { + out.print(x); + out.flush(); + } + + /** + * Prints an integer to standard output and flushes standard output. + * + * @param x the integer to print + */ + public static void print(int x) { + out.print(x); + out.flush(); + } + + /** + * Prints a long integer to standard output and flushes standard output. + * + * @param x the long integer to print + */ + public static void print(long x) { + out.print(x); + out.flush(); + } + + /** + * Prints a short integer to standard output and flushes standard output. + * + * @param x the short integer to print + */ + public static void print(short x) { + out.print(x); + out.flush(); + } + + /** + * Prints a byte to standard output and flushes standard output. + * + * @param x the byte to print + */ + public static void print(byte x) { + out.print(x); + out.flush(); + } + + /** + * Prints a formatted string to standard output, using the specified format + * string and arguments, and then flushes standard output. + * + * + * @param format the format string + * @param args the arguments accompanying the format string + */ + public static void printf(String format, Object... args) { + out.printf(LOCALE, format, args); + out.flush(); + } + + /** + * Prints a formatted string to standard output, using the locale and + * the specified format string and arguments; then flushes standard output. + * + * @param locale the locale + * @param format the format string + * @param args the arguments accompanying the format string + */ + public static void printf(Locale locale, String format, Object... args) { + out.printf(locale, format, args); + out.flush(); + } + + /** + * Unit tests some of the methods in {@code StdOut}. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + + // write to stdout + StdOut.println("Test"); + StdOut.println(17); + StdOut.println(true); + StdOut.printf("%.6f\n", 1.0/7.0); + } + +} + diff --git a/Algorithms/src/basic/StdRandom.java b/Algorithms/src/basic/StdRandom.java new file mode 100644 index 0000000..10f6abf --- /dev/null +++ b/Algorithms/src/basic/StdRandom.java @@ -0,0 +1,534 @@ +package basic; + +/****************************************************************************** + * Compilation: javac StdRandom.java + * Execution: java StdRandom + * Dependencies: StdOut.java + * + * A library of static methods to generate pseudo-random numbers from + * different distributions (bernoulli, uniform, gaussian, discrete, + * and exponential). Also includes a method for shuffling an array. + * + * + * % java StdRandom 5 + * seed = 1316600602069 + * 59 16.81826 true 8.83954 0 + * 32 91.32098 true 9.11026 0 + * 35 10.11874 true 8.95396 3 + * 92 32.88401 true 8.87089 0 + * 72 92.55791 true 9.46241 0 + * + * % java StdRandom 5 + * seed = 1316600616575 + * 96 60.17070 true 8.72821 0 + * 79 32.01607 true 8.58159 0 + * 81 59.49065 true 9.10423 1 + * 96 51.65818 true 9.02102 0 + * 99 17.55771 true 8.99762 0 + * + * % java StdRandom 5 1316600616575 + * seed = 1316600616575 + * 96 60.17070 true 8.72821 0 + * 79 32.01607 true 8.58159 0 + * 81 59.49065 true 9.10423 1 + * 96 51.65818 true 9.02102 0 + * 99 17.55771 true 8.99762 0 + * + * + * Remark + * ------ + * - Relies on randomness of nextDouble() method in java.util.Random + * to generate pseudorandom numbers in [0, 1). + * + * - This library allows you to set and get the pseudorandom number seed. + * + * - See http://www.honeylocust.com/RngPack/ for an industrial + * strength random number generator in Java. + * + ******************************************************************************/ + +import java.util.Random; + +/** + * The {@code StdRandom} class provides static methods for generating + * random number from various discrete and continuous distributions, + * including Bernoulli, uniform, Gaussian, exponential, pareto, + * Poisson, and Cauchy. It also provides method for shuffling an + * array or subarray. + *

+ * For additional documentation, + * see Section 2.2 of + * Introduction to Programming in Java: An Interdisciplinary Approach + * by Robert Sedgewick and Kevin Wayne. + * + * @author Robert Sedgewick + * @author Kevin Wayne + */ +public final class StdRandom { + + private static Random random; // pseudo-random number generator + private static long seed; // pseudo-random number generator seed + + // static initializer + static { + // this is how the seed was set in Java 1.4 + seed = System.currentTimeMillis(); + random = new Random(seed); + } + + // don't instantiate + private StdRandom() { } + + /** + * Sets the seed of the pseudorandom number generator. + * This method enables you to produce the same sequence of "random" + * number for each execution of the program. + * Ordinarily, you should call this method at most once per program. + * + * @param s the seed + */ + public static void setSeed(long s) { + seed = s; + random = new Random(seed); + } + + /** + * Returns the seed of the pseudorandom number generator. + * + * @return the seed + */ + public static long getSeed() { + return seed; + } + + /** + * Returns a random real number uniformly in [0, 1). + * + * @return a random real number uniformly in [0, 1) + */ + public static double uniform() { + return random.nextDouble(); + } + + /** + * Returns a random integer uniformly in [0, n). + * + * @param n number of possible integers + * @return a random integer uniformly between 0 (inclusive) and {@code N} (exclusive) + * @throws IllegalArgumentException if {@code n <= 0} + */ + public static int uniform(int n) { + if (n <= 0) throw new IllegalArgumentException("Parameter N must be positive"); + return random.nextInt(n); + } + + /////////////////////////////////////////////////////////////////////////// + // STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA + // THE STATIC METHODS ABOVE. + /////////////////////////////////////////////////////////////////////////// + + /** + * Returns a random real number uniformly in [0, 1). + * + * @return a random real number uniformly in [0, 1) + * @deprecated Replaced by {@link #uniform()}. + */ + @Deprecated + public static double random() { + return uniform(); + } + + /** + * Returns a random integer uniformly in [a, b). + * + * @param a the left endpoint + * @param b the right endpoint + * @return a random integer uniformly in [a, b) + * @throws IllegalArgumentException if {@code b <= a} + * @throws IllegalArgumentException if {@code b - a >= Integer.MAX_VALUE} + */ + public static int uniform(int a, int b) { + if (b <= a) throw new IllegalArgumentException("Invalid range"); + if ((long) b - a >= Integer.MAX_VALUE) throw new IllegalArgumentException("Invalid range"); + return a + uniform(b - a); + } + + /** + * Returns a random real number uniformly in [a, b). + * + * @param a the left endpoint + * @param b the right endpoint + * @return a random real number uniformly in [a, b) + * @throws IllegalArgumentException unless {@code a < b} + */ + public static double uniform(double a, double b) { + if (!(a < b)) throw new IllegalArgumentException("Invalid range"); + return a + uniform() * (b-a); + } + + /** + * Returns a random boolean from a Bernoulli distribution with success + * probability p. + * + * @param p the probability of returning {@code true} + * @return {@code true} with probability {@code p} and + * {@code false} with probability {@code p} + * @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0} + */ + public static boolean bernoulli(double p) { + if (!(p >= 0.0 && p <= 1.0)) + throw new IllegalArgumentException("Probability must be between 0.0 and 1.0"); + return uniform() < p; + } + + /** + * Returns a random boolean from a Bernoulli distribution with success + * probability 1/2. + * + * @return {@code true} with probability 1/2 and + * {@code false} with probability 1/2 + */ + public static boolean bernoulli() { + return bernoulli(0.5); + } + + /** + * Returns a random real number from a standard Gaussian distribution. + * + * @return a random real number from a standard Gaussian distribution + * (mean 0 and standard deviation 1). + */ + public static double gaussian() { + // use the polar form of the Box-Muller transform + double r, x, y; + do { + x = uniform(-1.0, 1.0); + y = uniform(-1.0, 1.0); + r = x*x + y*y; + } while (r >= 1 || r == 0); + return x * Math.sqrt(-2 * Math.log(r) / r); + + // Remark: y * Math.sqrt(-2 * Math.log(r) / r) + // is an independent random gaussian + } + + /** + * Returns a random real number from a Gaussian distribution with mean μ + * and standard deviation σ. + * + * @param mu the mean + * @param sigma the standard deviation + * @return a real number distributed according to the Gaussian distribution + * with mean {@code mu} and standard deviation {@code sigma} + */ + public static double gaussian(double mu, double sigma) { + return mu + sigma * gaussian(); + } + + /** + * Returns a random integer from a geometric distribution with success + * probability p. + * + * @param p the parameter of the geometric distribution + * @return a random integer from a geometric distribution with success + * probability {@code p}; or {@code Integer.MAX_VALUE} if + * {@code p} is (nearly) equal to {@code 1.0}. + * @throws IllegalArgumentException unless {@code p >= 0.0} and {@code p <= 1.0} + */ + public static int geometric(double p) { + if (!(p >= 0.0 && p <= 1.0)) + throw new IllegalArgumentException("Probability must be between 0.0 and 1.0"); + // using algorithm given by Knuth + return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p)); + } + + /** + * Returns a random integer from a Poisson distribution with mean λ. + * + * @param lambda the mean of the Poisson distribution + * @return a random integer from a Poisson distribution with mean {@code lambda} + * @throws IllegalArgumentException unless {@code lambda > 0.0} and not infinite + */ + public static int poisson(double lambda) { + if (!(lambda > 0.0)) + throw new IllegalArgumentException("Parameter lambda must be positive"); + if (Double.isInfinite(lambda)) + throw new IllegalArgumentException("Parameter lambda must not be infinite"); + // using algorithm given by Knuth + // see http://en.wikipedia.org/wiki/Poisson_distribution + int k = 0; + double p = 1.0; + double expLambda = Math.exp(-lambda); + do { + k++; + p *= uniform(); + } while (p >= expLambda); + return k-1; + } + + /** + * Returns a random real number from the standard Pareto distribution. + * + * @return a random real number from the standard Pareto distribution + */ + public static double pareto() { + return pareto(1.0); + } + + /** + * Returns a random real number from a Pareto distribution with + * shape parameter α. + * + * @param alpha shape parameter + * @return a random real number from a Pareto distribution with shape + * parameter {@code alpha} + * @throws IllegalArgumentException unless {@code alpha > 0.0} + */ + public static double pareto(double alpha) { + if (!(alpha > 0.0)) + throw new IllegalArgumentException("Shape parameter alpha must be positive"); + return Math.pow(1 - uniform(), -1.0/alpha) - 1.0; + } + + /** + * Returns a random real number from the Cauchy distribution. + * + * @return a random real number from the Cauchy distribution. + */ + public static double cauchy() { + return Math.tan(Math.PI * (uniform() - 0.5)); + } + + /** + * Returns a random integer from the specified discrete distribution. + * + * @param probabilities the probability of occurrence of each integer + * @return a random integer from a discrete distribution: + * {@code i} with probability {@code probabilities[i]} + * @throws NullPointerException if {@code probabilities} is {@code null} + * @throws IllegalArgumentException if sum of array entries is not (very nearly) equal to {@code 1.0} + * @throws IllegalArgumentException unless {@code probabilities[i] >= 0.0} for each index {@code i} + */ + public static int discrete(double[] probabilities) { + if (probabilities == null) throw new NullPointerException("argument array is null"); + double EPSILON = 1E-14; + double sum = 0.0; + for (int i = 0; i < probabilities.length; i++) { + if (!(probabilities[i] >= 0.0)) + throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + probabilities[i]); + sum += probabilities[i]; + } + if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) + throw new IllegalArgumentException("sum of array entries does not approximately equal 1.0: " + sum); + + // the for loop may not return a value when both r is (nearly) 1.0 and when the + // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) + while (true) { + double r = uniform(); + sum = 0.0; + for (int i = 0; i < probabilities.length; i++) { + sum = sum + probabilities[i]; + if (sum > r) return i; + } + } + } + + /** + * Returns a random integer from the specified discrete distribution. + * + * @param frequencies the frequency of occurrence of each integer + * @return a random integer from a discrete distribution: + * {@code i} with probability proportional to {@code frequencies[i]} + * @throws NullPointerException if {@code frequencies} is {@code null} + * @throws IllegalArgumentException if all array entries are {@code 0} + * @throws IllegalArgumentException if {@code frequencies[i]} is negative for any index {@code i} + * @throws IllegalArgumentException if sum of frequencies exceeds {@code Integer.MAX_VALUE} (231 - 1) + */ + public static int discrete(int[] frequencies) { + if (frequencies == null) throw new NullPointerException("argument array is null"); + long sum = 0; + for (int i = 0; i < frequencies.length; i++) { + if (frequencies[i] < 0) + throw new IllegalArgumentException("array entry " + i + " must be nonnegative: " + frequencies[i]); + sum += frequencies[i]; + } + if (sum == 0) + throw new IllegalArgumentException("at least one array entry must be positive"); + if (sum >= Integer.MAX_VALUE) + throw new IllegalArgumentException("sum of frequencies overflows an int"); + + // pick index i with probabilitity proportional to frequency + double r = uniform((int) sum); + sum = 0; + for (int i = 0; i < frequencies.length; i++) { + sum += frequencies[i]; + if (sum > r) return i; + } + + // can't reach here + assert false; + return -1; + } + + /** + * Returns a random real number from an exponential distribution + * with rate λ. + * + * @param lambda the rate of the exponential distribution + * @return a random real number from an exponential distribution with + * rate {@code lambda} + * @throws IllegalArgumentException unless {@code lambda > 0.0} + */ + public static double exp(double lambda) { + if (!(lambda > 0.0)) + throw new IllegalArgumentException("Rate lambda must be positive"); + return -Math.log(1 - uniform()) / lambda; + } + + /** + * Rearranges the elements of the specified array in uniformly random order. + * + * @param a the array to shuffle + * @throws NullPointerException if {@code a} is {@code null} + */ + public static void shuffle(Object[] a) { + if (a == null) throw new NullPointerException("argument array is null"); + int n = a.length; + for (int i = 0; i < n; i++) { + int r = i + uniform(n-i); // between i and n-1 + Object temp = a[i]; + a[i] = a[r]; + a[r] = temp; + } + } + + /** + * Rearranges the elements of the specified array in uniformly random order. + * + * @param a the array to shuffle + * @throws NullPointerException if {@code a} is {@code null} + */ + public static void shuffle(double[] a) { + if (a == null) throw new NullPointerException("argument array is null"); + int n = a.length; + for (int i = 0; i < n; i++) { + int r = i + uniform(n-i); // between i and n-1 + double temp = a[i]; + a[i] = a[r]; + a[r] = temp; + } + } + + /** + * Rearranges the elements of the specified array in uniformly random order. + * + * @param a the array to shuffle + * @throws NullPointerException if {@code a} is {@code null} + */ + public static void shuffle(int[] a) { + if (a == null) throw new NullPointerException("argument array is null"); + int n = a.length; + for (int i = 0; i < n; i++) { + int r = i + uniform(n-i); // between i and n-1 + int temp = a[i]; + a[i] = a[r]; + a[r] = temp; + } + } + + + /** + * Rearranges the elements of the specified subarray in uniformly random order. + * + * @param a the array to shuffle + * @param lo the left endpoint (inclusive) + * @param hi the right endpoint (inclusive) + * @throws NullPointerException if {@code a} is {@code null} + * @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)} + * + */ + public static void shuffle(Object[] a, int lo, int hi) { + if (a == null) throw new NullPointerException("argument array is null"); + if (lo < 0 || lo > hi || hi >= a.length) { + throw new IndexOutOfBoundsException("Illegal subarray range"); + } + for (int i = lo; i <= hi; i++) { + int r = i + uniform(hi-i+1); // between i and hi + Object temp = a[i]; + a[i] = a[r]; + a[r] = temp; + } + } + + /** + * Rearranges the elements of the specified subarray in uniformly random order. + * + * @param a the array to shuffle + * @param lo the left endpoint (inclusive) + * @param hi the right endpoint (inclusive) + * @throws NullPointerException if {@code a} is {@code null} + * @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)} + */ + public static void shuffle(double[] a, int lo, int hi) { + if (a == null) throw new NullPointerException("argument array is null"); + if (lo < 0 || lo > hi || hi >= a.length) { + throw new IndexOutOfBoundsException("Illegal subarray range"); + } + for (int i = lo; i <= hi; i++) { + int r = i + uniform(hi-i+1); // between i and hi + double temp = a[i]; + a[i] = a[r]; + a[r] = temp; + } + } + + /** + * Rearranges the elements of the specified subarray in uniformly random order. + * + * @param a the array to shuffle + * @param lo the left endpoint (inclusive) + * @param hi the right endpoint (inclusive) + * @throws NullPointerException if {@code a} is {@code null} + * @throws IndexOutOfBoundsException unless {@code (0 <= lo) && (lo <= hi) && (hi < a.length)} + */ + public static void shuffle(int[] a, int lo, int hi) { + if (a == null) throw new NullPointerException("argument array is null"); + if (lo < 0 || lo > hi || hi >= a.length) { + throw new IndexOutOfBoundsException("Illegal subarray range"); + } + for (int i = lo; i <= hi; i++) { + int r = i + uniform(hi-i+1); // between i and hi + int temp = a[i]; + a[i] = a[r]; + a[r] = temp; + } + } + + /** + * Unit test. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + int n = Integer.parseInt(args[0]); + if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1])); + double[] probabilities = { 0.5, 0.3, 0.1, 0.1 }; + int[] frequencies = { 5, 3, 1, 1 }; + String[] a = "A B C D E F G".split(" "); + + StdOut.println("seed = " + StdRandom.getSeed()); + for (int i = 0; i < n; i++) { + StdOut.printf("%2d ", uniform(100)); + StdOut.printf("%8.5f ", uniform(10.0, 99.0)); + StdOut.printf("%5b ", bernoulli(0.5)); + StdOut.printf("%7.5f ", gaussian(9.0, 0.2)); + StdOut.printf("%1d ", discrete(probabilities)); + StdOut.printf("%1d ", discrete(frequencies)); + StdRandom.shuffle(a); + for (String s : a) + StdOut.print(s); + StdOut.println(); + } + } + +} diff --git a/Algorithms/src/graph/Edge.java b/Algorithms/src/graph/Edge.java new file mode 100644 index 0000000..9c81e17 --- /dev/null +++ b/Algorithms/src/graph/Edge.java @@ -0,0 +1,101 @@ +package graph; + +import basic.StdOut; + +public class Edge implements Comparable { + + private final int v; + private final int w; + private final double weight; + + /** + * Initialize an edge between vertices{@code v} and vertices{@code w} of the given + * {@code weight}}} + * + * @param v one vertex + * @param w another vertex + * @param weight the weight of the edge + * @throws IndexOutOfBoundsException if either{@code v} or {@code w} is a negative integer} + * @throws IllegalArgumentException if {@code weight} is {@code NaN}} + * + */ + + public Edge(int v, int w, double weight){ + + if(v<0) throw new IndexOutOfBoundsException(" Vertex name must be a nonnegative integer"); + if(w<0) throw new IndexOutOfBoundsException(" Vertex name must be a nonnegative integer"); + if(Double.isNaN(weight)) throw new IllegalArgumentException(" Weigth is not a number"); + this.v = v; + this.w = w; + this.weight = weight; + + } + + + /** + * Returns the weight of this edge. + * + * @return the weight of this edge + * + * + */ + public double weight(){ + return this.weight; + } + + + /** + *Returns either endpoint of this edge ; + * + * @return either endpoint of this edge; + */ + + public int either(){ + return v; + } + + + /** + *Return the endpoint of this edge that is diff from the given vertex + * + * @param one vertex of this edge + * @return the other vertex of this edge + * @throws IllegalArgumentException if the vertex is not one of the endpoints of this edge. + * + */ + + public int other (int vertex){ + if (vertex ==v) return w; + if(vertex == w) return v; + else throw new IllegalArgumentException("Illegal endpoint" + vertex); + + } + + + /** + *Compare edge basic on their weight. + * + */ + @Override + public int compareTo(Edge o) { + return Double.compare(this.weight, o.weight); + + } + + public String toString(){ + return String.format("%d-%d %.5f", v,w,weight); + } + + /** + * Unit tests the {@code Edge} date type} + * + * @param args + */ + public static void main(String[] args){ + Edge e = new Edge(12,34,5.67); + StdOut.println(e); + + } + + +} diff --git a/Algorithms/src/minimalSpanningTree/EdgeWeightedGraph.java b/Algorithms/src/minimalSpanningTree/EdgeWeightedGraph.java new file mode 100644 index 0000000..2d402fc --- /dev/null +++ b/Algorithms/src/minimalSpanningTree/EdgeWeightedGraph.java @@ -0,0 +1,209 @@ +package minimalSpanningTree; + +import graph.Edge; +import basic.Bag; +import basic.In; +import basic.Stack; +import basic.StdOut; +import basic.StdRandom; + +public class EdgeWeightedGraph{ + + private static final String NEWLINE = System.getProperty("line.separator"); + private final int V; + private int E; + private Bag[] adj; + + + /** + * Initializes an empty edge-weighted graph with {@code V} vertices and 0 edges. + * + * @param V the number of vertices + * @throws IllegalArgumentException if {@code V < 0} + */ + public EdgeWeightedGraph(int V){ + if(V<0) throw new IllegalArgumentException("Number of vertices must be nonnegative"); + this.V = V; + this.E = 0; + adj = (Bag[])new Bag[V]; + for(int v=0;v(); + } + + } + + /** + * Initializes a random edge-weighted graph with {@code V} vertices and E edges. + * + * @param V the number of vertices + * @param E the number of edges + * @throws IllegalArgumentException if {@code V < 0} + * @throws IllegalArgumentException if {@code E < 0} + */ + public EdgeWeightedGraph(int V, int E) { + this(V); + if (E < 0) throw new IllegalArgumentException("Number of edges must be nonnegative"); + for (int i = 0; i < E; i++) { + int v = StdRandom.uniform(V); + int w = StdRandom.uniform(V); + double weight = Math.round(100 * StdRandom.uniform()) / 100.0; + Edge e = new Edge(v, w, weight); + addEdge(e); + } + } + + + + + /** + * Initializes an edge-weighted graph from an input stream. + * The format is the number of vertices V, + * followed by the number of edges E, + * followed by E pairs of vertices and edge weights, + * with each entry separated by whitespace. + * + * @param in the input stream + * @throws IndexOutOfBoundsException if the endpoints of any edge are not in prescribed range + * @throws IllegalArgumentException if the number of vertices or edges is negative + */ + public EdgeWeightedGraph(In in) { + this(in.readInt()); + int E = in.readInt(); + if (E < 0) throw new IllegalArgumentException("Number of edges must be nonnegative"); + for (int i = 0; i < E; i++) { + int v = in.readInt(); + int w = in.readInt(); + double weight = in.readDouble(); + Edge e = new Edge(v, w, weight); + addEdge(e); + } + } + + + + + /** + * Initializes a new edge-weighted graph that is a deep copy of {@code G}. + * + * @param G the edge-weighted graph to copy + */ + public EdgeWeightedGraph(EdgeWeightedGraph G) { + this(G.V()); + this.E = G.E(); + for (int v = 0; v < G.V(); v++) { + // reverse so that adjacency list is in same order as original + Stack reverse = new Stack(); + for (Edge e : G.adj[v]) { + reverse.push(e); + } + for (Edge e : reverse) { + adj[v].add(e); + } + } + } + + + + private void addEdge(Edge e) { + + int v = e.either(); + int w = e.other(v); + validateVertex(v); + validateVertex(w); + adj[v].add(e); + adj[w].add(e); + E++; + } + + private void validateVertex(int v) { + if (v < 0 || v >= V) + throw new IndexOutOfBoundsException("vertex " + v + " is not between 0 and " + (V-1)); + } + + + + public int V() { + return V; + } + + public int E() { + return E; + } + + + + + public Iterable adj(int v){ + validateVertex(v); + return adj[v]; + + } + + + + public int degree(int v){ + validateVertex(v); + return adj[v].size(); + } + + + + public Iterable edges(){ + Bag list = new Bag(); + for(int v=0;vv){ + list.add(e); + } + else if(e.other(v)==v){ + if(selfLoops%2==0){ + list.add(e); + selfLoops++; + } + } + } + } + return list; + } + + + + /** + * Returns a string representation of the edge-weighted graph. + * This method takes time proportional to E + V. + * + * @return the number of vertices V, followed by the number of edges E, + * followed by the V adjacency lists of edges + */ + public String toString() { + StringBuilder s = new StringBuilder(); + s.append(V + " " + E + NEWLINE); + for (int v = 0; v < V; v++) { + s.append(v + ": "); + for (Edge e : adj[v]) { + s.append(e + " "); + } + s.append(NEWLINE); + } + return s.toString(); + } + + + + + + + /** + * Unit tests the {@code EdgeWeightedGraph} data type. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + int in = 3; + EdgeWeightedGraph G = new EdgeWeightedGraph(in); + StdOut.println(G); + } + + +} \ No newline at end of file diff --git a/NaiveStringMatching.java b/NaiveStringMatching.java new file mode 100644 index 0000000..3eff3c5 --- /dev/null +++ b/NaiveStringMatching.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; + + +public class NaiveStringMatching{ + + public static ArrayList nativeStringMatching(String mother, String son){ + ArrayList index = new ArrayList(); + if (mother.isEmpty() || son.isEmpty()||son.length()> mother.length()){ + index.add(-1); + return index; + } + + int m = mother.length(); + int n = son.length(); + + for(int i=0;i result = nativeStringMatching(mother, son); + for(int i:result){ + System.out.println(i); + } + +} + +} + +