From 7dead95ef1fcb4b4db4cd34f0c9c2948a68de3db Mon Sep 17 00:00:00 2001 From: Kevin Date: Thu, 12 Oct 2017 20:04:50 -0400 Subject: [PATCH 1/2] Add a bag data type --- data_structures/Bag/Bag.java | 123 +++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 data_structures/Bag/Bag.java diff --git a/data_structures/Bag/Bag.java b/data_structures/Bag/Bag.java new file mode 100644 index 000000000000..17b5cca60a41 --- /dev/null +++ b/data_structures/Bag/Bag.java @@ -0,0 +1,123 @@ +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Scanner; + +/** + * The {@code Bag} class represents a bag (or multiset) of + * generic items. It supports insertion and iterating over the + * items in arbitrary order. + *

+ * This implementation uses a singly linked list with a static nested class Node. + * See {@link LinkedBag} for the version from the + * textbook that uses a non-static nested class. + * See {@link ResizingArrayBag} for a version that uses a resizing array. + * The add, isEmpty, and size operations + * take constant time. Iteration takes time proportional to the number of items. + *

+ * 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 bag + */ +public class Bag implements Iterable { + private Node first; // beginning of bag + private int n; // number of elements in bag + + // helper linked list class + private static class Node { + private Item item; + private Node next; + } + + /** + * Initializes an empty bag. + */ + public Bag() { + first = null; + n = 0; + } + + /** + * Returns true if this bag is empty. + * + * @return {@code true} if this bag is empty; + * {@code false} otherwise + */ + public boolean isEmpty() { + return first == null; + } + + /** + * Returns the number of items in this bag. + * + * @return the number of items in this bag + */ + public int size() { + return n; + } + + /** + * Adds the item to this bag. + * + * @param item the item to add to this bag + */ + public void add(Item item) { + Node oldfirst = first; + first = new Node(); + first.item = item; + first.next = oldfirst; + n++; + } + + + /** + * Returns an iterator that iterates over the items in this bag in arbitrary order. + * + * @return an iterator that iterates over the items in this bag in arbitrary 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 Bag} data type. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Bag bag = new Bag(); + while (scanner.hasNext()) { + String item = scanner.next(); + bag.add(item); + } + + System.out.println("size of bag = " + bag.size()); + for (String s : bag) { + System.out.println(s); + } + } + +} \ No newline at end of file From 88b2c9a6c2faead2d665ace05fa3abd1e954516b Mon Sep 17 00:00:00 2001 From: Kevin Date: Thu, 12 Oct 2017 20:13:48 -0400 Subject: [PATCH 2/2] Add Digraph --- data_structures/Digraphs/Bag$1.class | Bin 0 -> 157 bytes .../Digraphs/Bag$ListIterator.class | Bin 0 -> 1073 bytes data_structures/Digraphs/Bag$Node.class | Bin 0 -> 880 bytes data_structures/Digraphs/Bag.class | Bin 0 -> 1992 bytes data_structures/Digraphs/Bag.java | 123 ++++++++++ data_structures/Digraphs/Digraph.class | Bin 0 -> 4093 bytes data_structures/Digraphs/Digraph.java | 227 ++++++++++++++++++ 7 files changed, 350 insertions(+) create mode 100644 data_structures/Digraphs/Bag$1.class create mode 100644 data_structures/Digraphs/Bag$ListIterator.class create mode 100644 data_structures/Digraphs/Bag$Node.class create mode 100644 data_structures/Digraphs/Bag.class create mode 100644 data_structures/Digraphs/Bag.java create mode 100644 data_structures/Digraphs/Digraph.class create mode 100644 data_structures/Digraphs/Digraph.java diff --git a/data_structures/Digraphs/Bag$1.class b/data_structures/Digraphs/Bag$1.class new file mode 100644 index 0000000000000000000000000000000000000000..f299598901109990313b44169882364e1d6dce4a GIT binary patch literal 157 zcmWknK?=e!5S+EGiBT|5@Zi}Z_yR@2gLv=-F%7XLB+yhJ=fMZ~C~>>X&ali3^ZmU) z0Ct!Q2!RTth=HIXsU@ap0!EYRZ~}wvw3(R_zQrH# z#RpA9j3n~rgCAvFXQs3g%p_;;v-jF--)83bpC3N~%wr*rK};r~Bd4^yhC%`nhS>-AV z#B0`$ZFn7rxOC64xUuHRW_gK#sJCmm*^L=-ksTTY_ zurk_8yWJ`P literal 0 HcmV?d00001 diff --git a/data_structures/Digraphs/Bag$Node.class b/data_structures/Digraphs/Bag$Node.class new file mode 100644 index 0000000000000000000000000000000000000000..d48463f82c3b7608425415640d85c8a586b1999b GIT binary patch literal 880 zcmaiyOH0E*6ot>EZ4zVDTHmkwXw_ChTXChO3k5+ax=>uWOY2Y~ZGncc z<0U${xa)Qr^2Bbj&pKsx{3|jsj8PLBbQ5WeYbb<^LDL1&f3Hy>|;fz?}15o)Y z6n@kIFFD8z<`jHf7=AWc*koDGf!s7XXa?2IQ+*IG|$?O?anC( zMu%<@bHT%GU$Gr4QOR#vrFC;FM-a^}FXoHxo@cnJpf%~5>3geYv94Fk_G6k6g`hz* zlTpwUUD-7snBzIq$&TOH+O^W|jKl~>YiYye8gr6`eUZ~D&`4Mt$SqHu~nm2herxjzz*mf2Dh6(nLW( zSk+UDXcxxgPO;*$vzD1B$eB93Ur`8@wquqP)+63Y)$z7d4F-Exq0UT>vQVMTaey^4 z_BcSZSu9!(@6o9L9yMs~>%)m*GqbbNc>N~%!qvGzb;vE$JQQ?$b7KX*$V|T|dE}(_ zH$`TFC+n$?1{e4$I}c6(0seRic)rAUYXDLHc^`Ogri^!l>nNWtQ?77tj~zgXDbEpz z1)n4M14RnPxOVZq3j(PG3KOP{Fbc*oQ3sG+09s=|BJevjbsuW*dkO-cyF>$dKFPHS zftIUcP1TSOAmO{Ng!J|=-yV~0>v$^n`rV+w{}pm{?M zBQKzB#8QM)@17{6pOpjGn8hMGv4nms;~iWlcD&xB4;YVEuO9Cr<9UT0B9w{=^Z~+8 z3E@xiX5IB;_GTKAu%!AM6K&$Ya|k{43@r!zZXBXDb%3_j;VRmnpo3dSVq~<6&i$8v zJww+ax~V?Z)l)_9NEN56I8#Mm75#j8D>3>L&MJ6ImG z_ZV7ucDNS!eJira`y@mOgM7Hq)$ literal 0 HcmV?d00001 diff --git a/data_structures/Digraphs/Bag.java b/data_structures/Digraphs/Bag.java new file mode 100644 index 000000000000..17b5cca60a41 --- /dev/null +++ b/data_structures/Digraphs/Bag.java @@ -0,0 +1,123 @@ +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Scanner; + +/** + * The {@code Bag} class represents a bag (or multiset) of + * generic items. It supports insertion and iterating over the + * items in arbitrary order. + *

+ * This implementation uses a singly linked list with a static nested class Node. + * See {@link LinkedBag} for the version from the + * textbook that uses a non-static nested class. + * See {@link ResizingArrayBag} for a version that uses a resizing array. + * The add, isEmpty, and size operations + * take constant time. Iteration takes time proportional to the number of items. + *

+ * 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 bag + */ +public class Bag implements Iterable { + private Node first; // beginning of bag + private int n; // number of elements in bag + + // helper linked list class + private static class Node { + private Item item; + private Node next; + } + + /** + * Initializes an empty bag. + */ + public Bag() { + first = null; + n = 0; + } + + /** + * Returns true if this bag is empty. + * + * @return {@code true} if this bag is empty; + * {@code false} otherwise + */ + public boolean isEmpty() { + return first == null; + } + + /** + * Returns the number of items in this bag. + * + * @return the number of items in this bag + */ + public int size() { + return n; + } + + /** + * Adds the item to this bag. + * + * @param item the item to add to this bag + */ + public void add(Item item) { + Node oldfirst = first; + first = new Node(); + first.item = item; + first.next = oldfirst; + n++; + } + + + /** + * Returns an iterator that iterates over the items in this bag in arbitrary order. + * + * @return an iterator that iterates over the items in this bag in arbitrary 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 Bag} data type. + * + * @param args the command-line arguments + */ + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + Bag bag = new Bag(); + while (scanner.hasNext()) { + String item = scanner.next(); + bag.add(item); + } + + System.out.println("size of bag = " + bag.size()); + for (String s : bag) { + System.out.println(s); + } + } + +} \ No newline at end of file diff --git a/data_structures/Digraphs/Digraph.class b/data_structures/Digraphs/Digraph.class new file mode 100644 index 0000000000000000000000000000000000000000..7be47e26262770c93152bfa826ef605b82fac747 GIT binary patch literal 4093 zcmb7H`F9i775>JOJ+eG3Q7{HefD)G2k{1er1Pl}iPHJjw5)&M=#barZ2V_Z=Ml5Ml zNJCd332jK*K$Ad|I&IT75G+F+AW75phi++4Pfwd}r$6+x|3Jebb-z0^wuEudX^)TI zd-L9Xclqvj?~H%?@7J#YxD!A2V;K@E`h76{D8rsgG-0m{Nf`!Iq*QE>W!ev)NM2gAR))hO^*I%v_hTUvK72vuqcR-x;ke9Ch|(uT>?su|%%EAa9X_onjg>MdAad|4`=+`IjcbJXzgxq>u6OFXy2pn)0>le zD$(3!WzAHgMS-%Fzc&6T;L+oI6jW?)U$4tiWtW*q=~g~#CYYJML3r3Tu)zF4c1-BPXv?Y^9 zLQk&CCh`MD%4$6jGcuN$rlqA0=;8G4Fuk_Sn2`&csjwb)6@~}$IV;>}gj4BMiaIQF zpCS5R)UX!oG_055K754WlNuWC!3G7l*p~B_nQZQg>AaU!@sfsbU{J2Utl^t@kfu|1 zzW*=N3Kkb{8O-Vb;%zq`QV=fs)RFGW$NF27#sn;)X3C}x0m$U7@a}YWK(_>qF)U)~ zRL;ugV^%sVfqY9acu-aw1qiP0!wzz}XvyZVhHv8)@>9ci@Ldhx!>eNm+4bgDi-vQe z;XGc`Z~;Ra3K&*UQ_P`5p7nV%88@<|nWW1&5Y})Jmt=UIv=o8V*4)2iC9=Q^m}ZbaLNo0ytd?GAKKXSBBJ$vmr9CGGM?=WZ$d z8yl0`NvSK7&-E)wCG+KFak}?y;qC{3xHEhZi2sZINLp!PA&Bg0h}~XBghA zk>C)@Bc35tM1pVlhoDA+m*IO8l|%4*R)>OTF*9-j{?G_~J;SK#I#Q+#j{ftUZLXbT z1b&Wp&_ErXt49rYLWp8M8t8l@-EX3+jdW@;Hc@g0JfjpWQ_-OS*D*)A#yjF{r{k=$ zg1Rawc}AQaf!1>#Q-(3MJrXTonmBs_?8 z3}6jU)-telgk?RJut%r_fcl)acVfq=M%V}8ar_koAClQ z3TTVq8>J!vP31OWn@!kiuOpybhoZcXx$9NjUuDDifD2>9h4Cf9ZRRj)WS+%5Gpi0P zGdQWCXsCeMopxIP!6Okqi|hz$neJdmRC2$hfY3_sZ0{vziywvaWHnb|tDaXtczJna zb@@fyR>1AugQM>?7BIg=cK!renxsDW!h*rk-`R$b75OB<0o(X_x*gN8gT&v-kJcSz z)Gl(Vm*DFB>%(5ekU|{CVc-;Y^UHJ>UPQkQSF^wsfX9YQXm$;=1g8&BtD;NAmTOpe z9pzlSkNRt@E=AtK4sMvknO7X1y~2fJr?$f0%y8sOnxm9esc6MS(Szg!-ryN(Y*!(qblm>sSc zWm+BW@Ds(g_7HO~_1+K(4s!^}K;VN*LUy7S@IejjX!7=UMtUxw!rMz)hz%#yTD$y? z(&J++?&D*pLU+8Om>|H}zOQ{2ufmIi=`ZX*qs&NXwmI4L^%CP%C6mh-B literal 0 HcmV?d00001 diff --git a/data_structures/Digraphs/Digraph.java b/data_structures/Digraphs/Digraph.java new file mode 100644 index 000000000000..06885ab46da3 --- /dev/null +++ b/data_structures/Digraphs/Digraph.java @@ -0,0 +1,227 @@ +import java.util.NoSuchElementException; +import java.util.Stack; +import java.util.Scanner; +/** + * The {@code Digraph} class represents a directed graph of vertices + * named 0 through V - 1. + * It supports the following two primary operations: add an edge to the digraph, + * iterate over all of the vertices adjacent from a given vertex. + * Parallel edges and self-loops are permitted. + *

+ * This implementation uses an adjacency-lists representation, which + * is a vertex-indexed array of {@link Bag} objects. + * All operations take constant time (in the worst case) except + * iterating over the vertices adjacent from a given vertex, which takes + * time proportional to the number of such vertices. + *

+ * For additional documentation, + * see Section 4.2 of + * Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne. + * + * @author Robert Sedgewick + * @author Kevin Wayne + */ + +public class Digraph { + private static final String NEWLINE = System.getProperty("line.separator"); + + private final int V; // number of vertices in this digraph + private int E; // number of edges in this digraph + private Bag[] adj; // adj[v] = adjacency list for vertex v + private int[] indegree; // indegree[v] = indegree of vertex v + + /** + * Initializes an empty digraph with V vertices. + * + * @param V the number of vertices + * @throws IllegalArgumentException if {@code V < 0} + */ + public Digraph(int V) { + if (V < 0) throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); + this.V = V; + this.E = 0; + indegree = new int[V]; + adj = (Bag[]) new Bag[V]; + for (int v = 0; v < V; v++) { + adj[v] = new Bag(); + } + } + + /** + * Initializes a digraph from the specified input stream. + * The format is the number of vertices V, + * followed by the number of edges E, + * followed by E pairs of vertices, with each entry separated by whitespace. + * + * @param in the input stream + * @throws IllegalArgumentException if the endpoints of any edge are not in prescribed range + * @throws IllegalArgumentException if the number of vertices or edges is negative + * @throws IllegalArgumentException if the input stream is in the wrong format + */ + public Digraph() { + Scanner in = new Scanner(System.in); + try { + this.V = in.nextInt(); + if (V < 0) throw new IllegalArgumentException("number of vertices in a Digraph must be nonnegative"); + indegree = new int[V]; + adj = (Bag[]) new Bag[V]; + for (int v = 0; v < V; v++) { + adj[v] = new Bag(); + } + int E = in.nextInt(); + if (E < 0) throw new IllegalArgumentException("number of edges in a Digraph must be nonnegative"); + for (int i = 0; i < E; i++) { + int v = in.nextInt(); + int w = in.nextInt(); + addEdge(v, w); + } + } + catch (NoSuchElementException e) { + throw new IllegalArgumentException("invalid input format in Digraph constructor", e); + } + } + + /** + * Initializes a new digraph that is a deep copy of the specified digraph. + * + * @param G the digraph to copy + */ + public Digraph(Digraph G) { + this(G.V()); + this.E = G.E(); + for (int v = 0; v < V; v++) + this.indegree[v] = G.indegree(v); + for (int v = 0; v < G.V(); v++) { + // reverse so that adjacency list is in same order as original + Stack reverse = new Stack(); + for (int w : G.adj[v]) { + reverse.push(w); + } + for (int w : reverse) { + adj[v].add(w); + } + } + } + + /** + * Returns the number of vertices in this digraph. + * + * @return the number of vertices in this digraph + */ + public int V() { + return V; + } + + /** + * Returns the number of edges in this digraph. + * + * @return the number of edges in this digraph + */ + public int E() { + return E; + } + + + // throw an IllegalArgumentException unless {@code 0 <= v < V} + private void validateVertex(int v) { + if (v < 0 || v >= V) + throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1)); + } + + /** + * Adds the directed edge v→w to this digraph. + * + * @param v the tail vertex + * @param w the head vertex + * @throws IllegalArgumentException unless both {@code 0 <= v < V} and {@code 0 <= w < V} + */ + public void addEdge(int v, int w) { + validateVertex(v); + validateVertex(w); + adj[v].add(w); + indegree[w]++; + E++; + } + + /** + * Returns the vertices adjacent from vertex {@code v} in this digraph. + * + * @param v the vertex + * @return the vertices adjacent from vertex {@code v} in this digraph, as an iterable + * @throws IllegalArgumentException unless {@code 0 <= v < V} + */ + public Iterable adj(int v) { + validateVertex(v); + return adj[v]; + } + + /** + * Returns the number of directed edges incident from vertex {@code v}. + * This is known as the outdegree of vertex {@code v}. + * + * @param v the vertex + * @return the outdegree of vertex {@code v} + * @throws IllegalArgumentException unless {@code 0 <= v < V} + */ + public int outdegree(int v) { + validateVertex(v); + return adj[v].size(); + } + + /** + * Returns the number of directed edges incident to vertex {@code v}. + * This is known as the indegree of vertex {@code v}. + * + * @param v the vertex + * @return the indegree of vertex {@code v} + * @throws IllegalArgumentException unless {@code 0 <= v < V} + */ + public int indegree(int v) { + validateVertex(v); + return indegree[v]; + } + + /** + * Returns the reverse of the digraph. + * + * @return the reverse of the digraph + */ + public Digraph reverse() { + Digraph reverse = new Digraph(V); + for (int v = 0; v < V; v++) { + for (int w : adj(v)) { + reverse.addEdge(w, v); + } + } + return reverse; + } + + /** + * Returns a string representation of the graph. + * + * @return the number of vertices V, followed by the number of edges E, + * followed by the V adjacency lists + */ + public String toString() { + StringBuilder s = new StringBuilder(); + s.append(V + " vertices, " + E + " edges " + NEWLINE); + for (int v = 0; v < V; v++) { + s.append(String.format("%d: ", v)); + for (int w : adj[v]) { + s.append(String.format("%d ", w)); + } + s.append(NEWLINE); + } + return s.toString(); + } + + public static void main(String args[]) { + int V = Integer.parseInt(args[0]); + Digraph G = new Digraph(V); + System.out.println(G); + G.addEdge(0,1); + System.out.println(G); + System.out.println(G.reverse()); + } + +} \ No newline at end of file