├── .gitignore ├── src ├── main │ └── java │ │ └── com │ │ ├── datastructure │ │ ├── sort │ │ │ ├── Test.class │ │ │ ├── Person.class │ │ │ ├── Sorter.class │ │ │ ├── GnomeSortPeople.class │ │ │ ├── smallData.dat │ │ │ ├── Sorter.java │ │ │ ├── GnomeSortPeople.java │ │ │ └── Person.java │ │ ├── Trees │ │ │ ├── RedBlackSearchTree.java │ │ │ ├── TwoTreeSearchTree.java │ │ │ ├── Node.java │ │ │ └── BinarySearchTree.java │ │ ├── Helper │ │ │ ├── DrawListener.java │ │ │ ├── StreamUtil.java │ │ │ ├── SortCompare.java │ │ │ ├── Stopwatch.java │ │ │ ├── StdOut.java │ │ │ ├── Out.java │ │ │ ├── StdArrayIO.java │ │ │ ├── BinaryStdOut.java │ │ │ ├── BinaryStdIn.java │ │ │ ├── StdIn.java │ │ │ ├── StdAudio.java │ │ │ ├── BinaryOut.java │ │ │ ├── StdStats.java │ │ │ ├── BinaryIn.java │ │ │ ├── StdRandom.java │ │ │ ├── StdInTest.java │ │ │ └── In.java │ │ ├── Basic │ │ │ ├── Node.java │ │ │ ├── DataStore.java │ │ │ ├── Stack.java │ │ │ ├── Queue.java │ │ │ ├── LinkedStack.java │ │ │ ├── LinkedQueue.java │ │ │ ├── Permutations.java │ │ │ └── BinarySearch.java │ │ ├── Recursion │ │ │ ├── Factorial.java │ │ │ ├── Triangle.java │ │ │ └── Anagram.java │ │ ├── Sorting │ │ │ ├── Selection.java │ │ │ ├── Insertion.java │ │ │ ├── Shell.java │ │ │ ├── Quick.java │ │ │ ├── AbstractSorter.java │ │ │ └── Merge.java │ │ ├── queue │ │ │ ├── PriorityQueue.java │ │ │ └── Queue.java │ │ ├── DynamicConnectivity │ │ │ ├── AbstractUnion.java │ │ │ ├── QuickUnion.java │ │ │ ├── QuickUnionFind.java │ │ │ └── WeightedQuickUnion.java │ │ ├── array │ │ │ ├── Person.java │ │ │ ├── OrderedArray.java │ │ │ └── GenericOrderedArray.java │ │ ├── stack │ │ │ └── StackDemo.java │ │ └── Graphs │ │ │ └── LinkedList.java │ │ ├── lintcode │ │ ├── SetsUtil.java │ │ └── StrUtils.java │ │ └── dataStructure │ │ └── DynamicConnectivity │ │ └── UF.java └── test │ ├── resources │ ├── tinyW.txt │ └── tinyT.txt │ └── java │ └── com │ ├── datastructure │ ├── SearchTest.java │ ├── KataTest.java │ ├── SortTest.java │ └── BasicTest.java │ └── lintcode │ ├── Subsets.java │ └── SubStr.java └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | bin 3 | target 4 | .classpath 5 | .project 6 | .settings 7 | src/main/webapp/META-INF 8 | .idea 9 | *.iml 10 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/Test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/DataStructure/master/src/main/java/com/datastructure/sort/Test.class -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/Person.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/DataStructure/master/src/main/java/com/datastructure/sort/Person.class -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/Sorter.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/DataStructure/master/src/main/java/com/datastructure/sort/Sorter.class -------------------------------------------------------------------------------- /src/test/resources/tinyW.txt: -------------------------------------------------------------------------------- 1 | 84 2 | 48 3 | 68 4 | 10 5 | 18 6 | 98 7 | 12 8 | 23 9 | 54 10 | 57 11 | 48 12 | 33 13 | 16 14 | 77 15 | 11 16 | 29 17 | -------------------------------------------------------------------------------- /src/test/resources/tinyT.txt: -------------------------------------------------------------------------------- 1 | 23 2 | 50 3 | 10 4 | 99 5 | 18 6 | 23 7 | 98 8 | 84 9 | 11 10 | 10 11 | 48 12 | 77 13 | 13 14 | 54 15 | 98 16 | 77 17 | 77 18 | 68 19 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/GnomeSortPeople.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/DataStructure/master/src/main/java/com/datastructure/sort/GnomeSortPeople.class -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Trees/RedBlackSearchTree.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Trees; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-5-22 6 | * Time: PM1:41 7 | */ 8 | public class RedBlackSearchTree { 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Trees/TwoTreeSearchTree.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Trees; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-5-22 6 | * Time: PM12:23 7 | */ 8 | public class TwoTreeSearchTree { 9 | 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Trees/Node.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Trees; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-5-15 6 | * Time: PM3:44 7 | */ 8 | public class Node { 9 | T item; 10 | Node left,right; 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/DrawListener.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Helper; 2 | public interface DrawListener { 3 | public void mousePressed (double x, double y); 4 | public void mouseDragged (double x, double y); 5 | public void mouseReleased(double x, double y); 6 | public void keyTyped(char c); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/lintcode/SetsUtil.java: -------------------------------------------------------------------------------- 1 | package com.lintcode; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by shawncao on 9/25/15. 8 | */ 9 | public class SetsUtil { 10 | public static ArrayList> subsets(ArrayList integers) { 11 | return null; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/dataStructure/DynamicConnectivity/UF.java: -------------------------------------------------------------------------------- 1 | package com.dataStructure.dynamicConnectivity; 2 | 3 | /** 4 | * User: Shawn cao 5 | * Date: 14-6-23 6 | * Time: AM10:35 7 | */ 8 | public class UF> { 9 | 10 | 11 | 12 | public boolean connected(T a, T b){ 13 | boolean flag = false; 14 | 15 | return flag; 16 | } 17 | 18 | public void union(T a, T b){ 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/Node.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/Node.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/Node.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-7 10 | * Time: PM3:49 11 | */ 12 | class Node { 13 | T item; 14 | Node next; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/DataStore.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/DataStore.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/DataStore.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-7 10 | * Time: PM4:06 11 | */ 12 | public interface DataStore { 13 | 14 | public int size(); 15 | public boolean isEmpty(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/Stack.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/Stack.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/Stack.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-7 10 | * Time: PM3:45 11 | */ 12 | public interface Stack extends DataStore{ 13 | 14 | public T pop(); 15 | public void push(T item); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/Queue.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/Queue.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/Queue.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-7 10 | * Time: PM3:44 11 | */ 12 | public interface Queue extends DataStore{ 13 | 14 | public void enqueue(T item); 15 | 16 | public T dequeue(); 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Recursion/Factorial.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Recursion/Factorial.java 2 | package com.dataStructure.recursion; 3 | ======= 4 | package com.datastructure.Recursion; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Recursion/Factorial.java 6 | 7 | public class Factorial { 8 | 9 | public static void main(String[] args) { 10 | System.out.println(recFactorial(6)); 11 | } 12 | 13 | public static int recFactorial(int n) { 14 | if (n == 1) 15 | return 1; 16 | else { 17 | System.out.println("n " + n); 18 | return n * recFactorial(n - 1); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/smallData.dat: -------------------------------------------------------------------------------- 1 | Reese, Jesse 2 | 2900 Fulham Ridge 3 | WINTON QLD 4735 4 | 5 | Gordon, Barbara 6 | 4206 Dobell Chase 7 | EIDSVOLD QLD 4627 8 | 9 | Palmer, Laura 10 | 642 Monaro Parade 11 | SANDY CREEK VIC 3695 12 | 13 | Pezzini, Sara 14 | 4555 White Crossing 15 | MOUNT EGERTON VIC 3352 16 | 17 | Hayes, Frank 18 | 2766 Benson Promenade 19 | KEW VIC 3101 20 | 21 | Pennyworth, Alfred 22 | 3529 Coolart Chase 23 | CRABOON NSW 2844 24 | 25 | Wayne, Helena 26 | 1603 Egan Crossing 27 | CONGO NSW 2537 28 | 29 | Redmond, Dinah 30 | 1785 Anzac Plaza 31 | SPRING RIDGE NSW 2343 32 | 33 | Avery, Jamie 34 | 710 Glenview Close 35 | LISAROW NSW 2250 36 | 37 | Doe, John 38 | 4804 Dale Avenue 39 | MACQUARIE CENTRE NSW 2113 40 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Recursion/Triangle.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Recursion/Triangle.java 2 | package com.dataStructure.recursion; 3 | ======= 4 | package com.datastructure.Recursion; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Recursion/Triangle.java 6 | 7 | public class Triangle { 8 | 9 | public static void main(String[] args) { 10 | System.out.println(recTriangle(5)); 11 | } 12 | 13 | public static int triangle(int n) { 14 | int total = 0; 15 | while (n > 0) { 16 | total += n; 17 | n--; 18 | } 19 | return total; 20 | } 21 | 22 | public static int recTriangle(int n){ 23 | if( n== 1) 24 | return 1; 25 | else{ 26 | System.out.println("n: " + n); 27 | return n + recTriangle(n-1); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Sorting/Selection.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Sorting/Selection.java 2 | package com.dataStructure.sorting; 3 | ======= 4 | package com.datastructure.Sorting; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Sorting/Selection.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-8 10 | * Time: PM6:25 11 | */ 12 | public class Selection extends AbstractSorter { 13 | 14 | @Override 15 | public void sort(Comparable[] arr) { 16 | for(int i = 0; i < arr.length; i++){ 17 | int min = i; 18 | for(int j = i+1; j < arr.length; j++){ 19 | if(less(arr[j],arr[min])) min=j; 20 | } 21 | exchange(arr ,i,min); 22 | show(arr); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/com/datastructure/SearchTest.java: -------------------------------------------------------------------------------- 1 | package com.datastructure; 2 | 3 | import com.datastructure.Trees.BinarySearchTree; 4 | import junit.framework.TestCase; 5 | import org.junit.Test; 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-15 10 | * Time: PM4:07 11 | */ 12 | public class SearchTest extends TestCase { 13 | 14 | @Test 15 | public void testBST(){ 16 | BinarySearchTree binarySearchTree = new BinarySearchTree<>(); 17 | binarySearchTree.put(2,"Two"); 18 | binarySearchTree.put(1,"One"); 19 | binarySearchTree.put(5,"Five"); 20 | binarySearchTree.put(3,"Three2"); 21 | binarySearchTree.put(9,"Nine"); 22 | binarySearchTree.put(3,"Three"); 23 | 24 | assertTrue(binarySearchTree.size() == 5); 25 | assertTrue(binarySearchTree.get(3).equals("Three")); 26 | } 27 | 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StreamUtil.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Helper; 2 | 3 | import com.google.common.base.Strings; 4 | 5 | import java.io.*; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | /** 10 | * User: Shawn cao 11 | * Date: 14-5-6 12 | * Time: PM5:58 13 | */ 14 | public class StreamUtil { 15 | 16 | public static Integer[] readAllInts(InputStream in){ 17 | BufferedReader br = new BufferedReader(new InputStreamReader(in)); 18 | List tmp = new LinkedList<>() ; 19 | String line=""; 20 | try { 21 | while(!Strings.isNullOrEmpty(line = br.readLine())){ 22 | tmp.add(Integer.parseInt(line.trim())); 23 | } 24 | } catch (IOException e) { 25 | e.printStackTrace(); 26 | } 27 | 28 | return tmp.toArray(new Integer[tmp.size()]); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/SortCompare.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Helper; 2 | 3 | import com.datastructure.Sorting.AbstractSorter; 4 | 5 | /** 6 | * User: Shawn cao 7 | * Date: 14-5-9 8 | * Time: PM1:34 9 | */ 10 | public class SortCompare { 11 | 12 | public static double time(AbstractSorter sorter , Comparable[] arr){ 13 | Stopwatch timer = new Stopwatch(); 14 | sorter.sort(arr); 15 | return timer.elapsedTime() ; 16 | } 17 | 18 | public static double timeRandomInput(AbstractSorter sorter, int N , int T){ 19 | 20 | double total = 0.0; 21 | Double[] arr = new Double[N]; 22 | for(int t = 0; t < T; t++){ 23 | for(int i = 0; i < N ; i ++){ 24 | 25 | arr[i] = StdRandom.uniform(); 26 | } 27 | total += time(sorter, arr); 28 | } 29 | return total; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Sorting/Insertion.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Sorting/Insertion.java 2 | package com.dataStructure.sorting; 3 | ======= 4 | package com.datastructure.Sorting; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Sorting/Insertion.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-9 10 | * Time: AM10:56 11 | */ 12 | public class Insertion extends AbstractSorter { 13 | @Override 14 | public void sort(Comparable[] arr) { 15 | int len = arr.length; 16 | for(int i = 1; i < len ; i++){ 17 | for( int j = i; j > 0 && less(arr[j],arr[j-1] ); j--){ 18 | exchange(arr , j-1 , j); 19 | show(arr); 20 | } 21 | 22 | } 23 | } 24 | 25 | public static void main(String[] args){ 26 | 27 | new Insertion().sort(new Integer[]{15,33,34, 45, 77, 72, 80, 94, 29, 26}); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/queue/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.queue; 2 | 3 | import java.lang.reflect.Array; 4 | 5 | public class PriorityQueue> { 6 | private int size; 7 | private T[] arr; 8 | private int n; 9 | 10 | public PriorityQueue(Class clazz, int size) { 11 | this.size = size; 12 | arr = (T[]) Array.newInstance(clazz, size); 13 | n = 0; 14 | } 15 | 16 | public void insert(T item) { 17 | int j; 18 | if (n == 0) 19 | arr[n++] = item; 20 | else { 21 | for (j = n - 1; j > 0; j--) { 22 | if (item.compareTo(arr[j]) > 0) { 23 | arr[j + 1] = arr[j]; 24 | } else { 25 | break; 26 | } 27 | } 28 | arr[j + 1] = item; 29 | n++; 30 | } 31 | } 32 | 33 | public T remove() { 34 | return arr[--n]; 35 | } 36 | 37 | public T peekMin() { 38 | return arr[n - 1]; 39 | } 40 | 41 | public boolean isEmpty() { 42 | return n == 0; 43 | } 44 | 45 | public boolean isFull() { 46 | return n == size; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/DynamicConnectivity/AbstractUnion.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/DynamicConnectivity/AbstractUnion.java 2 | package com.dataStructure.dynamicConnectivity; 3 | ======= 4 | package com.datastructure.DynamicConnectivity; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/DynamicConnectivity/AbstractUnion.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-6-23 10 | * Time: PM5:48 11 | */ 12 | public abstract class AbstractUnion { 13 | public int[] ids; 14 | public void init(int N){ 15 | ids = new int[N]; 16 | for(int i=0; i>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/LinkedStack.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-7 10 | * Time: PM3:32 11 | */ 12 | public class LinkedStack implements Stack{ 13 | 14 | 15 | 16 | private Node first; 17 | private int N; 18 | 19 | public boolean isEmpty(){ 20 | return first == null; 21 | } 22 | 23 | public int size(){ 24 | return N; 25 | } 26 | 27 | public void push(T t){ 28 | Node oldFirst = first; 29 | first = new Node(); 30 | first.item = t; 31 | first.next = oldFirst; 32 | N++; 33 | } 34 | 35 | public T pop(){ 36 | if(isEmpty()) return null; 37 | T t = first.item; 38 | first = first.next; 39 | N--; 40 | return t; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/lintcode/Subsets.java: -------------------------------------------------------------------------------- 1 | package com.lintcode; 2 | 3 | import com.google.common.collect.Lists; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.junit.runners.JUnit4; 7 | 8 | import java.util.ArrayList; 9 | 10 | import java.util.List; 11 | 12 | import static java.util.Arrays.asList; 13 | import static org.hamcrest.MatcherAssert.assertThat; 14 | import static org.hamcrest.Matchers.is; 15 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize; 16 | import static org.hamcrest.core.CombinableMatcher.both; 17 | import static org.hamcrest.core.IsCollectionContaining.hasItems; 18 | 19 | 20 | 21 | /** 22 | * Created by shawncao on 9/25/15. 23 | */ 24 | @RunWith(JUnit4.class) 25 | public class Subsets { 26 | 27 | @Test 28 | public void test_non_empty_subsets(){ 29 | ArrayList>ints = Lists.newArrayList(asList(1), asList(2),asList(3),asList(1,2,3),asList(1,3),asList(1,2),asList(2,3),asList()); 30 | assertThat(SetsUtil.subsets(Lists.newArrayList(1, 2, 3)), is(ints)); 31 | } 32 | 33 | 34 | 35 | 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/lintcode/SubStr.java: -------------------------------------------------------------------------------- 1 | package com.lintcode; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.junit.runners.JUnit4; 6 | 7 | import static org.hamcrest.MatcherAssert.assertThat; 8 | import static org.junit.Assert.assertEquals; 9 | 10 | /** 11 | * Created by shawncao on 9/25/15. 12 | */ 13 | @RunWith(JUnit4.class) 14 | public class SubStr { 15 | 16 | @Test 17 | public void find_pattern_in_mid_given_str(){ 18 | assertEquals("should find given str and return 3", 3, StrUtils.strStr("source","rc")); 19 | } 20 | 21 | @Test 22 | public void find_pattern_in_last_given_str(){ 23 | assertEquals("should find given str and return 1", 4, StrUtils.strStr("source","ce")); 24 | } 25 | 26 | @Test 27 | public void find_pattern_in_begin_given_str(){ 28 | assertEquals("should find given str and return 1", 0, StrUtils.strStr("source","sou")); 29 | } 30 | 31 | @Test 32 | public void find_pattern_perfect_match_given_str(){ 33 | assertEquals("should find given str and return 1", 0, StrUtils.strStr("source","source")); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/Stopwatch.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Stopwatch.java 3 | * 4 | * 5 | *************************************************************************/ 6 | package com.datastructure.Helper; 7 | /** 8 | * Stopwatch. This class is a data type for measuring 9 | * the running time (wall clock) of a program. 10 | *

11 | * For additional documentation, see 12 | * Section 3.2 of 13 | * Introduction to Programming in Java: An Interdisciplinary Approach 14 | * by Robert Sedgewick and Kevin Wayne. 15 | */ 16 | 17 | 18 | 19 | public class Stopwatch { 20 | 21 | private final long start; 22 | 23 | /** 24 | * Create a stopwatch object. 25 | */ 26 | public Stopwatch() { 27 | start = System.currentTimeMillis(); 28 | } 29 | 30 | 31 | /** 32 | * Return elapsed time (in seconds) since this object was created. 33 | */ 34 | public double elapsedTime() { 35 | long now = System.currentTimeMillis(); 36 | return (now - start) / 1000.0; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/LinkedQueue.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/LinkedQueue.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/LinkedQueue.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-7 10 | * Time: PM3:40 11 | */ 12 | public class LinkedQueue implements Queue { 13 | 14 | private Node first; 15 | private Node last; 16 | private int N; 17 | 18 | 19 | public int size(){ 20 | return N; 21 | } 22 | 23 | public boolean isEmpty(){ 24 | return first==null; 25 | } 26 | 27 | @Override 28 | public void enqueue(T item) { 29 | Node oldLast = last ; 30 | last = new Node(); 31 | last.item = item; 32 | last.next = null; 33 | if(isEmpty()) 34 | first = last ; 35 | else 36 | oldLast.next = last; 37 | N++; 38 | } 39 | 40 | @Override 41 | public T dequeue() { 42 | if(isEmpty()) return null; 43 | T t = first.item; 44 | first = first.next; 45 | N--; 46 | return t; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/array/Person.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.array; 2 | 3 | public class Person implements Comparable{ 4 | private String firstName; 5 | private String lastName; 6 | private int age; 7 | 8 | public Person(String firstName,String lastName,int age) { 9 | this.firstName = firstName; 10 | this.lastName = lastName; 11 | this.age = age; 12 | } 13 | 14 | public String getFirstName() { 15 | return firstName; 16 | } 17 | 18 | public void setFirstName(String firstName) { 19 | this.firstName = firstName; 20 | } 21 | 22 | public String getLastName() { 23 | return lastName; 24 | } 25 | 26 | public void setLastName(String lastName) { 27 | this.lastName = lastName; 28 | } 29 | 30 | public int getAge() { 31 | return age; 32 | } 33 | 34 | public void setAge(int age) { 35 | this.age = age; 36 | } 37 | 38 | @Override 39 | public int compareTo(Person o) { 40 | int val = this.getFirstName().compareTo(o.getFirstName()); 41 | if(val==0){ 42 | val = this.getLastName().compareTo(o.getLastName()); 43 | if(val == 0) 44 | val = this.getAge()-o.getAge(); 45 | } 46 | return val; 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]"; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Sorting/Shell.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Sorting/Shell.java 2 | package com.dataStructure.sorting; 3 | ======= 4 | package com.datastructure.Sorting; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Sorting/Shell.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-9 10 | * Time: PM2:39 11 | */ 12 | public class Shell extends AbstractSorter { 13 | @Override 14 | public void sort(Comparable[] arr) { 15 | int N = arr.length; 16 | int h = 1 ; 17 | 18 | while( h < N /3) h = h*3 + 1; // 1 , 4, 13 ... 19 | while ( h > 0 ){ 20 | for(int i = h; i < N ; i++){ 21 | // System.out.println(" i " + i + " ---"); 22 | for(int k = i; k >= h && less(arr[k] , arr[k - h]); k -= h){ 23 | // System.out.println("exchange for: " + (k-h)+" : " + arr[k-h] + " | " + k + " : "+ arr[k]); 24 | exchange(arr , k , k - h); 25 | } 26 | // System.out.println("######"); 27 | } 28 | super.show(arr); 29 | h = h/3 ; 30 | } 31 | } 32 | 33 | public static void main(String[] args){ 34 | 35 | new Shell().sort(new Integer[]{88, 26, 36, 67, 86, 82, 17, 78, 85, 60 }); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/Permutations.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/Permutations.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/Permutations.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-6-8 10 | * Time: PM10:26 11 | */ 12 | public class Permutations { 13 | 14 | public void permute(String value, int startIndex, int endIndex) { 15 | 16 | if (startIndex == endIndex) { 17 | System.out.printf("%s\n", value); 18 | } else { 19 | for (int currIndex = startIndex; currIndex <= endIndex; currIndex++) { 20 | 21 | value = swap(value, startIndex, currIndex); 22 | permute(value, startIndex + 1, endIndex); 23 | value = swap(value, startIndex, currIndex); 24 | } 25 | } 26 | } 27 | 28 | private String swap(String value, int idxOne, int idxTwo) { 29 | char[] charArray = value.toCharArray(); 30 | char temp = value.charAt(idxOne); 31 | charArray[idxOne] = charArray[idxTwo]; 32 | charArray[idxTwo] = temp; 33 | return new String(charArray); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Recursion/Anagram.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Recursion/Anagram.java 2 | package com.dataStructure.recursion; 3 | ======= 4 | package com.datastructure.Recursion; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Recursion/Anagram.java 6 | 7 | public class Anagram { 8 | 9 | static int size; 10 | int count = 0; 11 | char[] inputs; 12 | 13 | public void getInput(String input){ 14 | size = input.length(); 15 | inputs = new char[size]; 16 | for(int i= 0 ; i < size; i++){ 17 | inputs[i] = input.charAt(i); 18 | } 19 | } 20 | 21 | public void doAnagram(int splitSize){ 22 | if(splitSize == 1) 23 | return; 24 | for(int i = 0 ; i < splitSize; i++){ 25 | doAnagram(splitSize - 1); 26 | if(splitSize == 2){ 27 | for(int j = 0; j < size; j++){ 28 | System.out.print(inputs[j]); 29 | //System.out.println(); 30 | } 31 | System.out.println( "" + count++); 32 | rotate(splitSize); 33 | } 34 | } 35 | } 36 | 37 | public void rotate(int splitSize){ 38 | int j; 39 | int position = size - splitSize; 40 | char temp = inputs[position]; 41 | for(j = position + 1; j { 6 | private int front; 7 | private int rear; 8 | private T[] arr; 9 | private int size; 10 | 11 | public Queue(Class clazz, int size) { 12 | arr = (T[]) Array.newInstance(clazz, size); 13 | this.size = size + 1; 14 | front = 0; 15 | rear = -1; 16 | } 17 | 18 | public void insert(T t) { 19 | if (rear == size - 1) { 20 | rear = -1; 21 | } 22 | arr[++rear] = t; 23 | } 24 | 25 | public T remove() { 26 | T temp = arr[front++]; 27 | if (front == size) { 28 | front = 0; 29 | } 30 | return temp; 31 | } 32 | 33 | public T peekFront() { 34 | return arr[front]; 35 | } 36 | 37 | public boolean isEmpty() { 38 | return (rear+1 == front || (front + size - 1 == rear)); 39 | } 40 | 41 | public boolean isFull() { 42 | return rear+2 == front || (front + size -2) == rear; 43 | } 44 | 45 | public void display() { 46 | for (int i = 0; i < arr.length; i++) { 47 | System.out.print(" " + arr[i]); 48 | } 49 | System.out.println(" ... "); 50 | } 51 | 52 | public static void main(String[] args) { 53 | Queue queue = new Queue<>(Integer.class, 5); 54 | queue.insert(1); 55 | queue.insert(2); 56 | queue.insert(3); 57 | queue.insert(4); 58 | queue.insert(5); 59 | for (int i = 0; i < 5; i++) { 60 | System.out.println(queue.remove()); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/stack/StackDemo.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.stack; 2 | 3 | import java.lang.reflect.Array; 4 | 5 | public class StackDemo { 6 | 7 | private int max; 8 | private T[] stack; 9 | private int nElements; 10 | 11 | public StackDemo(Class clazz, int max) { 12 | this.max = max; 13 | stack = (T[]) Array.newInstance(clazz, max); 14 | nElements = -1; 15 | } 16 | 17 | public void push(T t) { 18 | stack[++nElements] = t; 19 | } 20 | 21 | public T pop(){ 22 | return stack[nElements--]; 23 | } 24 | 25 | public T peek(){ 26 | return stack[nElements]; 27 | } 28 | 29 | public boolean isEmpty(){ 30 | return nElements == -1; 31 | } 32 | 33 | public boolean isFull(){ 34 | return nElements == max-1; 35 | } 36 | 37 | public static void main(String[] args) { 38 | /* StackDemo stackDemo = new StackDemo<>(Integer.class, 5); 39 | stackDemo.push(10); 40 | stackDemo.push(11); 41 | stackDemo.push(9); 42 | 43 | System.out.println(stackDemo.pop()); 44 | System.out.println(stackDemo.pop());*/ 45 | 46 | String input = args[0]; 47 | int size = input.length(); 48 | StackDemo charStackDemo = new StackDemo<>(Character.class, size); 49 | for(int i=0; i>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/DynamicConnectivity/QuickUnion.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-6-23 10 | * Time: PM5:32 11 | */ 12 | public class QuickUnion extends AbstractUnion { 13 | 14 | 15 | public QuickUnion(int N){ 16 | init(N); 17 | } 18 | 19 | private int root(int i){ 20 | while(i != ids[i]) i = ids[i]; 21 | return i; 22 | } 23 | 24 | public boolean connected(int p, int q){ 25 | return root(p) == root(q); 26 | } 27 | 28 | public void union(int p, int q){ 29 | int pRoot = root(p); 30 | int qRoot = root(q); 31 | ids[pRoot] = qRoot; 32 | printArr(ids); 33 | } 34 | 35 | public static void main(String[] args){ 36 | QuickUnion quickUnion = new QuickUnion(10); 37 | // 38 | 39 | quickUnion.union(7,8); 40 | quickUnion.union( 0,9 ); 41 | quickUnion.union(9,8); 42 | quickUnion.union( 2,6 ); 43 | quickUnion.union( 3,2); 44 | quickUnion.union( 1,3 ); 45 | quickUnion.union( 5,3); 46 | quickUnion.union( 7,1 ); 47 | quickUnion.union(9,4); 48 | 49 | 50 | 51 | } 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/array/OrderedArray.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.array; 2 | 3 | public class OrderedArray { 4 | private int[] a; 5 | private int n; 6 | 7 | public OrderedArray(int max){ 8 | a = new int[max]; 9 | } 10 | 11 | public int size(){ 12 | return n; 13 | } 14 | 15 | public int find(int searchKey){ 16 | int lowerBound =0; 17 | int higherBound = n- 1; 18 | int curIndex; 19 | 20 | while(true){ 21 | curIndex = (lowerBound + higherBound)/2; 22 | if(a[curIndex] == searchKey) 23 | return curIndex; 24 | else if(lowerBound > higherBound) 25 | return n; 26 | else{ 27 | if(a[curIndex] value) 41 | break; 42 | for(int k=n;k>j;k--){ 43 | a[k]= a[k-1]; 44 | } 45 | a[j] = value; 46 | n++; 47 | } 48 | } 49 | 50 | public boolean delete(int value){ 51 | int j = find(value); 52 | if(j == -1) 53 | return false; 54 | else { 55 | for(int k=j;k>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Graphs/LinkedList.java 6 | 7 | public class LinkedList { 8 | private Node first; 9 | private Node last; 10 | private int size; 11 | 12 | private void LinkedFirst() { 13 | } 14 | 15 | public void add(E e) { 16 | Node l = last; 17 | Node newNode = new Node(l, e, null); 18 | last = newNode; 19 | } 20 | 21 | public boolean remove(E e) { 22 | Node current = first; 23 | Node pre = first; 24 | if (pre == null) 25 | while (current.next != e) { 26 | if (current == null) 27 | return false; 28 | else { 29 | pre = current; 30 | current = current.next; 31 | } 32 | } 33 | size--; 34 | return true; 35 | } 36 | 37 | public E get(E e) { 38 | Node current = first; 39 | while (current.next != e) { 40 | current = current.next; 41 | } 42 | return current.item; 43 | } 44 | 45 | public void addFirst(E e) { 46 | Node f = first; 47 | Node node = new Node<>(null, e, first); 48 | first = node; 49 | if (f == null) 50 | last = node; 51 | else 52 | f.pre = node; 53 | } 54 | 55 | static class Node { 56 | E item; 57 | Node pre; 58 | Node next; 59 | 60 | public Node(Node pre, E item, Node next) { 61 | this.pre = pre; 62 | this.item = item; 63 | this.next = next; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Basic/BinarySearch.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Basic/BinarySearch.java 2 | package com.dataStructure.basic; 3 | ======= 4 | package com.datastructure.Basic; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Basic/BinarySearch.java 6 | 7 | import java.util.Arrays; 8 | 9 | /** 10 | * User: Shawn cao 11 | * Date: 14-5-6 12 | * Time: PM5:19 13 | */ 14 | public final class BinarySearch { 15 | 16 | public static int rank(int key,Integer[] arr){ 17 | int higherBound = arr.length-1; 18 | int lowerBound = 0; 19 | while(lowerBound <= higherBound){ 20 | int middle = lowerBound + (higherBound-lowerBound)/2 ; 21 | if(key arr[middle]){ 25 | lowerBound = middle +1; 26 | }else{ 27 | return middle; 28 | } 29 | } 30 | 31 | return - 1; 32 | } 33 | 34 | public static int recursiveRank(int key , Integer[] arr){ 35 | if(arr.length<=1) return -1; 36 | int higherBound = arr.length -1; 37 | int lowerBound = 0; 38 | int middle = lowerBound + (higherBound-lowerBound)/2; 39 | 40 | if(key arr[middle]) 43 | return recursiveRank(key,Arrays.copyOfRange(arr,middle,higherBound+1)); 44 | else 45 | return middle; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Sorting/Quick.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Sorting/Quick.java 2 | package com.dataStructure.sorting; 3 | ======= 4 | package com.datastructure.Sorting; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Sorting/Quick.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-8 10 | * Time: PM6:07 11 | */ 12 | public class Quick extends AbstractSorter { 13 | 14 | private final int THRESH_HOLD = 15; 15 | 16 | @Override 17 | public void sort(Comparable[] arr) { 18 | sort(arr, 0, arr.length-1); 19 | 20 | } 21 | 22 | private void sort(Comparable[] arr , int low, int high){ 23 | if(high <= low) return ; 24 | 25 | /** 26 | * Improvement: 27 | * 28 | */ 29 | // if(high <= low + THRESH_HOLD ){ 30 | // new Insertion().sort(arr); 31 | // return ; 32 | // } 33 | 34 | int j = partition(arr, low , high); 35 | sort(arr, low, j-1 ); 36 | sort(arr, j+1, high); 37 | } 38 | 39 | private int partition(Comparable[] arr, int low, int high){ 40 | int i = low, j = high+1; 41 | Comparable pivot = arr[low]; 42 | while(true){ 43 | while(less(arr[++i],pivot)){ 44 | if(i == high) break; 45 | } 46 | while(less(pivot,arr[--j])){ 47 | if(j == low) break; 48 | } 49 | if(i >= j) break; 50 | exchange(arr, i , j); 51 | } 52 | exchange(arr, low, j); 53 | return j; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/DynamicConnectivity/QuickUnionFind.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/DynamicConnectivity/QuickUnionFind.java 2 | package com.dataStructure.dynamicConnectivity; 3 | ======= 4 | package com.datastructure.DynamicConnectivity; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/DynamicConnectivity/QuickUnionFind.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-6-23 10 | * Time: PM5:02 11 | */ 12 | public class QuickUnionFind extends AbstractUnion{ 13 | 14 | public QuickUnionFind(int N){ 15 | super.init(N); 16 | } 17 | 18 | public boolean connected(int p, int q){ 19 | return ids[p] == ids[q]; 20 | } 21 | 22 | public void union(int p, int q){ 23 | int pVal = ids[p]; 24 | int qVal = ids[q]; 25 | for(int i=0; i>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Sorting/AbstractSorter.java 10 | 11 | /** 12 | * User: Shawn cao 13 | * Date: 14-5-8 14 | * Time: PM5:53 15 | */ 16 | public abstract class AbstractSorter { 17 | public int exchangeCount = 0; 18 | public static int compareCount = 0 ; 19 | 20 | public abstract void sort(Comparable[] arr); 21 | 22 | 23 | public static boolean less(Comparable a, Comparable b){ 24 | compareCount++; 25 | return a.compareTo(b) < 0; 26 | } 27 | 28 | public void exchange(Comparable[] arr, int i, int j){ 29 | Comparable t = arr[i]; 30 | arr[i] = arr[j] ; 31 | arr[j] = t; 32 | exchangeCount++; 33 | } 34 | 35 | public void show(Comparable[] arr){ 36 | for(int i = 0; i< arr.length; i++) StdOut.print(arr[i] + " "); 37 | StdOut.println(); 38 | } 39 | 40 | public static boolean isSorted(Comparable[] arr){ 41 | for(int i = 1; i < arr.length; i++){ 42 | if(less(arr[i], arr[i - 1])) return false; 43 | } 44 | return true; 45 | } 46 | 47 | 48 | public static boolean isSorted(Comparable[] a, int lo, int hi) { 49 | for (int i = lo + 1; i <= hi; i++) 50 | if (less(a[i], a[i-1])) return false; 51 | return true; 52 | } 53 | 54 | 55 | } 56 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | DataStructureDemos 4 | DataStructureDemos 5 | 0.0.1-SNAPSHOT 6 | 7 | 8 | com.google.guava 9 | guava 10 | 18.0 11 | 12 | 13 | 14 | junit 15 | junit 16 | 4.11 17 | test 18 | 19 | 20 | com.github.jbellis 21 | jamm 22 | runtime 23 | 0.3.1 24 | 25 | 26 | org.hamcrest 27 | hamcrest-library 28 | 1.3 29 | test 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.apache.maven.plugins 39 | maven-compiler-plugin 40 | 2.0.2 41 | 42 | 1.8 43 | 1.8 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/Sorter.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.sort; 2 | 3 | import java.util.*; 4 | 5 | public class Sorter { 6 | 7 | private static > void swap(List container, int i, int j) { 8 | T temp = container.get(i); 9 | container.set(i, container.get(j)); 10 | container.set(j, temp); 11 | } 12 | 13 | public static > void gnomeSort(List container) { 14 | for (int i = 1; i < container.size();) { 15 | if (container.get(i - 1).compareTo(container.get(i)) < 0) { 16 | ++i; 17 | } else { 18 | swap(container, i - 1, i); 19 | --i; 20 | if (i == 0) { 21 | i = 1; 22 | } 23 | } 24 | } 25 | } 26 | 27 | public static > void selectionSort(List container) { 28 | int in, out, min; 29 | int max = container.size(); 30 | for (out = 0; out < max - 1; out++) { 31 | min = out; 32 | for (in = out; in < max; in++) { 33 | if (container.get(in).compareTo(container.get(min)) > 0) { 34 | min = in; 35 | } 36 | swap(container, min, out); 37 | } 38 | } 39 | } 40 | 41 | public static > void insertionSort(List container) { 42 | int in, out; 43 | T temp; 44 | int size = container.size(); 45 | for (out = 1; out < size; out++) { 46 | temp = container.get(out); 47 | for (in = out; in > 0 && container.get(in - 1).compareTo(temp) > 0; --in) { 48 | swap(container, in, in - 1); 49 | } 50 | container.set(in, temp); 51 | } 52 | } 53 | 54 | public static > void bubbleSort(List container) { 55 | int size = container.size(); 56 | int out, in; 57 | for (out = size - 1; out > 0; out--) { 58 | for (in = 0; in < out; in++) { 59 | if (container.get(in).compareTo(container.get(in + 1)) > 0) { 60 | swap(container, in, in + 1); 61 | } 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Sorting/Merge.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/Sorting/Merge.java 2 | package com.dataStructure.sorting; 3 | ======= 4 | package com.datastructure.Sorting; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/Sorting/Merge.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-5-12 10 | * Time: AM10:44 11 | */ 12 | public class Merge extends AbstractSorter { 13 | 14 | 15 | @Override 16 | public void sort(Comparable[] arr) { 17 | Comparable[] auxArr; 18 | auxArr = new Comparable[arr.length]; 19 | sort(arr ,auxArr , 0 ,arr.length - 1); 20 | } 21 | 22 | 23 | private void sort(Comparable[] arr, Comparable[] auxArr, int low , int high){ 24 | if(high <= low) 25 | return ; 26 | int mid = low + (high - low) /2 ; 27 | 28 | sort(arr,auxArr, low , mid ); 29 | sort(arr , auxArr, mid+1, high); 30 | merge(arr,auxArr, low , mid , high ); 31 | } 32 | 33 | private void merge(Comparable[] arr,Comparable[] auxArr, int low , int mid , int high){ 34 | 35 | // assert isSorted(arr, low, mid); 36 | // assert isSorted(arr, mid+1, high); 37 | 38 | for(int k = low; k <= high; k++){ 39 | auxArr[k] = arr[k]; 40 | } 41 | int i = low, j = mid+1; 42 | for (int k = low; k <= high; k++) { 43 | //left exhausted 44 | if(i > mid) { 45 | arr[k] = auxArr[j++]; // this copying is unnecessary 46 | } 47 | //right exhausted 48 | else if(j > high) { 49 | arr[k] = auxArr[i++]; 50 | } 51 | else if(less(auxArr[j], auxArr[i])) { 52 | arr[k] = auxArr[j++]; 53 | } 54 | else { 55 | arr[k] = auxArr[i++]; 56 | } 57 | } 58 | 59 | } 60 | } 61 | 62 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/DynamicConnectivity/WeightedQuickUnion.java: -------------------------------------------------------------------------------- 1 | <<<<<<< HEAD:src/main/java/com/dataStructure/DynamicConnectivity/WeightedQuickUnion.java 2 | package com.dataStructure.dynamicConnectivity; 3 | ======= 4 | package com.datastructure.DynamicConnectivity; 5 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/main/java/com/datastructure/DynamicConnectivity/WeightedQuickUnion.java 6 | 7 | /** 8 | * User: Shawn cao 9 | * Date: 14-6-23 10 | * Time: PM6:29 11 | */ 12 | public class WeightedQuickUnion extends AbstractUnion { 13 | 14 | private int[] sizeWeight; 15 | private int count; 16 | 17 | public WeightedQuickUnion(int N){ 18 | init(N); 19 | sizeWeight = new int[N]; 20 | for(int i=0; i people = new ArrayList(); 13 | 14 | if (args.length != 2) 15 | { 16 | System.out.println("Usage: GnomeSortPeople "); 17 | System.exit(1); 18 | } 19 | String inputFileName = args[0]; 20 | String outputFileName = args[1]; 21 | 22 | loadData(inputFileName, people); 23 | 24 | Person.resetCounter(); 25 | long start = System.currentTimeMillis(); 26 | // Sorter.gnomeSort(people); 27 | //Sorter.selectionSort(people); 28 | // Sorter.insertionSort(people); 29 | Sorter.bubbleSort(people); 30 | long end = System.currentTimeMillis(); 31 | System.out.println(" the duration of sorting: " + (end - start)); 32 | System.out.println("There were " + Person.getCounter() + 33 | " comparisons to sort " + people.size() + 34 | " people with Gnome Sort"); 35 | 36 | writeData(outputFileName, people); 37 | } 38 | 39 | public static void loadData(String fileName, List people) 40 | throws IOException 41 | { 42 | File inStream = new File( fileName ); 43 | Scanner reader = new Scanner( inStream ); 44 | 45 | String name = ""; 46 | String address = ""; 47 | String suburb = ""; 48 | String state = ""; 49 | String temp = ""; 50 | String firstName = ""; 51 | int postCode = 0; 52 | 53 | boolean more = false; 54 | if( reader.hasNext() ) 55 | { 56 | more = true; 57 | } 58 | 59 | while( more ) 60 | { 61 | name = reader.nextLine(); 62 | String [ ] tokens = name.split(","); 63 | 64 | name = tokens[0]; 65 | firstName = tokens[1]; 66 | 67 | address = reader.nextLine(); 68 | 69 | temp = reader.nextLine(); 70 | 71 | String [ ] st = temp.split("\\t"); 72 | 73 | suburb = st[0]; 74 | 75 | state = st[1]; 76 | 77 | postCode = Integer.parseInt(st[2]); 78 | 79 | people.add(new Person(firstName, name, address, suburb, 80 | state, postCode)); 81 | 82 | try 83 | { 84 | reader.nextLine(); 85 | } 86 | catch( NoSuchElementException nsee ) 87 | { 88 | more = false; 89 | } 90 | } 91 | 92 | reader.close(); 93 | } 94 | 95 | public static void writeData(String fileName, List people) 96 | throws IOException 97 | { 98 | PrintWriter outFile = new PrintWriter(new File(fileName)); 99 | 100 | for (Person p: people) 101 | { 102 | outFile.println(p); 103 | } 104 | 105 | outFile.close(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/com/datastructure/KataTest.java: -------------------------------------------------------------------------------- 1 | package com.datastructure; 2 | 3 | import junit.framework.TestCase; 4 | import org.junit.Test; 5 | 6 | /** 7 | * User: Shawn cao 8 | * Date: 14-5-14 9 | * Time: AM11:20 10 | */ 11 | public class KataTest extends TestCase{ 12 | 13 | @Test 14 | public void testFizzBuzz(){ 15 | for(int i=1 ; i<=100; i++) { 16 | printFizzBuzz(i); 17 | } 18 | } 19 | 20 | 21 | private void printFizzBuzz(int i){ 22 | if(i %3 == 0){ 23 | if(i % 5 == 0){ 24 | System.out.println("FizzBuzz"); 25 | return ; 26 | } 27 | System.out.println("Fizz"); 28 | 29 | }else if (i%5 == 0){ 30 | System.out.println("Buzz"); 31 | }else{ 32 | System.out.println(i); 33 | } 34 | } 35 | 36 | @Test 37 | public void testReverseString(){ 38 | String str = "abcdefghijklmnopq"; 39 | //String result = reverseWithExtraBuffer(str); 40 | String result = reverseWithoutExtraBuffer(str); 41 | System.out.println(result); 42 | assertTrue(result.equals(new StringBuilder(str).reverse().toString())); 43 | } 44 | 45 | public String reverseWithExtraBuffer(String str){ 46 | StringBuffer sb = new StringBuffer(str.length()); 47 | for(int i = str.length()-1; i >= 0 ; i--){ 48 | sb.append(str.charAt(i)); 49 | } 50 | return sb.toString(); 51 | } 52 | 53 | public String reverseWithoutExtraBuffer(String str){ 54 | char[] chars = str.toCharArray(); 55 | int low = 0, high = str.length() -1 ; 56 | while(low <= high){ 57 | swap(chars,low++,high--); 58 | } 59 | return new String(chars); 60 | } 61 | 62 | private void swap(char[] chars,int i, int j){ 63 | char tmp = chars[j]; 64 | chars[j] = chars[i]; 65 | chars[i] = tmp; 66 | } 67 | 68 | @Test 69 | public void testPrintMultiplicationTable(){ 70 | int matrixNum = 12; 71 | for(int i = 1; i <= matrixNum; i++){ 72 | for(int j = 1; j<= matrixNum;j++) { 73 | System.out.print(String.format("%4d", j * i)); 74 | } 75 | System.out.println(); 76 | } 77 | } 78 | 79 | @Test 80 | public void testOddPrint(){ 81 | printOdd(); 82 | } 83 | 84 | private void printOdd(){ 85 | int top = 100; 86 | for(int i=0; i<= 100; i++){ 87 | if(i % 2 != 0){ 88 | System.out.println(i); 89 | } 90 | } 91 | } 92 | 93 | @Test 94 | public void testFindLargest(){ 95 | 96 | int[] ints = new int[]{2,3,4,5,6,6,7,187362,3,42342,123,34,56,7,8,9,9,7,4,23,4231,123,34,3,543,6,346}; 97 | //StdRandom.shuffle(ints); 98 | int largest = findLargest(ints); 99 | 100 | assertTrue(187362 == largest ); 101 | } 102 | 103 | private int findLargest(int[] arr){ 104 | int largest = Integer.MIN_VALUE; 105 | for(int i=0; i< arr.length - 1; i++){ 106 | if(arr[i] > largest){ 107 | largest = arr[i]; 108 | } 109 | } 110 | return largest; 111 | } 112 | 113 | @Test 114 | public void testFormatRGBToHex(){ 115 | System.out.println(formatRGB(255,0,128)); 116 | } 117 | 118 | private String formatRGB(int r, int g, int b) { 119 | return String.format ( "%02X%02X%02X", r, g, b ); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/test/java/com/datastructure/SortTest.java: -------------------------------------------------------------------------------- 1 | package com.datastructure; 2 | 3 | <<<<<<< HEAD:src/test/java/com/dataStructure/test/SortTest.java 4 | import com.dataStructure.helper.SortCompare; 5 | import com.dataStructure.helper.StdOut; 6 | import com.dataStructure.sorting.*; 7 | ======= 8 | import com.datastructure.Helper.SortCompare; 9 | import com.datastructure.Helper.StdOut; 10 | import com.datastructure.Sorting.*; 11 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/test/java/com/datastructure/SortTest.java 12 | import junit.framework.TestCase; 13 | import org.junit.Test; 14 | 15 | /** 16 | * User: Shawn cao 17 | * Date: 14-5-9 18 | * Time: PM1:42 19 | */ 20 | public class SortTest extends TestCase { 21 | 22 | 23 | 24 | @Test 25 | public void testSelectionSort(){ 26 | AbstractSorter sorter = new Selection(); 27 | //String[] arr = new String[]{"b","z","n","i","h","o","p","g","x","c","l","s","r","a"}; 28 | String[] arr = new String[]{"m","b","c","d","e","f","g","h","k","y"}; 29 | sorter.sort(arr); 30 | sorter.show(arr); 31 | System.out.println("Compare " + sorter.compareCount + " swap:" + sorter.exchangeCount); 32 | } 33 | 34 | @Test 35 | public void testInsertionSort(){ 36 | AbstractSorter sorter = new Insertion(); 37 | //String[] arr = new String[]{"b","z","n","i","h","o","p","g","x","c","l","s","r","a"}; 38 | String[] arr = new String[]{"m","b","c","d","e","f","g","h","k","y"}; 39 | sorter.sort(arr); 40 | sorter.show(arr); 41 | System.out.println("Compare " + sorter.compareCount + " swap:" + sorter.exchangeCount); 42 | 43 | } 44 | 45 | @Test 46 | public void testCompareSort(){ 47 | int N = 10000; 48 | int T=100; 49 | double t1 = SortCompare.timeRandomInput(new Selection(),N,T); 50 | double t2 = SortCompare.timeRandomInput(new Insertion(),N,T); 51 | double t3 = SortCompare.timeRandomInput(new Shell(),N,T); 52 | double t4 = SortCompare.timeRandomInput(new Merge(),N,T); 53 | double t5 = SortCompare.timeRandomInput(new Quick(),N,T); 54 | StdOut.printf("For %d random Doubles \n ", N); 55 | // StdOut.printf("selection is %.1f ; insertion is %.1f ; shell is %.1f ; ratio is %.001f ", t1, t2,t3, t1/t2); 56 | StdOut.printf("selection is %.1f ; insertion is %.1f ;shell is %.1f ; merge is %.1f ; quick is %.1f ", t1,t2,t3,t4,t5); 57 | } 58 | 59 | @Test 60 | public void testShellSort(){ 61 | // Integer[] arr = new Integer[]{10,9,8,7,6,5,4,3,2,1}; 62 | // AbstractSorter sorter = new Shell<>(); 63 | // sorter.sort(arr); 64 | // sorter.show(arr); 65 | 66 | AbstractSorter sorter = new Shell(); 67 | //String[] arr = new String[]{"b","z","n","i","h","o","p","g","x","c","l","s","r","a"}; 68 | String[] arr = new String[]{"m","b","c","d","e","f","g","h","k","y"}; 69 | sorter.sort(arr); 70 | sorter.show(arr); 71 | System.out.println("Compare " + sorter.compareCount + " swap:" + sorter.exchangeCount); 72 | } 73 | 74 | 75 | @Test 76 | public void testQuickSort(){ 77 | 78 | AbstractSorter sorter = new Quick(); 79 | //String[] arr = new String[]{"b","z","n","i","h","o","p","g","x","c","l","s","r","a"}; 80 | String[] arr = new String[]{"m","b","c","d","e","f","g","h","k","y"}; 81 | sorter.sort(arr); 82 | sorter.show(arr); 83 | sorter.isSorted(arr); 84 | System.out.println("Compare " + sorter.compareCount + " swap:" + sorter.exchangeCount + " is sort " + sorter.isSorted(arr)); 85 | } 86 | 87 | 88 | } 89 | 90 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/sort/Person.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Class Name: Person 3 | * 4 | * Author: Julie Main 5 | * Creation Date: Friday, March 11 2005, 15:07 6 | * Last Modified: Monday, March 10 2008, 13:45 7 | * 8 | * Revision History 9 | * 10 | * Author: Richard Tresider 11 | * Date: March 09 2008 12 | * Description: This class now implements the interface 13 | * Comparable from Java 1.5, replacing the 14 | * interface Comparable which is Java 1.4, which was 15 | * the standard when this class was originally written. 16 | * 17 | * The compareTo method changes to take a Person object 18 | * as the input parameter, rather than an Object object 19 | * which was the requirement in Java 1.4 There is no need 20 | * now, to cast from Object to Person. 21 | * 22 | * There should no longer be unchecked warnings when 23 | * this class is used with the rest of the lab. 24 | */ 25 | package com.datastructure.sort; 26 | 27 | public class Person implements Comparable 28 | { 29 | private String firstName; 30 | private String lastName; 31 | private String address; 32 | private String suburb; 33 | private String state; 34 | private int postCode; 35 | private static int noOfComparisons = 0; 36 | 37 | // Lab 01, Question 1 - b - i 38 | 39 | public Person(String firstName, String lastName, String address, 40 | String suburb, String state, int postCode) 41 | { 42 | this.firstName = firstName; 43 | this.lastName = lastName; 44 | this.address = address; 45 | this.suburb = suburb; 46 | this.state = state; 47 | this.postCode = postCode; 48 | } 49 | 50 | // Lab 01, Question 1 - b - ii 51 | 52 | public String toString() 53 | { 54 | return lastName + ", " + firstName + "\n" + 55 | address + "\n" + 56 | suburb + "\t" + state + "\t" + postCode + "\n"; 57 | } 58 | 59 | // Lab 01, Question 1 - b - iii 60 | 61 | public boolean equals(String first, String last, int post) 62 | { 63 | return this.firstName.equalsIgnoreCase(first) 64 | && this.lastName.equalsIgnoreCase(last) 65 | && this.postCode == post; 66 | } 67 | 68 | 69 | /* 70 | * Changed Mar 09 2008 to take a Person object, rather than an 71 | * Object object as we are now implementing Comparable, rather 72 | * than Comparable 73 | */ 74 | 75 | public int compareTo(Person p) 76 | { 77 | ++noOfComparisons; 78 | 79 | int lastNameDifference = 80 | this.lastName.compareToIgnoreCase(p.lastName); 81 | 82 | if (lastNameDifference != 0) 83 | { 84 | return lastNameDifference; 85 | } 86 | else 87 | { 88 | int firstNameDifference = 89 | this.firstName.compareToIgnoreCase(p.firstName); 90 | if (firstNameDifference != 0) 91 | { 92 | return firstNameDifference; 93 | } 94 | else 95 | { 96 | return this.postCode - p.postCode; 97 | } 98 | } 99 | } 100 | 101 | 102 | public String getLastName() 103 | { 104 | return this.lastName; 105 | } 106 | 107 | public String getFirstName() 108 | { 109 | return this.firstName; 110 | } 111 | 112 | public String getAddress() 113 | { 114 | return this.address; 115 | } 116 | 117 | public String getSuburb() 118 | { 119 | return this.suburb; 120 | } 121 | 122 | public String getState() 123 | { 124 | return this.state; 125 | } 126 | 127 | public int getPostCode() 128 | { 129 | return this.postCode; 130 | } 131 | 132 | 133 | public static int getCounter() 134 | { 135 | return noOfComparisons; 136 | } 137 | 138 | public static void resetCounter() 139 | { 140 | noOfComparisons = 0; 141 | } 142 | } 143 | 144 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/array/GenericOrderedArray.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.array; 2 | 3 | import java.lang.reflect.Array; 4 | 5 | public class GenericOrderedArray> { 6 | 7 | private T[] a; 8 | private int n; 9 | 10 | public GenericOrderedArray(Class clazz, int max) { 11 | a = (T[]) Array.newInstance(clazz, max); 12 | n = 0; 13 | } 14 | 15 | public int size() { 16 | return n; 17 | } 18 | 19 | public void insert(T value) { 20 | a[n] = value; 21 | n++; 22 | } 23 | 24 | public void orderInsert(T value) { 25 | int j; 26 | for (j = 0; j < n; j++) 27 | if (a[j] != null && a[j].compareTo(value) > 0) 28 | break; 29 | for (int k = n; k > j; k--) 30 | a[k] = a[k - 1]; 31 | a[j] = value; 32 | n++; 33 | } 34 | 35 | public boolean delete(T value) { 36 | boolean result = false; 37 | int hit = find(value); 38 | if (hit == -1) 39 | return result; 40 | else { 41 | for (int i = hit; i < n; i++) { 42 | a[i] = a[i + 1]; 43 | } 44 | n--; 45 | } 46 | return result; 47 | } 48 | 49 | public void display() { 50 | String st = "["; 51 | for (int i = 0; i < n; i++) { 52 | st += a[i] + ","; 53 | } 54 | 55 | System.out.println(st + "]"); 56 | } 57 | 58 | //rec binary search 59 | public int recBinarySearh(T t){ 60 | return recBinarySearch0(t, 0, n); 61 | } 62 | 63 | public int recBinarySearch0(T t, int lowerBound, int upperBound){ 64 | // System.out.println(lowerBound + " " + upperBound); 65 | int cur = (lowerBound + upperBound)/2; 66 | if(a[cur].equals(t)){ 67 | return cur; 68 | } 69 | else if(lowerBound > upperBound){ 70 | return -1; 71 | } 72 | else{ 73 | if(a[cur].compareTo(t) > 0){ 74 | return recBinarySearch0(t, 0,lowerBound); 75 | } 76 | else{ 77 | return recBinarySearch0(t, lowerBound+1, upperBound); 78 | } 79 | } 80 | } 81 | 82 | // binary search 83 | public int find(T value) { 84 | int lowerBound = 0; 85 | int upperBound = n - 1; 86 | int curIn; 87 | while (true) { 88 | curIn = (lowerBound + upperBound) / 2; 89 | if (a[curIn].equals(value)) 90 | return curIn; 91 | else if (lowerBound > upperBound) { 92 | return -1; 93 | } else { 94 | if (a[curIn].compareTo(value) < 0) 95 | lowerBound = curIn + 1; 96 | else { 97 | upperBound = curIn - 1; 98 | } 99 | } 100 | } 101 | } 102 | 103 | public void insertionSort() { 104 | int in, out; 105 | T temp; 106 | for (out = 1; out < n; out++) { 107 | temp = a[out]; 108 | for (in = out; in > 0 && a[in - 1].compareTo(temp) >= 0; --in) { 109 | a[in] = a[in-1]; 110 | } 111 | a[in] = temp; 112 | } 113 | } 114 | 115 | // selecton sort 116 | public void selectionSort() { 117 | int in, out, min; 118 | for (out = 0; out < n - 1; out++) { 119 | min = out; 120 | for (in = out; in < n; in++) { 121 | if (a[in].compareTo(a[min]) < 0) 122 | min = in; 123 | } 124 | swap(min, out); 125 | } 126 | } 127 | 128 | // bubble sort 129 | public void bubbleSort() { 130 | int in, out; 131 | for (out = n - 1; out > 1; out--) { 132 | for (in = 0; in < out; in++) { 133 | if (a[in].compareTo(a[in + 1]) > 0) { 134 | swap(in, in + 1); 135 | } 136 | } 137 | } 138 | } 139 | 140 | public void swap(int t1, int t2) { 141 | T temp = a[t1]; 142 | a[t1] = a[t2]; 143 | a[t2] = temp; 144 | } 145 | 146 | public T getMax() { 147 | if (n == 0) 148 | return null; 149 | else { 150 | return a[n - 1]; 151 | } 152 | } 153 | 154 | public boolean removeMax() { 155 | if (n == 0) 156 | return false; 157 | else { 158 | n--; 159 | return true; 160 | } 161 | } 162 | 163 | public static void main(String[] args) { 164 | 165 | int max = 100; 166 | GenericOrderedArray ints = new GenericOrderedArray<>(Integer.class, max); 167 | ints.insert(100); 168 | ints.insert(2); 169 | ints.insert(4); 170 | ints.insert(1); 171 | ints.insert(88); 172 | ints.insert(8); 173 | ints.insert(6); 174 | ints.insert(9); 175 | ints.insert(5); 176 | ints.display(); 177 | // ints.delete(2); 178 | // ints.bubbleSort(); 179 | ints.selectionSort(); 180 | //ints.insertionSort(); 181 | ints.display(); 182 | // System.out.println(ints.find(6)); 183 | System.out.println(ints.recBinarySearh(100)); 184 | /* 185 | * int max = 4; GenericOrderedArray persons = new 186 | * GenericOrderedArray<>(Person.class, max); persons.insert(new 187 | * Person("aa", "bb", 1)); persons.insert(new Person("ab", "bc", 1)); 188 | * persons.insert(new Person("aa", "bb", 2)); persons.display(); 189 | */ 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Trees/BinarySearchTree.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Trees; 2 | 3 | 4 | 5 | 6 | 7 | import java.util.LinkedList; 8 | import java.util.Queue; 9 | 10 | /** 11 | * User: Shawn cao 12 | * Date: 14-5-15 13 | * Time: PM3:44 14 | */ 15 | public class BinarySearchTree, Value> { 16 | 17 | private Node root; 18 | 19 | 20 | public boolean isEmpty(){ 21 | return size() == 0; 22 | } 23 | public int size(){ 24 | return size(root); 25 | } 26 | 27 | public int size(Node node){ 28 | if(node == null) return 0; 29 | else 30 | return node.N; 31 | } 32 | 33 | 34 | public void put(Key key, Value val){ 35 | root = put(root,key, val); 36 | } 37 | 38 | private Node put(Node node , Key key, Value val){ 39 | if(node == null){ 40 | return new Node(key,val,1); 41 | } 42 | int compare = key.compareTo(node.key); 43 | if(compare < 0){ 44 | node.left = put(node.left, key ,val); 45 | } 46 | else if(compare > 0){ 47 | node.right = put(node.right, key ,val); 48 | }else{ 49 | node.val = val; 50 | } 51 | node.N = size(node.left) + size(node.right) + 1; 52 | return node; 53 | 54 | } 55 | 56 | 57 | public Value get(Key key){ 58 | return get(root,key); 59 | } 60 | 61 | private Value get(Node node , Key key){ 62 | if(node == null){ 63 | return null; 64 | } 65 | int compare = key.compareTo(node.key); 66 | if(compare < 0){ 67 | return get(node.left, key); 68 | }else if(compare > 0){ 69 | return get(node.right, key); 70 | } 71 | else 72 | return node.val; 73 | } 74 | 75 | public Node min(){ 76 | return min(root); 77 | } 78 | 79 | private Node min(Node node){ 80 | if(node == null){ 81 | return null; 82 | } 83 | else if(node.left == null){ 84 | return node; 85 | } 86 | return min(root.left); 87 | } 88 | 89 | public Node max(){ 90 | return max(root); 91 | } 92 | 93 | private Node max(Node node){ 94 | if(node == null){ 95 | return null; 96 | } 97 | else if(node.right == null){ 98 | return node; 99 | } 100 | else { 101 | return max(node.right); 102 | } 103 | } 104 | 105 | public int rank(Key key){ 106 | return rank(key,root); 107 | } 108 | 109 | private int rank(Key key, Node node){ 110 | if(node == null) 111 | return 0; 112 | int compare = key.compareTo(node.key); 113 | if(compare < 0){ 114 | return rank(key,node.left); 115 | } 116 | else if(compare > 0){ 117 | return 1+ size(node.left) + rank(key, node.right); 118 | } 119 | else 120 | return size(node.left); 121 | } 122 | 123 | public void delete(Key key) { 124 | delete(root, key); 125 | } 126 | 127 | private Node delete(Node node , Key key){ 128 | if(node == null) 129 | return null; 130 | int compare = key.compareTo(node.key); 131 | if(compare > 0){ 132 | node.left = delete(node.left,key); 133 | }else if (compare > 0){ 134 | node.right = delete(node.right,key); 135 | } 136 | else{ 137 | if(node.right == null){ 138 | return node.left; 139 | } 140 | if(node.left == null){ 141 | return node.right; 142 | } 143 | Node t = node; 144 | node = min(t.right); 145 | node.right = deleteMin(t.right); 146 | node.left = t.left; 147 | } 148 | 149 | node.N = size(node.left) + size(node.right) + 1; 150 | return node ; 151 | } 152 | 153 | public void deleteMin(){ 154 | root = deleteMin(root); 155 | } 156 | 157 | private Node deleteMin(Node node){ 158 | if(node.left == null){ 159 | return node.right; 160 | } 161 | node.left = deleteMin(node.left); 162 | node.N = size(node.left) + size(node.right) + 1; 163 | return node ; 164 | } 165 | 166 | 167 | public Iterable keys(){ 168 | return keys(min().key,max().key); 169 | } 170 | 171 | private Iterable keys(Key low, Key high){ 172 | Queue queue = new LinkedList<>(); 173 | return queue; 174 | } 175 | 176 | private void keys(Node node , Queue keys, Key low, Key high){ 177 | if(node == null){ 178 | return ; 179 | } 180 | int compareLow = low.compareTo(node.key); 181 | int compareHigh = high.compareTo(node.key); 182 | if(compareLow < 0){ 183 | keys(node.left, keys, low , high); 184 | } 185 | if(compareHigh >= 0 && compareLow <=0 ){ 186 | keys.add(node.key); 187 | } 188 | if(compareHigh > 0){ 189 | keys(node.right,keys,low,high); 190 | } 191 | } 192 | 193 | 194 | private class Node{ 195 | private Key key; 196 | private Value val; 197 | private Node left,right; 198 | private int N; 199 | 200 | public Node(Key key, Value val, int N){ 201 | this.key = key; 202 | this.val = val; 203 | this.N = N; 204 | } 205 | 206 | 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /src/test/java/com/datastructure/BasicTest.java: -------------------------------------------------------------------------------- 1 | package com.datastructure; 2 | 3 | <<<<<<< HEAD:src/test/java/com/dataStructure/test/BasicTest.java 4 | import com.dataStructure.basic.BinarySearch; 5 | import com.dataStructure.basic.LinkedQueue; 6 | import com.dataStructure.basic.LinkedStack; 7 | import com.dataStructure.basic.Queue; 8 | 9 | import com.dataStructure.helper.StdRandom; 10 | import com.dataStructure.helper.Stopwatch; 11 | import com.dataStructure.helper.StreamUtil; 12 | ======= 13 | import com.datastructure.Basic.BinarySearch; 14 | import com.datastructure.Basic.LinkedQueue; 15 | import com.datastructure.Basic.LinkedStack; 16 | import com.datastructure.Basic.Queue; 17 | 18 | import com.datastructure.Helper.StdRandom; 19 | import com.datastructure.Helper.Stopwatch; 20 | import com.datastructure.Helper.StreamUtil; 21 | >>>>>>> c79664621f893d3f94e2feb4b1e893e8df413d7f:src/test/java/com/datastructure/BasicTest.java 22 | 23 | import com.google.common.collect.Lists; 24 | import com.google.common.collect.Sets; 25 | import junit.framework.TestCase; 26 | import org.github.jamm.MemoryMeter; 27 | import org.junit.Test; 28 | 29 | import java.io.InputStream; 30 | import java.util.Arrays; 31 | import java.util.Set; 32 | 33 | /** 34 | * User: Shawn cao 35 | * Date: 14-5-6 36 | * Time: PM5:19 37 | */ 38 | public class BasicTest extends TestCase { 39 | 40 | private static MemoryMeter memoryMeter = new MemoryMeter(); 41 | 42 | @Test 43 | public void testReadAllInts(){ 44 | InputStream in = getClass().getResourceAsStream("/tinyW.txt"); 45 | Integer[] numbers = StreamUtil.readAllInts(in); 46 | assertTrue(numbers.length > 0); 47 | } 48 | 49 | 50 | @Test 51 | public void testBinarySearch(){ 52 | Integer[] numbers = StreamUtil.readAllInts(getClass().getResourceAsStream("/tinyW.txt")); 53 | Arrays.sort(numbers); 54 | int first = BinarySearch.recursiveRank(48,numbers); 55 | int second = BinarySearch.recursiveRank(19,numbers); 56 | //int first = BinarySearch.rank(48,numbers); 57 | //int second = BinarySearch.rank(19,numbers); 58 | assertTrue(first > -1); 59 | assertTrue(second == -1); 60 | } 61 | 62 | @Test 63 | public void testChar(){ 64 | System.out.println('b') ; 65 | System.out.println('b' + 'c') ; 66 | System.out.println((char) ('a' + 4)) ; 67 | } 68 | 69 | @Test 70 | public void testLinkedStack(){ 71 | LinkedStack stack = new LinkedStack<>(); 72 | 73 | for(Integer e:new Integer[]{1,2,3,4,5,6,7,8,9,10}) stack.push(e); 74 | assertTrue(stack.size() == 10); 75 | assertTrue(stack.pop()==10); 76 | assertTrue(stack.pop()==9); 77 | } 78 | 79 | @Test 80 | public void testLinkedQueue(){ 81 | Queue queue = new LinkedQueue<>(); 82 | for(Integer e:new Integer[]{1,2,3,4,5,6,7,8,9,10}) queue.enqueue(e); 83 | assertTrue(queue.size() == 10); 84 | assertTrue(queue.dequeue() == 1); 85 | assertTrue(queue.dequeue() == 2); 86 | } 87 | 88 | @Test 89 | public void testUnionOperation(){ 90 | int N = 10000; 91 | Set set1 = Sets.newHashSetWithExpectedSize(N); 92 | for(int i=0; i set2 = Sets.newHashSetWithExpectedSize(N); 97 | for(int i=0; i results = Sets.union(set1, set2); 102 | System.out.printf("total time %s count: %d",stopwatch1.elapsedTime(),results.size() ); 103 | Stopwatch stopwatch2 = new Stopwatch(); 104 | Lists.newLinkedList(results); 105 | System.out.printf("total time %s",stopwatch2.elapsedTime() ); 106 | 107 | 108 | } 109 | @Test 110 | public void testThreeSum(){ 111 | Stopwatch stopwatch = new Stopwatch(); 112 | int count = threeSumFast(StreamUtil.readAllInts(getClass().getResourceAsStream("/2Kints.txt"))); 113 | 114 | System.out.printf("total time %s count: %d ",stopwatch.elapsedTime(), count); 115 | } 116 | 117 | @Test 118 | public void testLambda(){ 119 | Arrays.asList(1,2,3,4,5).forEach(e -> { 120 | System.out.println(e+1); 121 | }); 122 | } 123 | 124 | 125 | @Test 126 | public void testArraySize(){ 127 | int N = 1000000 ; 128 | //double[] arr = new double[N]; 129 | double[] arr = new double[N]; 130 | for(int i = 0; i < N ; i ++){ 131 | 132 | arr[i] = StdRandom.uniform(); 133 | 134 | } 135 | byte b = 'a'; 136 | char c = '\u4e00'; 137 | System.out.println("double arr occupied total of memory " + memoryMeter.measureDeep(arr)/1024/1024 +"mb"+ " | " + memoryMeter.measure(arr)/1024/1024+"mb"); 138 | System.out.println(memoryMeter.measureDeep(new Double(23))+ " | " + memoryMeter.measure(new Double(23))); 139 | System.out.println(memoryMeter.measureDeep(b)+ " | " + memoryMeter.measure(b)); 140 | System.out.println(memoryMeter.measureDeep(c)+ " | " + memoryMeter.measure(c)); 141 | } 142 | 143 | 144 | @Test 145 | public void testSwapWithoutThirdVariable(){ 146 | String a="a",b="b"; 147 | a = returnFirst(b,b = a); 148 | System.out.println(a + " | " + b); 149 | assertTrue(a.equals("b")); 150 | assertTrue(b.equals("a")); 151 | } 152 | 153 | private String returnFirst(String x, String y){ 154 | return x; 155 | } 156 | 157 | private int threeSum(Integer[] arr){ 158 | int len = arr.length; 159 | 160 | int count = 0; 161 | for(int i = 0; i < len; i++){ 162 | for(int j = i+1;j < len; j++){ 163 | for(int k = j+1;k < len; k++){ 164 | if(arr[i] + arr[j] + arr[k] == 0){ 165 | count++; 166 | } 167 | } 168 | } 169 | } 170 | return count; 171 | } 172 | 173 | private int threeSumFast(Integer[] arr){ 174 | Arrays.sort(arr); 175 | int len = arr.length; 176 | int count = 0; 177 | for(int i = 0; i < len; i++){ 178 | for(int j = i + 1; j < len;j++) { 179 | if (BinarySearch.rank(-arr[i], arr) > i) 180 | count++; 181 | } 182 | } 183 | return count ; 184 | } 185 | 186 | 187 | 188 | } 189 | 190 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdOut.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac StdOut.java 3 | * Execution: java StdOut 4 | * 5 | * Writes data of various types to standard output. 6 | * 7 | *************************************************************************/ 8 | package com.datastructure.Helper; 9 | import java.io.OutputStreamWriter; 10 | import java.io.PrintWriter; 11 | import java.io.UnsupportedEncodingException; 12 | import java.util.Locale; 13 | 14 | /** 15 | * Standard output. This class provides methods for writing strings 16 | * and numbers to standard output. 17 | *

18 | * For additional documentation, see Section 1.5 of 19 | * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. 20 | * 21 | * @author Robert Sedgewick 22 | * @author Kevin Wayne 23 | */ 24 | public final class StdOut { 25 | 26 | // force Unicode UTF-8 encoding; otherwise it's system dependent 27 | private static final String charsetName = "UTF-8"; 28 | 29 | // assume language = English, country = US for consistency with StdIn 30 | private static final Locale US_LOCALE = new Locale("en", "US"); 31 | 32 | // send output here 33 | private static PrintWriter out; 34 | 35 | // this is called before invoking any methods 36 | static { 37 | try { 38 | out = new PrintWriter(new OutputStreamWriter(System.out, charsetName), true); 39 | } 40 | catch (UnsupportedEncodingException e) { System.out.println(e); } 41 | } 42 | 43 | // don't instantiate 44 | private StdOut() { } 45 | 46 | // close the output stream (not required) 47 | /** 48 | * Close standard output. 49 | */ 50 | public static void close() { 51 | out.close(); 52 | } 53 | 54 | /** 55 | * Terminate the current line by printing the line separator string. 56 | */ 57 | public static void println() { 58 | out.println(); 59 | } 60 | 61 | /** 62 | * Print an object to standard output and then terminate the line. 63 | */ 64 | public static void println(Object x) { 65 | out.println(x); 66 | } 67 | 68 | /** 69 | * Print a boolean to standard output and then terminate the line. 70 | */ 71 | public static void println(boolean x) { 72 | out.println(x); 73 | } 74 | 75 | /** 76 | * Print a char to standard output and then terminate the line. 77 | */ 78 | public static void println(char x) { 79 | out.println(x); 80 | } 81 | 82 | /** 83 | * Print a double to standard output and then terminate the line. 84 | */ 85 | public static void println(double x) { 86 | out.println(x); 87 | } 88 | 89 | /** 90 | * Print a float to standard output and then terminate the line. 91 | */ 92 | public static void println(float x) { 93 | out.println(x); 94 | } 95 | 96 | /** 97 | * Print an int to standard output and then terminate the line. 98 | */ 99 | public static void println(int x) { 100 | out.println(x); 101 | } 102 | 103 | /** 104 | * Print a long to standard output and then terminate the line. 105 | */ 106 | public static void println(long x) { 107 | out.println(x); 108 | } 109 | 110 | /** 111 | * Print a short to standard output and then terminate the line. 112 | */ 113 | public static void println(short x) { 114 | out.println(x); 115 | } 116 | 117 | /** 118 | * Print a byte to standard output and then terminate the line. 119 | */ 120 | public static void println(byte x) { 121 | out.println(x); 122 | } 123 | 124 | /** 125 | * Flush standard output. 126 | */ 127 | public static void print() { 128 | out.flush(); 129 | } 130 | 131 | /** 132 | * Print an Object to standard output and flush standard output. 133 | */ 134 | public static void print(Object x) { 135 | out.print(x); 136 | out.flush(); 137 | } 138 | 139 | /** 140 | * Print a boolean to standard output and flush standard output. 141 | */ 142 | public static void print(boolean x) { 143 | out.print(x); 144 | out.flush(); 145 | } 146 | 147 | /** 148 | * Print a char to standard output and flush standard output. 149 | */ 150 | public static void print(char x) { 151 | out.print(x); 152 | out.flush(); 153 | } 154 | 155 | /** 156 | * Print a double to standard output and flush standard output. 157 | */ 158 | public static void print(double x) { 159 | out.print(x); 160 | out.flush(); 161 | } 162 | 163 | /** 164 | * Print a float to standard output and flush standard output. 165 | */ 166 | public static void print(float x) { 167 | out.print(x); 168 | out.flush(); 169 | } 170 | 171 | /** 172 | * Print an int to standard output and flush standard output. 173 | */ 174 | public static void print(int x) { 175 | out.print(x); 176 | out.flush(); 177 | } 178 | 179 | /** 180 | * Print a long to standard output and flush standard output. 181 | */ 182 | public static void print(long x) { 183 | out.print(x); 184 | out.flush(); 185 | } 186 | 187 | /** 188 | * Print a short to standard output and flush standard output. 189 | */ 190 | public static void print(short x) { 191 | out.print(x); 192 | out.flush(); 193 | } 194 | 195 | /** 196 | * Print a byte to standard output and flush standard output. 197 | */ 198 | public static void print(byte x) { 199 | out.print(x); 200 | out.flush(); 201 | } 202 | 203 | /** 204 | * Print a formatted string to standard output using the specified 205 | * format string and arguments, and flush standard output. 206 | */ 207 | public static void printf(String format, Object... args) { 208 | out.printf(US_LOCALE, format, args); 209 | out.flush(); 210 | } 211 | 212 | /** 213 | * Print a formatted string to standard output using the specified 214 | * locale, format string, and arguments, and flush standard output. 215 | */ 216 | public static void printf(Locale locale, String format, Object... args) { 217 | out.printf(locale, format, args); 218 | out.flush(); 219 | } 220 | 221 | // This method is just here to test the class 222 | public static void main(String[] args) { 223 | 224 | // write to stdout 225 | StdOut.println("Test"); 226 | StdOut.println(17); 227 | StdOut.println(true); 228 | StdOut.printf("%.6f\n", 1.0/7.0); 229 | } 230 | 231 | } 232 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/Out.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac Out.java 3 | * Execution: java Out 4 | * 5 | * Writes data of various types to: stdout, file, or socket. 6 | * 7 | *************************************************************************/ 8 | package com.datastructure.Helper; 9 | 10 | import java.io.FileOutputStream; 11 | import java.io.IOException; 12 | import java.io.OutputStream; 13 | import java.io.OutputStreamWriter; 14 | import java.io.PrintWriter; 15 | import java.net.Socket; 16 | import java.util.Locale; 17 | 18 | /** 19 | * This class provides methods for writing strings and numbers to 20 | * various output streams, including standard output, file, and sockets. 21 | *

22 | * For additional documentation, see 23 | * Section 3.1 of 24 | * Introduction to Programming in Java: An Interdisciplinary Approach 25 | * by Robert Sedgewick and Kevin Wayne. 26 | * 27 | * @author Robert Sedgewick 28 | * @author Kevin Wayne 29 | */ 30 | public class Out { 31 | 32 | // force Unicode UTF-8 encoding; otherwise it's system dependent 33 | private static String charsetName = "UTF-8"; 34 | 35 | // assume language = English, country = US for consistency with In 36 | private static final Locale US_LOCALE = new Locale("en", "US"); 37 | 38 | private PrintWriter out; 39 | 40 | /** 41 | * Create an Out object using an OutputStream. 42 | */ 43 | public Out(OutputStream os) { 44 | try { 45 | OutputStreamWriter osw = new OutputStreamWriter(os, charsetName); 46 | out = new PrintWriter(osw, true); 47 | } 48 | catch (IOException e) { e.printStackTrace(); } 49 | } 50 | 51 | /** 52 | * Create an Out object using standard output. 53 | */ 54 | public Out() { this(System.out); } 55 | 56 | /** 57 | * Create an Out object using a Socket. 58 | */ 59 | public Out(Socket socket) { 60 | try { 61 | OutputStream os = socket.getOutputStream(); 62 | OutputStreamWriter osw = new OutputStreamWriter(os, charsetName); 63 | out = new PrintWriter(osw, true); 64 | } 65 | catch (IOException e) { e.printStackTrace(); } 66 | } 67 | 68 | /** 69 | * Create an Out object using a file specified by the given name. 70 | */ 71 | public Out(String s) { 72 | try { 73 | OutputStream os = new FileOutputStream(s); 74 | OutputStreamWriter osw = new OutputStreamWriter(os, charsetName); 75 | out = new PrintWriter(osw, true); 76 | } 77 | catch (IOException e) { e.printStackTrace(); } 78 | } 79 | 80 | /** 81 | * Close the output stream. 82 | */ 83 | public void close() { out.close(); } 84 | 85 | 86 | 87 | /** 88 | * Terminate the line. 89 | */ 90 | public void println() { 91 | out.println(); 92 | } 93 | 94 | /** 95 | * Print an object and then terminate the line. 96 | */ 97 | public void println(Object x) { 98 | out.println(x); 99 | } 100 | 101 | /** 102 | * Print a boolean and then terminate the line. 103 | */ 104 | public void println(boolean x) { 105 | out.println(x); 106 | } 107 | 108 | /** 109 | * Print a char and then terminate the line. 110 | */ 111 | public void println(char x) { 112 | out.println(x); 113 | } 114 | 115 | /** 116 | * Print an double and then terminate the line. 117 | */ 118 | public void println(double x) { 119 | out.println(x); 120 | } 121 | 122 | /** 123 | * Print a float and then terminate the line. 124 | */ 125 | public void println(float x) { 126 | out.println(x); 127 | } 128 | 129 | /** 130 | * Print an int and then terminate the line. 131 | */ 132 | public void println(int x) { 133 | out.println(x); 134 | } 135 | 136 | /** 137 | * Print a long and then terminate the line. 138 | */ 139 | public void println(long x) { 140 | out.println(x); 141 | } 142 | 143 | /** 144 | * Print a byte and then terminate the line. 145 | */ 146 | public void println(byte x) { 147 | out.println(x); 148 | } 149 | 150 | 151 | 152 | /** 153 | * Flush the output stream. 154 | */ 155 | public void print() { 156 | out.flush(); 157 | } 158 | 159 | /** 160 | * Print an object and then flush the output stream. 161 | */ 162 | public void print(Object x) { 163 | out.print(x); 164 | out.flush(); 165 | } 166 | 167 | /** 168 | * Print an boolean and then flush the output stream. 169 | */ 170 | public void print(boolean x) { 171 | out.print(x); 172 | out.flush(); 173 | } 174 | 175 | /** 176 | * Print an char and then flush the output stream. 177 | */ 178 | public void print(char x) { 179 | out.print(x); 180 | out.flush(); 181 | } 182 | 183 | /** 184 | * Print an double and then flush the output stream. 185 | */ 186 | public void print(double x) { 187 | out.print(x); 188 | out.flush(); 189 | } 190 | 191 | /** 192 | * Print a float and then flush the output stream. 193 | */ 194 | public void print(float x) { 195 | out.print(x); 196 | out.flush(); 197 | } 198 | 199 | /** 200 | * Print an int and then flush the output stream. 201 | */ 202 | public void print(int x) { 203 | out.print(x); 204 | out.flush(); 205 | } 206 | 207 | /** 208 | * Print a long and then flush the output stream. 209 | */ 210 | public void print(long x) { 211 | out.print(x); 212 | out.flush(); 213 | } 214 | 215 | /** 216 | * Print a byte and then flush the output stream. 217 | */ 218 | public void print(byte x) { 219 | out.print(x); 220 | out.flush(); 221 | } 222 | 223 | /** 224 | * Print a formatted string using the specified format string and arguments, 225 | * and then flush the output stream. 226 | */ 227 | public void printf(String format, Object... args) { 228 | out.printf(US_LOCALE, format, args); 229 | out.flush(); 230 | } 231 | 232 | /** 233 | * Print a formatted string using the specified locale, format string and arguments, 234 | * and then flush the output stream. 235 | */ 236 | public void printf(Locale locale, String format, Object... args) { 237 | out.printf(locale, format, args); 238 | out.flush(); 239 | } 240 | 241 | 242 | /** 243 | * A test client. 244 | */ 245 | public static void main(String[] args) { 246 | Out out; 247 | 248 | // write to stdout 249 | out = new Out(); 250 | out.println("Test 1"); 251 | out.close(); 252 | 253 | // write to a file 254 | out = new Out("test.txt"); 255 | out.println("Test 2"); 256 | out.close(); 257 | } 258 | 259 | } 260 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdArrayIO.java: -------------------------------------------------------------------------------- 1 | package com.datastructure.Helper; 2 | /************************************************************************* 3 | * Compilation: javac StdArrayIO.java 4 | * Execution: java StdArrayIO < input.txt 5 | * 6 | * A library for reading in 1D and 2D arrays of integers, doubles, 7 | * and booleans from standard input and printing them out to 8 | * standard output. 9 | * 10 | * % more tinyDouble1D.txt 11 | * 4 12 | * .000 .246 .222 -.032 13 | * 14 | * % more tinyDouble2D.txt 15 | * 4 3 16 | * .000 .270 .000 17 | * .246 .224 -.036 18 | * .222 .176 .0893 19 | * -.032 .739 .270 20 | * 21 | * % more tinyBoolean2D.txt 22 | * 4 3 23 | * 1 1 0 24 | * 0 0 0 25 | * 0 1 1 26 | * 1 1 1 27 | * 28 | * % cat tinyDouble1D.txt tinyDouble2D.txt tinyBoolean2D.txt | java StdArrayIO 29 | * 4 30 | * 0.00000 0.24600 0.22200 -0.03200 31 | * 32 | * 4 3 33 | * 0.00000 0.27000 0.00000 34 | * 0.24600 0.22400 -0.03600 35 | * 0.22200 0.17600 0.08930 36 | * 0.03200 0.73900 0.27000 37 | * 38 | * 4 3 39 | * 1 1 0 40 | * 0 0 0 41 | * 0 1 1 42 | * 1 1 1 43 | * 44 | *************************************************************************/ 45 | 46 | 47 | /** 48 | * Standard array IO. This class provides methods for reading 49 | * in 1D and 2D arrays from standard input and printing out to 50 | * standard output. 51 | *

52 | * For additional documentation, see 53 | * Section 2.2 of 54 | * Introduction to Programming in Java: An Interdisciplinary Approach 55 | * by Robert Sedgewick and Kevin Wayne. 56 | * 57 | * @author Robert Sedgewick 58 | * @author Kevin Wayne 59 | */ 60 | public class StdArrayIO { 61 | 62 | // it doesn't make sense to instantiate this class 63 | private StdArrayIO() { } 64 | 65 | /** 66 | * Read in and return an array of doubles from standard input. 67 | */ 68 | public static double[] readDouble1D() { 69 | int N = StdIn.readInt(); 70 | double[] a = new double[N]; 71 | for (int i = 0; i < N; i++) { 72 | a[i] = StdIn.readDouble(); 73 | } 74 | return a; 75 | } 76 | 77 | /** 78 | * Print an array of doubles to standard output. 79 | */ 80 | public static void print(double[] a) { 81 | int N = a.length; 82 | StdOut.println(N); 83 | for (int i = 0; i < N; i++) { 84 | StdOut.printf("%9.5f ", a[i]); 85 | } 86 | StdOut.println(); 87 | } 88 | 89 | 90 | /** 91 | * Read in and return an M-by-N array of doubles from standard input. 92 | */ 93 | public static double[][] readDouble2D() { 94 | int M = StdIn.readInt(); 95 | int N = StdIn.readInt(); 96 | double[][] a = new double[M][N]; 97 | for (int i = 0; i < M; i++) { 98 | for (int j = 0; j < N; j++) { 99 | a[i][j] = StdIn.readDouble(); 100 | } 101 | } 102 | return a; 103 | } 104 | 105 | /** 106 | * Print the M-by-N array of doubles to standard output. 107 | */ 108 | public static void print(double[][] a) { 109 | int M = a.length; 110 | int N = a[0].length; 111 | StdOut.println(M + " " + N); 112 | for (int i = 0; i < M; i++) { 113 | for (int j = 0; j < N; j++) { 114 | StdOut.printf("%9.5f ", a[i][j]); 115 | } 116 | StdOut.println(); 117 | } 118 | } 119 | 120 | 121 | /** 122 | * Read in and return an array of ints from standard input. 123 | */ 124 | public static int[] readInt1D() { 125 | int N = StdIn.readInt(); 126 | int[] a = new int[N]; 127 | for (int i = 0; i < N; i++) { 128 | a[i] = StdIn.readInt(); 129 | } 130 | return a; 131 | } 132 | 133 | /** 134 | * Print an array of ints to standard output. 135 | */ 136 | public static void print(int[] a) { 137 | int N = a.length; 138 | StdOut.println(N); 139 | for (int i = 0; i < N; i++) { 140 | StdOut.printf("%9d ", a[i]); 141 | } 142 | StdOut.println(); 143 | } 144 | 145 | 146 | /** 147 | * Read in and return an M-by-N array of ints from standard input. 148 | */ 149 | public static int[][] readInt2D() { 150 | int M = StdIn.readInt(); 151 | int N = StdIn.readInt(); 152 | int[][] a = new int[M][N]; 153 | for (int i = 0; i < M; i++) { 154 | for (int j = 0; j < N; j++) { 155 | a[i][j] = StdIn.readInt(); 156 | } 157 | } 158 | return a; 159 | } 160 | 161 | /** 162 | * Print the M-by-N array of ints to standard output. 163 | */ 164 | public static void print(int[][] a) { 165 | int M = a.length; 166 | int N = a[0].length; 167 | StdOut.println(M + " " + N); 168 | for (int i = 0; i < M; i++) { 169 | for (int j = 0; j < N; j++) { 170 | StdOut.printf("%9d ", a[i][j]); 171 | } 172 | StdOut.println(); 173 | } 174 | } 175 | 176 | 177 | /** 178 | * Read in and return an array of booleans from standard input. 179 | */ 180 | public static boolean[] readBoolean1D() { 181 | int N = StdIn.readInt(); 182 | boolean[] a = new boolean[N]; 183 | for (int i = 0; i < N; i++) { 184 | a[i] = StdIn.readBoolean(); 185 | } 186 | return a; 187 | } 188 | 189 | /** 190 | * Print an array of booleans to standard output. 191 | */ 192 | public static void print(boolean[] a) { 193 | int N = a.length; 194 | StdOut.println(N); 195 | for (int i = 0; i < N; i++) { 196 | if (a[i]) StdOut.print("1 "); 197 | else StdOut.print("0 "); 198 | } 199 | StdOut.println(); 200 | } 201 | 202 | /** 203 | * Read in and return an M-by-N array of booleans from standard input. 204 | */ 205 | public static boolean[][] readBoolean2D() { 206 | int M = StdIn.readInt(); 207 | int N = StdIn.readInt(); 208 | boolean[][] a = new boolean[M][N]; 209 | for (int i = 0; i < M; i++) { 210 | for (int j = 0; j < N; j++) { 211 | a[i][j] = StdIn.readBoolean(); 212 | } 213 | } 214 | return a; 215 | } 216 | 217 | /** 218 | * Print the M-by-N array of booleans to standard output. 219 | */ 220 | public static void print(boolean[][] a) { 221 | int M = a.length; 222 | int N = a[0].length; 223 | StdOut.println(M + " " + N); 224 | for (int i = 0; i < M; i++) { 225 | for (int j = 0; j < N; j++) { 226 | if (a[i][j]) StdOut.print("1 "); 227 | else StdOut.print("0 "); 228 | } 229 | StdOut.println(); 230 | } 231 | } 232 | 233 | 234 | /** 235 | * Test client. 236 | */ 237 | public static void main(String[] args) { 238 | 239 | // read and print an array of doubles 240 | double[] a = StdArrayIO.readDouble1D(); 241 | StdArrayIO.print(a); 242 | StdOut.println(); 243 | 244 | // read and print a matrix of doubles 245 | double[][] b = StdArrayIO.readDouble2D(); 246 | StdArrayIO.print(b); 247 | StdOut.println(); 248 | 249 | // read and print a matrix of doubles 250 | boolean[][] d = StdArrayIO.readBoolean2D(); 251 | StdArrayIO.print(d); 252 | StdOut.println(); 253 | } 254 | 255 | } 256 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/BinaryStdOut.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryStdOut.java 3 | * Execution: java BinaryStdOut 4 | * 5 | * Write binary data to standard output, either one 1-bit boolean, 6 | * one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float, 7 | * or one 64-bit long at a time. 8 | * 9 | * The bytes written are not aligned. 10 | * 11 | *************************************************************************/ 12 | package com.datastructure.Helper; 13 | import java.io.BufferedOutputStream; 14 | import java.io.IOException; 15 | 16 | /** 17 | * Binary standard output. This class provides methods for converting 18 | * primtive type variables (boolean, byte, char, 19 | * int, long, float, and double) 20 | * to sequences of bits and writing them to standard output. 21 | * Uses big-endian (most-significant byte first). 22 | *

23 | * The client must flush() the output stream when finished writing bits. 24 | *

25 | * The client should not intermixing calls to BinaryStdOut with calls 26 | * to StdOut or System.out; otherwise unexpected behavior 27 | * will result. 28 | * 29 | * @author Robert Sedgewick 30 | * @author Kevin Wayne 31 | */ 32 | public final class BinaryStdOut { 33 | private static BufferedOutputStream out = new BufferedOutputStream(System.out); 34 | 35 | private static int buffer; // 8-bit buffer of bits to write out 36 | private static int N; // number of bits remaining in buffer 37 | 38 | // don't instantiate 39 | private BinaryStdOut() { } 40 | 41 | /** 42 | * Write the specified bit to standard output. 43 | */ 44 | private static void writeBit(boolean bit) { 45 | // add bit to buffer 46 | buffer <<= 1; 47 | if (bit) buffer |= 1; 48 | 49 | // if buffer is full (8 bits), write out as a single byte 50 | N++; 51 | if (N == 8) clearBuffer(); 52 | } 53 | 54 | /** 55 | * Write the 8-bit byte to standard output. 56 | */ 57 | private static void writeByte(int x) { 58 | assert x >= 0 && x < 256; 59 | 60 | // optimized if byte-aligned 61 | if (N == 0) { 62 | try { out.write(x); } 63 | catch (IOException e) { e.printStackTrace(); } 64 | return; 65 | } 66 | 67 | // otherwise write one bit at a time 68 | for (int i = 0; i < 8; i++) { 69 | boolean bit = ((x >>> (8 - i - 1)) & 1) == 1; 70 | writeBit(bit); 71 | } 72 | } 73 | 74 | // write out any remaining bits in buffer to standard output, padding with 0s 75 | private static void clearBuffer() { 76 | if (N == 0) return; 77 | if (N > 0) buffer <<= (8 - N); 78 | try { out.write(buffer); } 79 | catch (IOException e) { e.printStackTrace(); } 80 | N = 0; 81 | buffer = 0; 82 | } 83 | 84 | /** 85 | * Flush standard output, padding 0s if number of bits written so far 86 | * is not a multiple of 8. 87 | */ 88 | public static void flush() { 89 | clearBuffer(); 90 | try { out.flush(); } 91 | catch (IOException e) { e.printStackTrace(); } 92 | } 93 | 94 | /** 95 | * Flush and close standard output. Once standard output is closed, you can no 96 | * longer write bits to it. 97 | */ 98 | public static void close() { 99 | flush(); 100 | try { out.close(); } 101 | catch (IOException e) { e.printStackTrace(); } 102 | } 103 | 104 | 105 | /** 106 | * Write the specified bit to standard output. 107 | * @param x the boolean to write. 108 | */ 109 | public static void write(boolean x) { 110 | writeBit(x); 111 | } 112 | 113 | /** 114 | * Write the 8-bit byte to standard output. 115 | * @param x the byte to write. 116 | */ 117 | public static void write(byte x) { 118 | writeByte(x & 0xff); 119 | } 120 | 121 | /** 122 | * Write the 32-bit int to standard output. 123 | * @param x the int to write. 124 | */ 125 | public static void write(int x) { 126 | writeByte((x >>> 24) & 0xff); 127 | writeByte((x >>> 16) & 0xff); 128 | writeByte((x >>> 8) & 0xff); 129 | writeByte((x >>> 0) & 0xff); 130 | } 131 | 132 | /** 133 | * Write the r-bit int to standard output. 134 | * @param x the int to write. 135 | * @param r the number of relevant bits in the char. 136 | * @throws RuntimeException if r is not between 1 and 32. 137 | * @throws RuntimeException if x is not between 0 and 2r - 1. 138 | */ 139 | public static void write(int x, int r) { 140 | if (r == 32) { write(x); return; } 141 | if (r < 1 || r > 32) throw new RuntimeException("Illegal value for r = " + r); 142 | if (x < 0 || x >= (1 << r)) throw new RuntimeException("Illegal " + r + "-bit char = " + x); 143 | for (int i = 0; i < r; i++) { 144 | boolean bit = ((x >>> (r - i - 1)) & 1) == 1; 145 | writeBit(bit); 146 | } 147 | } 148 | 149 | 150 | 151 | 152 | 153 | /** 154 | * Write the 64-bit double to standard output. 155 | * @param x the double to write. 156 | */ 157 | public static void write(double x) { 158 | write(Double.doubleToRawLongBits(x)); 159 | } 160 | 161 | /** 162 | * Write the 64-bit long to standard output. 163 | * @param x the long to write. 164 | */ 165 | public static void write(long x) { 166 | writeByte((int) ((x >>> 56) & 0xff)); 167 | writeByte((int) ((x >>> 48) & 0xff)); 168 | writeByte((int) ((x >>> 40) & 0xff)); 169 | writeByte((int) ((x >>> 32) & 0xff)); 170 | writeByte((int) ((x >>> 24) & 0xff)); 171 | writeByte((int) ((x >>> 16) & 0xff)); 172 | writeByte((int) ((x >>> 8) & 0xff)); 173 | writeByte((int) ((x >>> 0) & 0xff)); 174 | } 175 | 176 | /** 177 | * Write the 32-bit float to standard output. 178 | * @param x the float to write. 179 | */ 180 | public static void write(float x) { 181 | write(Float.floatToRawIntBits(x)); 182 | } 183 | 184 | /** 185 | * Write the 16-bit int to standard output. 186 | * @param x the short to write. 187 | */ 188 | public static void write(short x) { 189 | writeByte((x >>> 8) & 0xff); 190 | writeByte((x >>> 0) & 0xff); 191 | } 192 | 193 | /** 194 | * Write the 8-bit char to standard output. 195 | * @param x the char to write. 196 | * @throws RuntimeException if x is not betwen 0 and 255. 197 | */ 198 | public static void write(char x) { 199 | if (x < 0 || x >= 256) throw new RuntimeException("Illegal 8-bit char = " + x); 200 | writeByte(x); 201 | } 202 | 203 | /** 204 | * Write the r-bit char to standard output. 205 | * @param x the char to write. 206 | * @param r the number of relevant bits in the char. 207 | * @throws RuntimeException if r is not between 1 and 16. 208 | * @throws RuntimeException if x is not between 0 and 2r - 1. 209 | */ 210 | public static void write(char x, int r) { 211 | if (r == 8) { write(x); return; } 212 | if (r < 1 || r > 16) throw new RuntimeException("Illegal value for r = " + r); 213 | if (x < 0 || x >= (1 << r)) throw new RuntimeException("Illegal " + r + "-bit char = " + x); 214 | for (int i = 0; i < r; i++) { 215 | boolean bit = ((x >>> (r - i - 1)) & 1) == 1; 216 | writeBit(bit); 217 | } 218 | } 219 | 220 | /** 221 | * Write the string of 8-bit characters to standard output. 222 | * @param s the String to write. 223 | * @throws RuntimeException if any character in the string is not 224 | * between 0 and 255. 225 | */ 226 | public static void write(String s) { 227 | for (int i = 0; i < s.length(); i++) 228 | write(s.charAt(i)); 229 | } 230 | 231 | /** 232 | * Write the String of r-bit characters to standard output. 233 | * @param s the String to write. 234 | * @param r the number of relevants bits in each character. 235 | * @throws RuntimeException if r is not between 1 and 16. 236 | * @throws RuntimeException if any character in the string is not 237 | * between 0 and 2r - 1. 238 | */ 239 | public static void write(String s, int r) { 240 | for (int i = 0; i < s.length(); i++) 241 | write(s.charAt(i), r); 242 | } 243 | 244 | /** 245 | * Test client. 246 | */ 247 | public static void main(String[] args) { 248 | int T = Integer.parseInt(args[0]); 249 | // write to standard output 250 | for (int i = 0; i < T; i++) { 251 | BinaryStdOut.write(i); 252 | } 253 | BinaryStdOut.flush(); 254 | } 255 | 256 | } 257 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/BinaryStdIn.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryStdIn.java 3 | * Execution: java BinaryStdIn < input > output 4 | * 5 | * Supports reading binary data from standard input. 6 | * 7 | * % java BinaryStdIn < input.jpg > output.jpg 8 | * % diff input.jpg output.jpg 9 | * 10 | *************************************************************************/ 11 | package com.datastructure.Helper; 12 | import java.io.BufferedInputStream; 13 | import java.io.IOException; 14 | 15 | /** 16 | * Binary standard input. This class provides methods for reading 17 | * in bits from standard input, either one bit at a time (as a boolean), 18 | * 8 bits at a time (as a byte or char), 19 | * 16 bits at a time (as a short), 32 bits at a time 20 | * (as an int or float), or 64 bits at a time (as a 21 | * double or long). 22 | *

23 | * All primitive types are assumed to be represented using their 24 | * standard Java representations, in big-endian (most significant 25 | * byte first) order. 26 | *

27 | * The client should not intermix calls to BinaryStdIn with calls 28 | * to StdIn or System.in; 29 | * otherwise unexpected behavior will result. 30 | * 31 | * @author Robert Sedgewick 32 | * @author Kevin Wayne 33 | */ 34 | public final class BinaryStdIn { 35 | private static BufferedInputStream in = new BufferedInputStream(System.in); 36 | private static final int EOF = -1; // end of file 37 | 38 | private static int buffer; // one character buffer 39 | private static int N; // number of bits left in buffer 40 | 41 | // static initializer 42 | static { fillBuffer(); } 43 | 44 | // don't instantiate 45 | private BinaryStdIn() { } 46 | 47 | private static void fillBuffer() { 48 | try { buffer = in.read(); N = 8; } 49 | catch (IOException e) { System.out.println("EOF"); buffer = EOF; N = -1; } 50 | } 51 | 52 | /** 53 | * Close this input stream and release any associated system resources. 54 | */ 55 | public static void close() { 56 | try { 57 | in.close(); 58 | } 59 | catch (IOException e) { 60 | e.printStackTrace(); 61 | throw new RuntimeException("Could not close BinaryStdIn"); 62 | } 63 | } 64 | 65 | /** 66 | * Returns true if standard input is empty. 67 | * @return true if and only if standard input is empty 68 | */ 69 | public static boolean isEmpty() { 70 | return buffer == EOF; 71 | } 72 | 73 | /** 74 | * Read the next bit of data from standard input and return as a boolean. 75 | * @return the next bit of data from standard input as a boolean 76 | * @throws RuntimeException if standard input is empty 77 | */ 78 | public static boolean readBoolean() { 79 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 80 | N--; 81 | boolean bit = ((buffer >> N) & 1) == 1; 82 | if (N == 0) fillBuffer(); 83 | return bit; 84 | } 85 | 86 | /** 87 | * Read the next 8 bits from standard input and return as an 8-bit char. 88 | * Note that char is a 16-bit type; 89 | * to read the next 16 bits as a char, use readChar(16) 90 | * @return the next 8 bits of data from standard input as a char 91 | * @throws RuntimeException if there are fewer than 8 bits available on standard input 92 | */ 93 | public static char readChar() { 94 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 95 | 96 | // special case when aligned byte 97 | if (N == 8) { 98 | int x = buffer; 99 | fillBuffer(); 100 | return (char) (x & 0xff); 101 | } 102 | 103 | // combine last N bits of current buffer with first 8-N bits of new buffer 104 | int x = buffer; 105 | x <<= (8-N); 106 | int oldN = N; 107 | fillBuffer(); 108 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 109 | N = oldN; 110 | x |= (buffer >>> N); 111 | return (char) (x & 0xff); 112 | // the above code doesn't quite work for the last character if N = 8 113 | // because buffer will be -1 114 | } 115 | 116 | /** 117 | * Read the next r bits from standard input and return as an r-bit character. 118 | * @param r number of bits to read. 119 | * @return the next r bits of data from standard input as a char 120 | * @throws RuntimeException if there are fewer than r bits available on standard input 121 | * @throws RuntimeException unless 1 ≤ r ≤ 16 122 | */ 123 | public static char readChar(int r) { 124 | if (r < 1 || r > 16) throw new RuntimeException("Illegal value of r = " + r); 125 | 126 | // optimize r = 8 case 127 | if (r == 8) return readChar(); 128 | 129 | char x = 0; 130 | for (int i = 0; i < r; i++) { 131 | x <<= 1; 132 | boolean bit = readBoolean(); 133 | if (bit) x |= 1; 134 | } 135 | return x; 136 | } 137 | 138 | /** 139 | * Read the remaining bytes of data from standard input and return as a string. 140 | * @return the remaining bytes of data from standard input as a String 141 | * @throws RuntimeException if standard input is empty or if the number of bits 142 | * available on standard input is not a multiple of 8 (byte-aligned) 143 | */ 144 | public static String readString() { 145 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 146 | 147 | StringBuilder sb = new StringBuilder(); 148 | while (!isEmpty()) { 149 | char c = readChar(); 150 | sb.append(c); 151 | } 152 | return sb.toString(); 153 | } 154 | 155 | 156 | /** 157 | * Read the next 16 bits from standard input and return as a 16-bit short. 158 | * @return the next 16 bits of data from standard input as a short 159 | * @throws RuntimeException if there are fewer than 16 bits available on standard input 160 | */ 161 | public static short readShort() { 162 | short x = 0; 163 | for (int i = 0; i < 2; i++) { 164 | char c = readChar(); 165 | x <<= 8; 166 | x |= c; 167 | } 168 | return x; 169 | } 170 | 171 | /** 172 | * Read the next 32 bits from standard input and return as a 32-bit int. 173 | * @return the next 32 bits of data from standard input as a int 174 | * @throws RuntimeException if there are fewer than 32 bits available on standard input 175 | */ 176 | public static int readInt() { 177 | int x = 0; 178 | for (int i = 0; i < 4; i++) { 179 | char c = readChar(); 180 | x <<= 8; 181 | x |= c; 182 | } 183 | return x; 184 | } 185 | 186 | /** 187 | * Read the next r bits from standard input and return as an r-bit int. 188 | * @param r number of bits to read. 189 | * @return the next r bits of data from standard input as a int 190 | * @throws RuntimeException if there are fewer than r bits available on standard input 191 | * @throws RuntimeException unless 1 ≤ r ≤ 32 192 | */ 193 | public static int readInt(int r) { 194 | if (r < 1 || r > 32) throw new RuntimeException("Illegal value of r = " + r); 195 | 196 | // optimize r = 32 case 197 | if (r == 32) return readInt(); 198 | 199 | int x = 0; 200 | for (int i = 0; i < r; i++) { 201 | x <<= 1; 202 | boolean bit = readBoolean(); 203 | if (bit) x |= 1; 204 | } 205 | return x; 206 | } 207 | 208 | /** 209 | * Read the next 64 bits from standard input and return as a 64-bit long. 210 | * @return the next 64 bits of data from standard input as a long 211 | * @throws RuntimeException if there are fewer than 64 bits available on standard input 212 | */ 213 | public static long readLong() { 214 | long x = 0; 215 | for (int i = 0; i < 8; i++) { 216 | char c = readChar(); 217 | x <<= 8; 218 | x |= c; 219 | } 220 | return x; 221 | } 222 | 223 | 224 | /** 225 | * Read the next 64 bits from standard input and return as a 64-bit double. 226 | * @return the next 64 bits of data from standard input as a double 227 | * @throws RuntimeException if there are fewer than 64 bits available on standard input 228 | */ 229 | public static double readDouble() { 230 | return Double.longBitsToDouble(readLong()); 231 | } 232 | 233 | /** 234 | * Read the next 32 bits from standard input and return as a 32-bit float. 235 | * @return the next 32 bits of data from standard input as a float 236 | * @throws RuntimeException if there are fewer than 32 bits available on standard input 237 | */ 238 | public static float readFloat() { 239 | return Float.intBitsToFloat(readInt()); 240 | } 241 | 242 | 243 | /** 244 | * Read the next 8 bits from standard input and return as an 8-bit byte. 245 | * @return the next 8 bits of data from standard input as a byte 246 | * @throws RuntimeException if there are fewer than 8 bits available on standard input 247 | */ 248 | public static byte readByte() { 249 | char c = readChar(); 250 | byte x = (byte) (c & 0xff); 251 | return x; 252 | } 253 | 254 | /** 255 | * Test client. Reads in a binary input file from standard input and writes 256 | * it to standard output. 257 | */ 258 | public static void main(String[] args) { 259 | 260 | // read one 8-bit char at a time 261 | while (!BinaryStdIn.isEmpty()) { 262 | char c = BinaryStdIn.readChar(); 263 | BinaryStdOut.write(c); 264 | } 265 | BinaryStdOut.flush(); 266 | } 267 | } 268 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdIn.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac StdIn.java 3 | * Execution: java StdIn (interactive test of basic functionality) 4 | * 5 | * Reads in data of various types from standard input. 6 | * 7 | *************************************************************************/ 8 | package com.datastructure.Helper; 9 | import java.util.Scanner; 10 | import java.util.regex.Pattern; 11 | 12 | /** 13 | * Standard input. This class provides methods for reading strings 14 | * and numbers from standard input. See 15 | * Section 1.5 of 16 | * Introduction to Programming in Java: An Interdisciplinary Approach 17 | * by Robert Sedgewick and Kevin Wayne. 18 | *

19 | * See the technical information in the documentation of the {@link In} 20 | * class, which applies to this class as well. 21 | * 22 | * @author Robert Sedgewick 23 | * @author Kevin Wayne 24 | */ 25 | public final class StdIn { 26 | 27 | // it doesn't make sense to instantiate this class 28 | private StdIn() {} 29 | 30 | private static Scanner scanner; 31 | 32 | /*** begin: section (1 of 2) of code duplicated from In to StdIn */ 33 | 34 | // assume Unicode UTF-8 encoding 35 | private static final String charsetName = "UTF-8"; 36 | 37 | // assume language = English, country = US for consistency with System.out. 38 | private static final java.util.Locale usLocale = 39 | new java.util.Locale("en", "US"); 40 | 41 | // the default token separator; we maintain the invariant that this value 42 | // is held by the scanner's delimiter between calls 43 | private static final Pattern WHITESPACE_PATTERN 44 | = Pattern.compile("\\p{javaWhitespace}+"); 45 | 46 | // makes whitespace characters significant 47 | private static final Pattern EMPTY_PATTERN 48 | = Pattern.compile(""); 49 | 50 | // used to read the entire input. source: 51 | // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html 52 | private static final Pattern EVERYTHING_PATTERN 53 | = Pattern.compile("\\A"); 54 | 55 | /*** end: section (1 of 2) of code duplicated from In to StdIn */ 56 | 57 | /*** begin: section (2 of 2) of code duplicated from In to StdIn, 58 | * with all methods changed from "public" to "public static" ***/ 59 | 60 | /** 61 | * Is the input empty (except possibly for whitespace)? Use this 62 | * to know whether the next call to {@link #readString()}, 63 | * {@link #readDouble()}, etc will succeed. 64 | */ 65 | public static boolean isEmpty() { 66 | return !scanner.hasNext(); 67 | } 68 | 69 | /** 70 | * Does the input have a next line? Use this to know whether the 71 | * next call to {@link #readLine()} will succeed.

Functionally 72 | * equivalent to {@link #hasNextChar()}. 73 | */ 74 | public static boolean hasNextLine() { 75 | return scanner.hasNextLine(); 76 | } 77 | 78 | /** 79 | * Is the input empty (including whitespace)? Use this to know 80 | * whether the next call to {@link #readChar()} will succeed.

Functionally 81 | * equivalent to {@link #hasNextLine()}. 82 | */ 83 | public static boolean hasNextChar() { 84 | scanner.useDelimiter(EMPTY_PATTERN); 85 | boolean result = scanner.hasNext(); 86 | scanner.useDelimiter(WHITESPACE_PATTERN); 87 | return result; 88 | } 89 | 90 | 91 | /** 92 | * Read and return the next line. 93 | */ 94 | public static String readLine() { 95 | String line; 96 | try { line = scanner.nextLine(); } 97 | catch (Exception e) { line = null; } 98 | return line; 99 | } 100 | 101 | /** 102 | * Read and return the next character. 103 | */ 104 | public static char readChar() { 105 | scanner.useDelimiter(EMPTY_PATTERN); 106 | String ch = scanner.next(); 107 | assert (ch.length() == 1) : "Internal (Std)In.readChar() error!" 108 | + " Please contact the authors."; 109 | scanner.useDelimiter(WHITESPACE_PATTERN); 110 | return ch.charAt(0); 111 | } 112 | 113 | 114 | /** 115 | * Read and return the remainder of the input as a string. 116 | */ 117 | public static String readAll() { 118 | if (!scanner.hasNextLine()) 119 | return ""; 120 | 121 | String result = scanner.useDelimiter(EVERYTHING_PATTERN).next(); 122 | // not that important to reset delimeter, since now scanner is empty 123 | scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway 124 | return result; 125 | } 126 | 127 | 128 | /** 129 | * Read and return the next string. 130 | */ 131 | public static String readString() { 132 | return scanner.next(); 133 | } 134 | 135 | /** 136 | * Read and return the next int. 137 | */ 138 | public static int readInt() { 139 | return scanner.nextInt(); 140 | } 141 | 142 | /** 143 | * Read and return the next double. 144 | */ 145 | public static double readDouble() { 146 | return scanner.nextDouble(); 147 | } 148 | 149 | /** 150 | * Read and return the next float. 151 | */ 152 | public static float readFloat() { 153 | return scanner.nextFloat(); 154 | } 155 | 156 | /** 157 | * Read and return the next long. 158 | */ 159 | public static long readLong() { 160 | return scanner.nextLong(); 161 | } 162 | 163 | /** 164 | * Read and return the next short. 165 | */ 166 | public static short readShort() { 167 | return scanner.nextShort(); 168 | } 169 | 170 | /** 171 | * Read and return the next byte. 172 | */ 173 | public static byte readByte() { 174 | return scanner.nextByte(); 175 | } 176 | 177 | /** 178 | * Read and return the next boolean, allowing case-insensitive 179 | * "true" or "1" for true, and "false" or "0" for false. 180 | */ 181 | public static boolean readBoolean() { 182 | String s = readString(); 183 | if (s.equalsIgnoreCase("true")) return true; 184 | if (s.equalsIgnoreCase("false")) return false; 185 | if (s.equals("1")) return true; 186 | if (s.equals("0")) return false; 187 | throw new java.util.InputMismatchException(); 188 | } 189 | 190 | /** 191 | * Read all strings until the end of input is reached, and return them. 192 | */ 193 | public static String[] readAllStrings() { 194 | // we could use readAll.trim().split(), but that's not consistent 195 | // since trim() uses characters 0x00..0x20 as whitespace 196 | String[] tokens = WHITESPACE_PATTERN.split(readAll()); 197 | if (tokens.length == 0 || tokens[0].length() > 0) 198 | return tokens; 199 | String[] decapitokens = new String[tokens.length-1]; 200 | for (int i=0; i < tokens.length-1; i++) 201 | decapitokens[i] = tokens[i+1]; 202 | return decapitokens; 203 | } 204 | 205 | /** 206 | * Read all ints until the end of input is reached, and return them. 207 | */ 208 | public static int[] readAllInts() { 209 | String[] fields = readAllStrings(); 210 | int[] vals = new int[fields.length]; 211 | for (int i = 0; i < fields.length; i++) 212 | vals[i] = Integer.parseInt(fields[i]); 213 | return vals; 214 | } 215 | 216 | /** 217 | * Read all doubles until the end of input is reached, and return them. 218 | */ 219 | public static double[] readAllDoubles() { 220 | String[] fields = readAllStrings(); 221 | double[] vals = new double[fields.length]; 222 | for (int i = 0; i < fields.length; i++) 223 | vals[i] = Double.parseDouble(fields[i]); 224 | return vals; 225 | } 226 | 227 | /*** end: section (2 of 2) of code duplicated from In to StdIn */ 228 | 229 | 230 | /** 231 | * If StdIn changes, use this to reinitialize the scanner. 232 | */ 233 | private static void resync() { 234 | setScanner(new Scanner(new java.io.BufferedInputStream(System.in), 235 | charsetName)); 236 | } 237 | 238 | private static void setScanner(Scanner scanner) { 239 | StdIn.scanner = scanner; 240 | StdIn.scanner.useLocale(usLocale); 241 | } 242 | 243 | // do this once when StdIn is initialized 244 | static { 245 | resync(); 246 | } 247 | 248 | /** 249 | * Reads all ints from stdin. 250 | * @deprecated For more consistency, use {@link #readAllInts()} 251 | */ 252 | public static int[] readInts() { 253 | return readAllInts(); 254 | } 255 | 256 | /** 257 | * Reads all doubles from stdin. 258 | * @deprecated For more consistency, use {@link #readAllDoubles()} 259 | */ 260 | public static double[] readDoubles() { 261 | return readAllDoubles(); 262 | } 263 | 264 | /** 265 | * Reads all Strings from stdin. 266 | * @deprecated For more consistency, use {@link #readAllStrings()} 267 | */ 268 | public static String[] readStrings() { 269 | return readAllStrings(); 270 | } 271 | 272 | 273 | /** 274 | * Interactive test of basic functionality. 275 | */ 276 | public static void main(String[] args) { 277 | 278 | System.out.println("Type a string: "); 279 | String s = StdIn.readString(); 280 | System.out.println("Your string was: " + s); 281 | System.out.println(); 282 | 283 | System.out.println("Type an int: "); 284 | int a = StdIn.readInt(); 285 | System.out.println("Your int was: " + a); 286 | System.out.println(); 287 | 288 | System.out.println("Type a boolean: "); 289 | boolean b = StdIn.readBoolean(); 290 | System.out.println("Your boolean was: " + b); 291 | System.out.println(); 292 | 293 | System.out.println("Type a double: "); 294 | double c = StdIn.readDouble(); 295 | System.out.println("Your double was: " + c); 296 | System.out.println(); 297 | 298 | } 299 | 300 | } 301 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdAudio.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac StdAudio.java 3 | * Execution: java StdAudio 4 | * 5 | * Simple library for reading, writing, and manipulating .wav files. 6 | 7 | * 8 | * Limitations 9 | * ----------- 10 | * - Does not seem to work properly when reading .wav files from a .jar file. 11 | * - Assumes the audio is monaural, with sampling rate of 44,100. 12 | * 13 | *************************************************************************/ 14 | package com.datastructure.Helper; 15 | import java.applet.*; 16 | import java.io.*; 17 | import java.net.*; 18 | import javax.sound.sampled.*; 19 | 20 | /** 21 | * Standard audio. This class provides a basic capability for 22 | * creating, reading, and saving audio. 23 | *

24 | * The audio format uses a sampling rate of 44,100 (CD quality audio), 16-bit, monaural. 25 | * 26 | *

27 | * For additional documentation, see Section 1.5 of 28 | * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. 29 | * 30 | * @author Robert Sedgewick 31 | * @author Kevin Wayne 32 | */ 33 | public final class StdAudio { 34 | 35 | /** 36 | * The sample rate - 44,100 Hz for CD quality audio. 37 | */ 38 | public static final int SAMPLE_RATE = 44100; 39 | 40 | private static final int BYTES_PER_SAMPLE = 2; // 16-bit audio 41 | private static final int BITS_PER_SAMPLE = 16; // 16-bit audio 42 | private static final double MAX_16_BIT = Short.MAX_VALUE; // 32,767 43 | private static final int SAMPLE_BUFFER_SIZE = 4096; 44 | 45 | 46 | private static SourceDataLine line; // to play the sound 47 | private static byte[] buffer; // our internal buffer 48 | private static int bufferSize = 0; // number of samples currently in internal buffer 49 | 50 | // do not instantiate 51 | private StdAudio() { } 52 | 53 | 54 | // static initializer 55 | static { init(); } 56 | 57 | // open up an audio stream 58 | private static void init() { 59 | try { 60 | // 44,100 samples per second, 16-bit audio, mono, signed PCM, little Endian 61 | AudioFormat format = new AudioFormat((float) SAMPLE_RATE, BITS_PER_SAMPLE, 1, true, false); 62 | DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); 63 | 64 | line = (SourceDataLine) AudioSystem.getLine(info); 65 | line.open(format, SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE); 66 | 67 | // the internal buffer is a fraction of the actual buffer size, this choice is arbitrary 68 | // it gets divided because we can't expect the buffered data to line up exactly with when 69 | // the sound card decides to push out its samples. 70 | buffer = new byte[SAMPLE_BUFFER_SIZE * BYTES_PER_SAMPLE/3]; 71 | } catch (Exception e) { 72 | System.out.println(e.getMessage()); 73 | System.exit(1); 74 | } 75 | 76 | // no sound gets made before this call 77 | line.start(); 78 | } 79 | 80 | 81 | /** 82 | * Close standard audio. 83 | */ 84 | public static void close() { 85 | line.drain(); 86 | line.stop(); 87 | } 88 | 89 | /** 90 | * Write one sample (between -1.0 and +1.0) to standard audio. If the sample 91 | * is outside the range, it will be clipped. 92 | */ 93 | public static void play(double in) { 94 | 95 | // clip if outside [-1, +1] 96 | if (in < -1.0) in = -1.0; 97 | if (in > +1.0) in = +1.0; 98 | 99 | // convert to bytes 100 | short s = (short) (MAX_16_BIT * in); 101 | buffer[bufferSize++] = (byte) s; 102 | buffer[bufferSize++] = (byte) (s >> 8); // little Endian 103 | 104 | // send to sound card if buffer is full 105 | if (bufferSize >= buffer.length) { 106 | line.write(buffer, 0, buffer.length); 107 | bufferSize = 0; 108 | } 109 | } 110 | 111 | /** 112 | * Write an array of samples (between -1.0 and +1.0) to standard audio. If a sample 113 | * is outside the range, it will be clipped. 114 | */ 115 | public static void play(double[] input) { 116 | for (int i = 0; i < input.length; i++) { 117 | play(input[i]); 118 | } 119 | } 120 | 121 | /** 122 | * Read audio samples from a file (in .wav or .au format) and return them as a double array 123 | * with values between -1.0 and +1.0. 124 | */ 125 | public static double[] read(String filename) { 126 | byte[] data = readByte(filename); 127 | int N = data.length; 128 | double[] d = new double[N/2]; 129 | for (int i = 0; i < N/2; i++) { 130 | d[i] = ((short) (((data[2*i+1] & 0xFF) << 8) + (data[2*i] & 0xFF))) / ((double) MAX_16_BIT); 131 | } 132 | return d; 133 | } 134 | 135 | 136 | 137 | 138 | /** 139 | * Play a sound file (in .wav, .mid, or .au format) in a background thread. 140 | */ 141 | public static void play(String filename) { 142 | URL url = null; 143 | try { 144 | File file = new File(filename); 145 | if (file.canRead()) url = file.toURI().toURL(); 146 | } 147 | catch (MalformedURLException e) { e.printStackTrace(); } 148 | // URL url = StdAudio.class.getResource(filename); 149 | if (url == null) throw new RuntimeException("audio " + filename + " not found"); 150 | AudioClip clip = Applet.newAudioClip(url); 151 | clip.play(); 152 | } 153 | 154 | /** 155 | * Loop a sound file (in .wav, .mid, or .au format) in a background thread. 156 | */ 157 | public static void loop(String filename) { 158 | URL url = null; 159 | try { 160 | File file = new File(filename); 161 | if (file.canRead()) url = file.toURI().toURL(); 162 | } 163 | catch (MalformedURLException e) { e.printStackTrace(); } 164 | // URL url = StdAudio.class.getResource(filename); 165 | if (url == null) throw new RuntimeException("audio " + filename + " not found"); 166 | AudioClip clip = Applet.newAudioClip(url); 167 | clip.loop(); 168 | } 169 | 170 | 171 | // return data as a byte array 172 | private static byte[] readByte(String filename) { 173 | byte[] data = null; 174 | AudioInputStream ais = null; 175 | try { 176 | 177 | // try to read from file 178 | File file = new File(filename); 179 | if (file.exists()) { 180 | ais = AudioSystem.getAudioInputStream(file); 181 | data = new byte[ais.available()]; 182 | ais.read(data); 183 | } 184 | 185 | // try to read from URL 186 | else { 187 | URL url = StdAudio.class.getResource(filename); 188 | ais = AudioSystem.getAudioInputStream(url); 189 | data = new byte[ais.available()]; 190 | ais.read(data); 191 | } 192 | } 193 | catch (Exception e) { 194 | System.out.println(e.getMessage()); 195 | throw new RuntimeException("Could not read " + filename); 196 | } 197 | 198 | return data; 199 | } 200 | 201 | 202 | 203 | /** 204 | * Save the double array as a sound file (using .wav or .au format). 205 | */ 206 | public static void save(String filename, double[] input) { 207 | 208 | // assumes 44,100 samples per second 209 | // use 16-bit audio, mono, signed PCM, little Endian 210 | AudioFormat format = new AudioFormat(SAMPLE_RATE, 16, 1, true, false); 211 | byte[] data = new byte[2 * input.length]; 212 | for (int i = 0; i < input.length; i++) { 213 | int temp = (short) (input[i] * MAX_16_BIT); 214 | data[2*i + 0] = (byte) temp; 215 | data[2*i + 1] = (byte) (temp >> 8); 216 | } 217 | 218 | // now save the file 219 | try { 220 | ByteArrayInputStream bais = new ByteArrayInputStream(data); 221 | AudioInputStream ais = new AudioInputStream(bais, format, input.length); 222 | if (filename.endsWith(".wav") || filename.endsWith(".WAV")) { 223 | AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(filename)); 224 | } 225 | else if (filename.endsWith(".au") || filename.endsWith(".AU")) { 226 | AudioSystem.write(ais, AudioFileFormat.Type.AU, new File(filename)); 227 | } 228 | else { 229 | throw new RuntimeException("File format not supported: " + filename); 230 | } 231 | } 232 | catch (Exception e) { 233 | System.out.println(e); 234 | System.exit(1); 235 | } 236 | } 237 | 238 | 239 | 240 | 241 | /*********************************************************************** 242 | * sample test client 243 | ***********************************************************************/ 244 | 245 | // create a note (sine wave) of the given frequency (Hz), for the given 246 | // duration (seconds) scaled to the given volume (amplitude) 247 | private static double[] note(double hz, double duration, double amplitude) { 248 | int N = (int) (StdAudio.SAMPLE_RATE * duration); 249 | double[] a = new double[N+1]; 250 | for (int i = 0; i <= N; i++) 251 | a[i] = amplitude * Math.sin(2 * Math.PI * i * hz / StdAudio.SAMPLE_RATE); 252 | return a; 253 | } 254 | 255 | /** 256 | * Test client - play an A major scale to standard audio. 257 | */ 258 | public static void main(String[] args) { 259 | 260 | // 440 Hz for 1 sec 261 | double freq = 440.0; 262 | for (int i = 0; i <= StdAudio.SAMPLE_RATE; i++) { 263 | StdAudio.play(0.5 * Math.sin(2*Math.PI * freq * i / StdAudio.SAMPLE_RATE)); 264 | } 265 | 266 | // scale increments 267 | int[] steps = { 0, 2, 4, 5, 7, 9, 11, 12 }; 268 | for (int i = 0; i < steps.length; i++) { 269 | double hz = 440.0 * Math.pow(2, steps[i] / 12.0); 270 | StdAudio.play(note(hz, 1.0, 0.5)); 271 | } 272 | 273 | 274 | // need to call this in non-interactive stuff so the program doesn't terminate 275 | // until all the sound leaves the speaker. 276 | StdAudio.close(); 277 | 278 | // need to terminate a Java program with sound 279 | System.exit(0); 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/BinaryOut.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryOut.java 3 | * Execution: java BinaryOut 4 | * 5 | * Write binary data to an output stream, either one 1-bit boolean, 6 | * one 8-bit char, one 32-bit int, one 64-bit double, one 32-bit float, 7 | * or one 64-bit long at a time. The output stream can be standard 8 | * output, a file, an OutputStream or a Socket. 9 | * 10 | * The bytes written are not aligned. 11 | * 12 | * [wayne 7.17.2013] fixed bugs in write(char x, int r) and 13 | * write(int x, int r) to add return statement for (r == 8) 14 | * and (r == 32) cases, respectively. 15 | * 16 | *************************************************************************/ 17 | 18 | package com.datastructure.Helper; 19 | import java.io.BufferedOutputStream; 20 | import java.io.FileOutputStream; 21 | import java.io.IOException; 22 | import java.io.OutputStream; 23 | import java.net.Socket; 24 | 25 | /** 26 | * Binary output. This class provides methods for converting 27 | * primtive type variables (boolean, byte, char, 28 | * int, long, float, and double) 29 | * to sequences of bits and writing them to an output stream. 30 | * The output stream can be standard output, a file, an OutputStream or a Socket. 31 | * Uses big-endian (most-significant byte first). 32 | *

33 | * The client must flush() the output stream when finished writing bits. 34 | *

35 | * The client should not intermixing calls to BinaryOut with calls 36 | * to Out; otherwise unexpected behavior will result. 37 | * 38 | * @author Robert Sedgewick 39 | * @author Kevin Wayne 40 | */ 41 | public final class BinaryOut { 42 | 43 | private BufferedOutputStream out; // the output stream 44 | private int buffer; // 8-bit buffer of bits to write out 45 | private int N; // number of bits remaining in buffer 46 | 47 | 48 | /** 49 | * Create a binary output stream from an OutputStream. 50 | */ 51 | public BinaryOut(OutputStream os) { 52 | out = new BufferedOutputStream(os); 53 | } 54 | 55 | /** 56 | * Create a binary output stream from standard output. 57 | */ 58 | public BinaryOut() { 59 | out = new BufferedOutputStream(System.out); 60 | } 61 | 62 | /** 63 | * Create a binary output stream from a filename. 64 | */ 65 | public BinaryOut(String s) { 66 | try { 67 | OutputStream os = new FileOutputStream(s); 68 | out = new BufferedOutputStream(os); 69 | } 70 | catch (IOException e) { e.printStackTrace(); } 71 | } 72 | 73 | /** 74 | * Create a binary output stream from a Socket. 75 | */ 76 | public BinaryOut(Socket socket) { 77 | try { 78 | OutputStream os = socket.getOutputStream(); 79 | out = new BufferedOutputStream(os); 80 | } 81 | catch (IOException e) { e.printStackTrace(); } 82 | } 83 | 84 | 85 | /** 86 | * Write the specified bit to the binary output stream. 87 | */ 88 | private void writeBit(boolean bit) { 89 | // add bit to buffer 90 | buffer <<= 1; 91 | if (bit) buffer |= 1; 92 | 93 | // if buffer is full (8 bits), write out as a single byte 94 | N++; 95 | if (N == 8) clearBuffer(); 96 | } 97 | 98 | /** 99 | * Write the 8-bit byte to the binary output stream. 100 | */ 101 | private void writeByte(int x) { 102 | assert x >= 0 && x < 256; 103 | 104 | // optimized if byte-aligned 105 | if (N == 0) { 106 | try { out.write(x); } 107 | catch (IOException e) { e.printStackTrace(); } 108 | return; 109 | } 110 | 111 | // otherwise write one bit at a time 112 | for (int i = 0; i < 8; i++) { 113 | boolean bit = ((x >>> (8 - i - 1)) & 1) == 1; 114 | writeBit(bit); 115 | } 116 | } 117 | 118 | // write out any remaining bits in buffer to the binary output stream, padding with 0s 119 | private void clearBuffer() { 120 | if (N == 0) return; 121 | if (N > 0) buffer <<= (8 - N); 122 | try { out.write(buffer); } 123 | catch (IOException e) { e.printStackTrace(); } 124 | N = 0; 125 | buffer = 0; 126 | } 127 | 128 | /** 129 | * Flush the binary output stream, padding 0s if number of bits written so far 130 | * is not a multiple of 8. 131 | */ 132 | public void flush() { 133 | clearBuffer(); 134 | try { out.flush(); } 135 | catch (IOException e) { e.printStackTrace(); } 136 | } 137 | 138 | /** 139 | * Close and flush the binary output stream. Once it is closed, you can no longer write bits. 140 | */ 141 | public void close() { 142 | flush(); 143 | try { out.close(); } 144 | catch (IOException e) { e.printStackTrace(); } 145 | } 146 | 147 | 148 | /** 149 | * Write the specified bit to the binary output stream. 150 | * @param x the boolean to write. 151 | */ 152 | public void write(boolean x) { 153 | writeBit(x); 154 | } 155 | 156 | /** 157 | * Write the 8-bit byte to the binary output stream. 158 | * @param x the byte to write. 159 | */ 160 | public void write(byte x) { 161 | writeByte(x & 0xff); 162 | } 163 | 164 | /** 165 | * Write the 32-bit int to the binary output stream. 166 | * @param x the int to write. 167 | */ 168 | public void write(int x) { 169 | writeByte((x >>> 24) & 0xff); 170 | writeByte((x >>> 16) & 0xff); 171 | writeByte((x >>> 8) & 0xff); 172 | writeByte((x >>> 0) & 0xff); 173 | } 174 | 175 | /** 176 | * Write the r-bit int to the binary output stream. 177 | * @param x the int to write. 178 | * @param r the number of relevant bits in the char. 179 | * @throws RuntimeException if r is not between 1 and 32. 180 | * @throws RuntimeException if x is not between 0 and 2r - 1. 181 | */ 182 | public void write(int x, int r) { 183 | if (r == 32) { write(x); return; } 184 | if (r < 1 || r > 32) throw new RuntimeException("Illegal value for r = " + r); 185 | if (x < 0 || x >= (1 << r)) throw new RuntimeException("Illegal " + r + "-bit char = " + x); 186 | for (int i = 0; i < r; i++) { 187 | boolean bit = ((x >>> (r - i - 1)) & 1) == 1; 188 | writeBit(bit); 189 | } 190 | } 191 | 192 | 193 | /** 194 | * Write the 64-bit double to the binary output stream. 195 | * @param x the double to write. 196 | */ 197 | public void write(double x) { 198 | write(Double.doubleToRawLongBits(x)); 199 | } 200 | 201 | /** 202 | * Write the 64-bit long to the binary output stream. 203 | * @param x the long to write. 204 | */ 205 | public void write(long x) { 206 | writeByte((int) ((x >>> 56) & 0xff)); 207 | writeByte((int) ((x >>> 48) & 0xff)); 208 | writeByte((int) ((x >>> 40) & 0xff)); 209 | writeByte((int) ((x >>> 32) & 0xff)); 210 | writeByte((int) ((x >>> 24) & 0xff)); 211 | writeByte((int) ((x >>> 16) & 0xff)); 212 | writeByte((int) ((x >>> 8) & 0xff)); 213 | writeByte((int) ((x >>> 0) & 0xff)); 214 | } 215 | 216 | /** 217 | * Write the 32-bit float to the binary output stream. 218 | * @param x the float to write. 219 | */ 220 | public void write(float x) { 221 | write(Float.floatToRawIntBits(x)); 222 | } 223 | 224 | /** 225 | * Write the 16-bit int to the binary output stream. 226 | * @param x the short to write. 227 | */ 228 | public void write(short x) { 229 | writeByte((x >>> 8) & 0xff); 230 | writeByte((x >>> 0) & 0xff); 231 | } 232 | 233 | /** 234 | * Write the 8-bit char to the binary output stream. 235 | * @param x the char to write. 236 | * @throws RuntimeException if x is not betwen 0 and 255. 237 | */ 238 | public void write(char x) { 239 | if (x < 0 || x >= 256) throw new RuntimeException("Illegal 8-bit char = " + x); 240 | writeByte(x); 241 | } 242 | 243 | /** 244 | * Write the r-bit char to the binary output stream. 245 | * @param x the char to write. 246 | * @param r the number of relevant bits in the char. 247 | * @throws RuntimeException if r is not between 1 and 16. 248 | * @throws RuntimeException if x is not between 0 and 2r - 1. 249 | */ 250 | public void write(char x, int r) { 251 | if (r == 8) { write(x); return; } 252 | if (r < 1 || r > 16) throw new RuntimeException("Illegal value for r = " + r); 253 | if (x < 0 || x >= (1 << r)) throw new RuntimeException("Illegal " + r + "-bit char = " + x); 254 | for (int i = 0; i < r; i++) { 255 | boolean bit = ((x >>> (r - i - 1)) & 1) == 1; 256 | writeBit(bit); 257 | } 258 | } 259 | 260 | /** 261 | * Write the string of 8-bit characters to the binary output stream. 262 | * @param s the String to write. 263 | * @throws RuntimeException if any character in the string is not 264 | * between 0 and 255. 265 | */ 266 | public void write(String s) { 267 | for (int i = 0; i < s.length(); i++) 268 | write(s.charAt(i)); 269 | } 270 | 271 | 272 | /** 273 | * Write the String of r-bit characters to the binary output stream. 274 | * @param s the String to write. 275 | * @param r the number of relevants bits in each character. 276 | * @throws RuntimeException if r is not between 1 and 16. 277 | * @throws RuntimeException if any character in the string is not 278 | * between 0 and 2r - 1. 279 | */ 280 | public void write(String s, int r) { 281 | for (int i = 0; i < s.length(); i++) 282 | write(s.charAt(i), r); 283 | } 284 | 285 | 286 | /** 287 | * Test client. Read bits from standard input and write to the file 288 | * specified on command line. 289 | */ 290 | public static void main(String[] args) { 291 | 292 | // create binary output stream to write to file 293 | String filename = args[0]; 294 | BinaryOut out = new BinaryOut(filename); 295 | BinaryIn in = new BinaryIn(); 296 | 297 | // read from standard input and write to file 298 | while (!in.isEmpty()) { 299 | char c = in.readChar(); 300 | out.write(c); 301 | } 302 | out.flush(); 303 | } 304 | 305 | } 306 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdStats.java: -------------------------------------------------------------------------------- 1 | 2 | /************************************************************************* 3 | * Compilation: javac StdStats.java 4 | * Execution: java StdStats < input.txt 5 | * 6 | * Library of statistical functions. 7 | * 8 | * The test client reads an array of real numbers from standard 9 | * input, and computes the minimum, mean, maximum, and 10 | * standard deviation. 11 | * 12 | * The functions all throw a NullPointerException if the array 13 | * passed in is null. 14 | 15 | * % more tiny.txt 16 | * 5 17 | * 3.0 1.0 2.0 5.0 4.0 18 | * 19 | * % java StdStats < tiny.txt 20 | * min 1.000 21 | * mean 3.000 22 | * max 5.000 23 | * std dev 1.581 24 | * 25 | *************************************************************************/ 26 | package com.datastructure.Helper; 27 | /** 28 | * Standard statistics. This class provides methods for computing 29 | * statistics such as min, max, mean, sample standard deviation, and 30 | * sample variance. 31 | *

32 | * For additional documentation, see 33 | * Section 2.2 of 34 | * Introduction to Programming in Java: An Interdisciplinary Approach 35 | * by Robert Sedgewick and Kevin Wayne. 36 | * 37 | * @author Robert Sedgewick 38 | * @author Kevin Wayne 39 | */ 40 | public final class StdStats { 41 | 42 | private StdStats() { } 43 | 44 | /** 45 | * Returns the maximum value in the array a[], -infinity if no such value. 46 | */ 47 | public static double max(double[] a) { 48 | double max = Double.NEGATIVE_INFINITY; 49 | for (int i = 0; i < a.length; i++) { 50 | if (a[i] > max) max = a[i]; 51 | } 52 | return max; 53 | } 54 | 55 | /** 56 | * Returns the maximum value in the subarray a[lo..hi], -infinity if no such value. 57 | */ 58 | public static double max(double[] a, int lo, int hi) { 59 | if (lo < 0 || hi >= a.length || lo > hi) 60 | throw new RuntimeException("Subarray indices out of bounds"); 61 | double max = Double.NEGATIVE_INFINITY; 62 | for (int i = lo; i <= hi; i++) { 63 | if (a[i] > max) max = a[i]; 64 | } 65 | return max; 66 | } 67 | 68 | /** 69 | * Returns the maximum value in the array a[], Integer.MIN_VALUE if no such value. 70 | */ 71 | public static int max(int[] a) { 72 | int max = Integer.MIN_VALUE; 73 | for (int i = 0; i < a.length; i++) { 74 | if (a[i] > max) max = a[i]; 75 | } 76 | return max; 77 | } 78 | 79 | /** 80 | * Returns the minimum value in the array a[], +infinity if no such value. 81 | */ 82 | public static double min(double[] a) { 83 | double min = Double.POSITIVE_INFINITY; 84 | for (int i = 0; i < a.length; i++) { 85 | if (a[i] < min) min = a[i]; 86 | } 87 | return min; 88 | } 89 | 90 | /** 91 | * Returns the minimum value in the subarray a[lo..hi], +infinity if no such value. 92 | */ 93 | public static double min(double[] a, int lo, int hi) { 94 | if (lo < 0 || hi >= a.length || lo > hi) 95 | throw new RuntimeException("Subarray indices out of bounds"); 96 | double min = Double.POSITIVE_INFINITY; 97 | for (int i = lo; i <= hi; i++) { 98 | if (a[i] < min) min = a[i]; 99 | } 100 | return min; 101 | } 102 | 103 | /** 104 | * Returns the minimum value in the array a[], Integer.MAX_VALUE if no such value. 105 | */ 106 | public static int min(int[] a) { 107 | int min = Integer.MAX_VALUE; 108 | for (int i = 0; i < a.length; i++) { 109 | if (a[i] < min) min = a[i]; 110 | } 111 | return min; 112 | } 113 | 114 | /** 115 | * Returns the average value in the array a[], NaN if no such value. 116 | */ 117 | public static double mean(double[] a) { 118 | if (a.length == 0) return Double.NaN; 119 | double sum = sum(a); 120 | return sum / a.length; 121 | } 122 | 123 | /** 124 | * Returns the average value in the subarray a[lo..hi], NaN if no such value. 125 | */ 126 | public static double mean(double[] a, int lo, int hi) { 127 | int length = hi - lo + 1; 128 | if (lo < 0 || hi >= a.length || lo > hi) 129 | throw new RuntimeException("Subarray indices out of bounds"); 130 | if (length == 0) return Double.NaN; 131 | double sum = sum(a, lo, hi); 132 | return sum / length; 133 | } 134 | 135 | /** 136 | * Returns the average value in the array a[], NaN if no such value. 137 | */ 138 | public static double mean(int[] a) { 139 | if (a.length == 0) return Double.NaN; 140 | double sum = 0.0; 141 | for (int i = 0; i < a.length; i++) { 142 | sum = sum + a[i]; 143 | } 144 | return sum / a.length; 145 | } 146 | 147 | /** 148 | * Returns the sample variance in the array a[], NaN if no such value. 149 | */ 150 | public static double var(double[] a) { 151 | if (a.length == 0) return Double.NaN; 152 | double avg = mean(a); 153 | double sum = 0.0; 154 | for (int i = 0; i < a.length; i++) { 155 | sum += (a[i] - avg) * (a[i] - avg); 156 | } 157 | return sum / (a.length - 1); 158 | } 159 | 160 | /** 161 | * Returns the sample variance in the subarray a[lo..hi], NaN if no such value. 162 | */ 163 | public static double var(double[] a, int lo, int hi) { 164 | int length = hi - lo + 1; 165 | if (lo < 0 || hi >= a.length || lo > hi) 166 | throw new RuntimeException("Subarray indices out of bounds"); 167 | if (length == 0) return Double.NaN; 168 | double avg = mean(a, lo, hi); 169 | double sum = 0.0; 170 | for (int i = lo; i <= hi; i++) { 171 | sum += (a[i] - avg) * (a[i] - avg); 172 | } 173 | return sum / (length - 1); 174 | } 175 | 176 | /** 177 | * Returns the sample variance in the array a[], NaN if no such value. 178 | */ 179 | public static double var(int[] a) { 180 | if (a.length == 0) return Double.NaN; 181 | double avg = mean(a); 182 | double sum = 0.0; 183 | for (int i = 0; i < a.length; i++) { 184 | sum += (a[i] - avg) * (a[i] - avg); 185 | } 186 | return sum / (a.length - 1); 187 | } 188 | 189 | /** 190 | * Returns the population variance in the array a[], NaN if no such value. 191 | */ 192 | public static double varp(double[] a) { 193 | if (a.length == 0) return Double.NaN; 194 | double avg = mean(a); 195 | double sum = 0.0; 196 | for (int i = 0; i < a.length; i++) { 197 | sum += (a[i] - avg) * (a[i] - avg); 198 | } 199 | return sum / a.length; 200 | } 201 | 202 | /** 203 | * Returns the population variance in the subarray a[lo..hi], NaN if no such value. 204 | */ 205 | public static double varp(double[] a, int lo, int hi) { 206 | int length = hi - lo + 1; 207 | if (lo < 0 || hi >= a.length || lo > hi) 208 | throw new RuntimeException("Subarray indices out of bounds"); 209 | if (length == 0) return Double.NaN; 210 | double avg = mean(a, lo, hi); 211 | double sum = 0.0; 212 | for (int i = lo; i <= hi; i++) { 213 | sum += (a[i] - avg) * (a[i] - avg); 214 | } 215 | return sum / length; 216 | } 217 | 218 | 219 | /** 220 | * Returns the sample standard deviation in the array a[], NaN if no such value. 221 | */ 222 | public static double stddev(double[] a) { 223 | return Math.sqrt(var(a)); 224 | } 225 | 226 | /** 227 | * Returns the sample standard deviation in the subarray a[lo..hi], NaN if no such value. 228 | */ 229 | public static double stddev(double[] a, int lo, int hi) { 230 | return Math.sqrt(var(a, lo, hi)); 231 | } 232 | 233 | /** 234 | * Returns the sample standard deviation in the array a[], NaN if no such value. 235 | */ 236 | public static double stddev(int[] a) { 237 | return Math.sqrt(var(a)); 238 | } 239 | 240 | /** 241 | * Returns the population standard deviation in the array a[], NaN if no such value. 242 | */ 243 | public static double stddevp(double[] a) { 244 | return Math.sqrt(varp(a)); 245 | } 246 | 247 | /** 248 | * Returns the population standard deviation in the subarray a[lo..hi], NaN if no such value. 249 | */ 250 | public static double stddevp(double[] a, int lo, int hi) { 251 | return Math.sqrt(varp(a, lo, hi)); 252 | } 253 | 254 | /** 255 | * Returns the sum of all values in the array a[]. 256 | */ 257 | public static double sum(double[] a) { 258 | double sum = 0.0; 259 | for (int i = 0; i < a.length; i++) { 260 | sum += a[i]; 261 | } 262 | return sum; 263 | } 264 | 265 | /** 266 | * Returns the sum of all values in the subarray a[lo..hi]. 267 | */ 268 | public static double sum(double[] a, int lo, int hi) { 269 | if (lo < 0 || hi >= a.length || lo > hi) 270 | throw new RuntimeException("Subarray indices out of bounds"); 271 | double sum = 0.0; 272 | for (int i = lo; i <= hi; i++) { 273 | sum += a[i]; 274 | } 275 | return sum; 276 | } 277 | 278 | /** 279 | * Returns the sum of all values in the array a[]. 280 | */ 281 | public static int sum(int[] a) { 282 | int sum = 0; 283 | for (int i = 0; i < a.length; i++) { 284 | sum += a[i]; 285 | } 286 | return sum; 287 | } 288 | 289 | /** 290 | * Plots the points (i, a[i]) to standard draw. 291 | */ 292 | public static void plotPoints(double[] a) { 293 | int N = a.length; 294 | StdDraw.setXscale(0, N-1); 295 | StdDraw.setPenRadius(1.0 / (3.0 * N)); 296 | for (int i = 0; i < N; i++) { 297 | StdDraw.point(i, a[i]); 298 | } 299 | } 300 | 301 | /** 302 | * Plots line segments connecting points (i, a[i]) to standard draw. 303 | */ 304 | public static void plotLines(double[] a) { 305 | int N = a.length; 306 | StdDraw.setXscale(0, N-1); 307 | StdDraw.setPenRadius(); 308 | for (int i = 1; i < N; i++) { 309 | StdDraw.line(i-1, a[i-1], i, a[i]); 310 | } 311 | } 312 | 313 | /** 314 | * Plots bars from (0, a[i]) to (i, a[i]) to standard draw. 315 | */ 316 | public static void plotBars(double[] a) { 317 | int N = a.length; 318 | StdDraw.setXscale(0, N-1); 319 | for (int i = 0; i < N; i++) { 320 | StdDraw.filledRectangle(i, a[i]/2, .25, a[i]/2); 321 | } 322 | } 323 | 324 | 325 | /** 326 | * Test client. 327 | * Convert command-line arguments to array of doubles and call various methods. 328 | */ 329 | public static void main(String[] args) { 330 | double[] a = StdArrayIO.readDouble1D(); 331 | StdOut.printf(" min %7.3f\n", min(a)); 332 | StdOut.printf(" mean %7.3f\n", mean(a)); 333 | StdOut.printf(" max %7.3f\n", max(a)); 334 | StdOut.printf(" std dev %7.3f\n", stddev(a)); 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/BinaryIn.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac BinaryIn.java 3 | * Execution: java BinaryIn input output 4 | * 5 | * This library is for reading binary data from an input stream. 6 | * 7 | * % java BinaryIn http://introcs.cs.princeton.edu/cover.jpg output.jpg 8 | * 9 | *************************************************************************/ 10 | 11 | package com.datastructure.Helper; 12 | 13 | import java.io.BufferedInputStream; 14 | import java.io.File; 15 | import java.io.FileInputStream; 16 | import java.io.IOException; 17 | import java.io.InputStream; 18 | import java.net.Socket; 19 | import java.net.URL; 20 | import java.net.URLConnection; 21 | 22 | 23 | /** 24 | * Binary input. This class provides methods for reading 25 | * in bits from a binary input stream, either 26 | * one bit at a time (as a boolean), 27 | * 8 bits at a time (as a byte or char), 28 | * 16 bits at a time (as a short), 29 | * 32 bits at a time (as an int or float), or 30 | * 64 bits at a time (as a double or long). 31 | *

32 | * The binary input stream can be from standard input, a filename, 33 | * a URL name, a Socket, or an InputStream. 34 | *

35 | * All primitive types are assumed to be represented using their 36 | * standard Java representations, in big-endian (most significant 37 | * byte first) order. 38 | *

39 | * The client should not intermix calls to BinaryIn with calls 40 | * to In; otherwise unexpected behavior will result. 41 | * 42 | * @author Robert Sedgewick 43 | * @author Kevin Wayne 44 | */ 45 | public final class BinaryIn { 46 | private static final int EOF = -1; // end of file 47 | 48 | private BufferedInputStream in; // the input stream 49 | private int buffer; // one character buffer 50 | private int N; // number of bits left in buffer 51 | 52 | /** 53 | * Create a binary input stream from standard input. 54 | */ 55 | public BinaryIn() { 56 | in = new BufferedInputStream(System.in); 57 | fillBuffer(); 58 | } 59 | 60 | /** 61 | * Create a binary input stream from an InputStream. 62 | */ 63 | public BinaryIn(InputStream is) { 64 | in = new BufferedInputStream(is); 65 | fillBuffer(); 66 | } 67 | 68 | /** 69 | * Create a binary input stream from a socket. 70 | */ 71 | public BinaryIn(Socket socket) { 72 | try { 73 | InputStream is = socket.getInputStream(); 74 | in = new BufferedInputStream(is); 75 | fillBuffer(); 76 | } 77 | catch (IOException ioe) { 78 | System.err.println("Could not open " + socket); 79 | } 80 | } 81 | 82 | /** 83 | * Create a binary input stream from a URL. 84 | */ 85 | public BinaryIn(URL url) { 86 | try { 87 | URLConnection site = url.openConnection(); 88 | InputStream is = site.getInputStream(); 89 | in = new BufferedInputStream(is); 90 | fillBuffer(); 91 | } 92 | catch (IOException ioe) { 93 | System.err.println("Could not open " + url); 94 | } 95 | } 96 | 97 | /** 98 | * Create a binary input stream from a filename or URL name. 99 | */ 100 | public BinaryIn(String s) { 101 | 102 | try { 103 | // first try to read file from local file system 104 | File file = new File(s); 105 | if (file.exists()) { 106 | FileInputStream fis = new FileInputStream(file); 107 | in = new BufferedInputStream(fis); 108 | fillBuffer(); 109 | return; 110 | } 111 | 112 | // next try for files included in jar 113 | URL url = getClass().getResource(s); 114 | 115 | // or URL from web 116 | if (url == null) { url = new URL(s); } 117 | 118 | URLConnection site = url.openConnection(); 119 | InputStream is = site.getInputStream(); 120 | in = new BufferedInputStream(is); 121 | fillBuffer(); 122 | } 123 | catch (IOException ioe) { 124 | System.err.println("Could not open " + s); 125 | } 126 | } 127 | 128 | private void fillBuffer() { 129 | try { buffer = in.read(); N = 8; } 130 | catch (IOException e) { System.err.println("EOF"); buffer = EOF; N = -1; } 131 | } 132 | 133 | /** 134 | * Does the binary input stream exist? 135 | */ 136 | public boolean exists() { 137 | return in != null; 138 | } 139 | 140 | /** 141 | * Returns true if the binary input stream is empty. 142 | * @return true if and only if the binary input stream is empty 143 | */ 144 | public boolean isEmpty() { 145 | return buffer == EOF; 146 | } 147 | 148 | /** 149 | * Read the next bit of data from the binary input stream and return as a boolean. 150 | * @return the next bit of data from the binary input stream as a boolean 151 | * @throws RuntimeException if the input stream is empty 152 | */ 153 | public boolean readBoolean() { 154 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 155 | N--; 156 | boolean bit = ((buffer >> N) & 1) == 1; 157 | if (N == 0) fillBuffer(); 158 | return bit; 159 | } 160 | 161 | /** 162 | * Read the next 8 bits from the binary input stream and return as an 8-bit char. 163 | * @return the next 8 bits of data from the binary input stream as a char 164 | * @throws RuntimeException if there are fewer than 8 bits available 165 | */ 166 | public char readChar() { 167 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 168 | 169 | // special case when aligned byte 170 | if (N == 8) { 171 | int x = buffer; 172 | fillBuffer(); 173 | return (char) (x & 0xff); 174 | } 175 | 176 | // combine last N bits of current buffer with first 8-N bits of new buffer 177 | int x = buffer; 178 | x <<= (8-N); 179 | int oldN = N; 180 | fillBuffer(); 181 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 182 | N = oldN; 183 | x |= (buffer >>> N); 184 | return (char) (x & 0xff); 185 | // the above code doesn't quite work for the last character if N = 8 186 | // because buffer will be -1 187 | } 188 | 189 | 190 | /** 191 | * Read the next r bits from the binary input stream and return as an r-bit character. 192 | * @param r number of bits to read. 193 | * @return the next r bits of data from the binary input streamt as a char 194 | * @throws RuntimeException if there are fewer than r bits available 195 | */ 196 | public char readChar(int r) { 197 | if (r < 1 || r > 16) throw new RuntimeException("Illegal value of r = " + r); 198 | 199 | // optimize r = 8 case 200 | if (r == 8) return readChar(); 201 | 202 | char x = 0; 203 | for (int i = 0; i < r; i++) { 204 | x <<= 1; 205 | boolean bit = readBoolean(); 206 | if (bit) x |= 1; 207 | } 208 | return x; 209 | } 210 | 211 | 212 | /** 213 | * Read the remaining bytes of data from the binary input stream and return as a string. 214 | * @return the remaining bytes of data from the binary input stream as a String 215 | * @throws RuntimeException if the input stream is empty or if the number of bits 216 | * available is not a multiple of 8 (byte-aligned) 217 | */ 218 | public String readString() { 219 | if (isEmpty()) throw new RuntimeException("Reading from empty input stream"); 220 | 221 | StringBuilder sb = new StringBuilder(); 222 | while (!isEmpty()) { 223 | char c = readChar(); 224 | sb.append(c); 225 | } 226 | return sb.toString(); 227 | } 228 | 229 | 230 | /** 231 | * Read the next 16 bits from the binary input stream and return as a 16-bit short. 232 | * @return the next 16 bits of data from the binary standard input as a short 233 | * @throws RuntimeException if there are fewer than 16 bits available 234 | */ 235 | public short readShort() { 236 | short x = 0; 237 | for (int i = 0; i < 2; i++) { 238 | char c = readChar(); 239 | x <<= 8; 240 | x |= c; 241 | } 242 | return x; 243 | } 244 | 245 | /** 246 | * Read the next 32 bits from the binary input stream and return as a 32-bit int. 247 | * @return the next 32 bits of data from the binary input stream as a int 248 | * @throws RuntimeException if there are fewer than 32 bits available 249 | */ 250 | public int readInt() { 251 | int x = 0; 252 | for (int i = 0; i < 4; i++) { 253 | char c = readChar(); 254 | x <<= 8; 255 | x |= c; 256 | } 257 | return x; 258 | } 259 | 260 | /** 261 | * Read the next r bits from the binary input stream return as an r-bit int. 262 | * @param r number of bits to read. 263 | * @return the next r bits of data from the binary input stream as a int 264 | * @throws RuntimeException if there are fewer than r bits available on standard input 265 | */ 266 | public int readInt(int r) { 267 | if (r < 1 || r > 32) throw new RuntimeException("Illegal value of r = " + r); 268 | 269 | // optimize r = 32 case 270 | if (r == 32) return readInt(); 271 | 272 | int x = 0; 273 | for (int i = 0; i < r; i++) { 274 | x <<= 1; 275 | boolean bit = readBoolean(); 276 | if (bit) x |= 1; 277 | } 278 | return x; 279 | } 280 | 281 | /** 282 | * Read the next 64 bits from the binary input stream and return as a 64-bit long. 283 | * @return the next 64 bits of data from the binary input stream as a long 284 | * @throws RuntimeException if there are fewer than 64 bits available 285 | */ 286 | public long readLong() { 287 | long x = 0; 288 | for (int i = 0; i < 8; i++) { 289 | char c = readChar(); 290 | x <<= 8; 291 | x |= c; 292 | } 293 | return x; 294 | } 295 | 296 | /** 297 | * Read the next 64 bits from the binary input stream and return as a 64-bit double. 298 | * @return the next 64 bits of data from the binary input stream as a double 299 | * @throws RuntimeException if there are fewer than 64 bits available 300 | */ 301 | public double readDouble() { 302 | return Double.longBitsToDouble(readLong()); 303 | } 304 | 305 | /** 306 | * Read the next 32 bits from standard input and return as a 32-bit float. 307 | * @return the next 32 bits of data from standard input as a float 308 | * @throws RuntimeException if there are fewer than 32 bits available on standard input 309 | */ 310 | public float readFloat() { 311 | return Float.intBitsToFloat(readInt()); 312 | } 313 | 314 | 315 | /** 316 | * Read the next 8 bits from the binary input stream and return as an 8-bit byte. 317 | * @return the next 8 bits of data from the binary input stream as a byte 318 | * @throws RuntimeException if there are fewer than 8 bits available 319 | */ 320 | public byte readByte() { 321 | char c = readChar(); 322 | byte x = (byte) (c & 0xff); 323 | return x; 324 | } 325 | 326 | /** 327 | * Test client. Reads in the name of a file or url (first command-line 328 | * argument) and writes it to a file (second command-line argument). 329 | */ 330 | public static void main(String[] args) { 331 | BinaryIn in = new BinaryIn(args[0]); 332 | BinaryOut out = new BinaryOut(args[1]); 333 | 334 | // read one 8-bit char at a time 335 | while (!in.isEmpty()) { 336 | char c = in.readChar(); 337 | out.write(c); 338 | } 339 | out.flush(); 340 | } 341 | } 342 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdRandom.java: -------------------------------------------------------------------------------- 1 | /************************************************************************* 2 | * Compilation: javac StdRandom.java 3 | * Execution: java StdRandom 4 | * 5 | * A library of static methods to generate pseudo-random numbers from 6 | * different distributions (bernoulli, uniform, gaussian, discrete, 7 | * and exponential). Also includes a method for shuffling an array. 8 | * 9 | * 10 | * % java StdRandom 5 11 | * seed = 1316600602069 12 | * 59 16.81826 true 8.83954 0 13 | * 32 91.32098 true 9.11026 0 14 | * 35 10.11874 true 8.95396 3 15 | * 92 32.88401 true 8.87089 0 16 | * 72 92.55791 true 9.46241 0 17 | * 18 | * % java StdRandom 5 19 | * seed = 1316600616575 20 | * 96 60.17070 true 8.72821 0 21 | * 79 32.01607 true 8.58159 0 22 | * 81 59.49065 true 9.10423 1 23 | * 96 51.65818 true 9.02102 0 24 | * 99 17.55771 true 8.99762 0 25 | * 26 | * % java StdRandom 5 1316600616575 27 | * seed = 1316600616575 28 | * 96 60.17070 true 8.72821 0 29 | * 79 32.01607 true 8.58159 0 30 | * 81 59.49065 true 9.10423 1 31 | * 96 51.65818 true 9.02102 0 32 | * 99 17.55771 true 8.99762 0 33 | * 34 | * 35 | * Remark 36 | * ------ 37 | * - Relies on randomness of nextDouble() method in java.util.Random 38 | * to generate pseudorandom numbers in [0, 1). 39 | * 40 | * - This library allows you to set and get the pseudorandom number seed. 41 | * 42 | * - See http://www.honeylocust.com/RngPack/ for an industrial 43 | * strength random number generator in Java. 44 | * 45 | *************************************************************************/ 46 | package com.datastructure.Helper; 47 | import java.util.Random; 48 | 49 | /** 50 | * Standard random. This class provides methods for generating 51 | * random number from various distributions. 52 | *

53 | * For additional documentation, see Section 2.2 of 54 | * Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne. 55 | * 56 | * @author Robert Sedgewick 57 | * @author Kevin Wayne 58 | */ 59 | public final class StdRandom { 60 | 61 | private static Random random; // pseudo-random number generator 62 | private static long seed; // pseudo-random number generator seed 63 | 64 | // static initializer 65 | static { 66 | // this is how the seed was set in Java 1.4 67 | seed = System.currentTimeMillis(); 68 | random = new Random(seed); 69 | } 70 | 71 | // don't instantiate 72 | private StdRandom() { } 73 | 74 | /** 75 | * Sets the seed of the psedurandom number generator. 76 | */ 77 | public static void setSeed(long s) { 78 | seed = s; 79 | random = new Random(seed); 80 | } 81 | 82 | /** 83 | * Returns the seed of the psedurandom number generator. 84 | */ 85 | public static long getSeed() { 86 | return seed; 87 | } 88 | 89 | /** 90 | * Return real number uniformly in [0, 1). 91 | */ 92 | public static double uniform() { 93 | return random.nextDouble(); 94 | } 95 | 96 | /** 97 | * Returns an integer uniformly between 0 (inclusive) and N (exclusive). 98 | * @throws IllegalArgumentException if N <= 0 99 | */ 100 | public static int uniform(int N) { 101 | if (N <= 0) throw new IllegalArgumentException("Parameter N must be positive"); 102 | return random.nextInt(N); 103 | } 104 | 105 | /////////////////////////////////////////////////////////////////////////// 106 | // STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA 107 | // THE STATIC METHODS ABOVE. 108 | /////////////////////////////////////////////////////////////////////////// 109 | 110 | /** 111 | * Returns a real number uniformly in [0, 1). 112 | * @deprecated clearer to use {@link #uniform()} 113 | */ 114 | public static double random() { 115 | return uniform(); 116 | } 117 | 118 | /** 119 | * Returns an integer uniformly in [a, b). 120 | * @throws IllegalArgumentException if b <= a 121 | * @throws IllegalArgumentException if b - a >= Integer.MAX_VALUE 122 | */ 123 | public static int uniform(int a, int b) { 124 | if (b <= a) throw new IllegalArgumentException("Invalid range"); 125 | if ((long) b - a >= Integer.MAX_VALUE) throw new IllegalArgumentException("Invalid range"); 126 | return a + uniform(b - a); 127 | } 128 | 129 | /** 130 | * Returns a real number uniformly in [a, b). 131 | * @throws IllegalArgumentException if b <= a 132 | */ 133 | public static double uniform(double a, double b) { 134 | if (b <= a) throw new IllegalArgumentException("Invalid range"); 135 | return a + uniform() * (b-a); 136 | } 137 | 138 | /** 139 | * Returns a boolean, which is true with probability p, and false otherwise. 140 | * @throws IllegalArgumentException if either p < 0.0 or p > 1.0 141 | */ 142 | public static boolean bernoulli(double p) { 143 | if (p < 0.0 || p > 1.0) 144 | throw new IllegalArgumentException("Probability must be between 0.0 and 1.0"); 145 | return uniform() < p; 146 | } 147 | 148 | /** 149 | * Returns a boolean, which is true with probability .5, and false otherwise. 150 | */ 151 | public static boolean bernoulli() { 152 | return bernoulli(0.5); 153 | } 154 | 155 | /** 156 | * Returns a real number with a standard Gaussian distribution. 157 | */ 158 | public static double gaussian() { 159 | // use the polar form of the Box-Muller transform 160 | double r, x, y; 161 | do { 162 | x = uniform(-1.0, 1.0); 163 | y = uniform(-1.0, 1.0); 164 | r = x*x + y*y; 165 | } while (r >= 1 || r == 0); 166 | return x * Math.sqrt(-2 * Math.log(r) / r); 167 | 168 | // Remark: y * Math.sqrt(-2 * Math.log(r) / r) 169 | // is an independent random gaussian 170 | } 171 | 172 | /** 173 | * Returns a real number from a gaussian distribution with given mean and stddev 174 | */ 175 | public static double gaussian(double mean, double stddev) { 176 | return mean + stddev * gaussian(); 177 | } 178 | 179 | /** 180 | * Returns an integer with a geometric distribution with mean 1/p. 181 | * @throws IllegalArgumentException if either p < 0.0 or p > 1.0 182 | */ 183 | public static int geometric(double p) { 184 | if (p < 0.0 || p > 1.0) 185 | throw new IllegalArgumentException("Probability must be between 0.0 and 1.0"); 186 | // using algorithm given by Knuth 187 | return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p)); 188 | } 189 | 190 | /** 191 | * Return an integer with a Poisson distribution with mean lambda. 192 | * @throws IllegalArgumentException if lambda <= 0.0 193 | */ 194 | public static int poisson(double lambda) { 195 | if (lambda <= 0.0) 196 | throw new IllegalArgumentException("Parameter lambda must be positive"); 197 | // using algorithm given by Knuth 198 | // see http://en.wikipedia.org/wiki/Poisson_distribution 199 | int k = 0; 200 | double p = 1.0; 201 | double L = Math.exp(-lambda); 202 | do { 203 | k++; 204 | p *= uniform(); 205 | } while (p >= L); 206 | return k-1; 207 | } 208 | 209 | /** 210 | * Returns a real number with a Pareto distribution with parameter alpha. 211 | * @throws IllegalArgumentException if alpha <= 0.0 212 | */ 213 | public static double pareto(double alpha) { 214 | if (alpha <= 0.0) 215 | throw new IllegalArgumentException("Shape parameter alpha must be positive"); 216 | return Math.pow(1 - uniform(), -1.0/alpha) - 1.0; 217 | } 218 | 219 | /** 220 | * Returns a real number with a Cauchy distribution. 221 | */ 222 | public static double cauchy() { 223 | return Math.tan(Math.PI * (uniform() - 0.5)); 224 | } 225 | 226 | /** 227 | * Returns a number from a discrete distribution: i with probability a[i]. 228 | * throws IllegalArgumentException if sum of array entries is not (very nearly) equal to 1.0 229 | * throws IllegalArgumentException if a[i] < 0.0 for any index i 230 | */ 231 | public static int discrete(double[] a) { 232 | double EPSILON = 1E-14; 233 | double sum = 0.0; 234 | for (int i = 0; i < a.length; i++) { 235 | if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]); 236 | sum = sum + a[i]; 237 | } 238 | if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON) 239 | throw new IllegalArgumentException("sum of array entries not equal to one: " + sum); 240 | 241 | // the for loop may not return a value when both r is (nearly) 1.0 and when the 242 | // cumulative sum is less than 1.0 (as a result of floating-point roundoff error) 243 | while (true) { 244 | double r = uniform(); 245 | sum = 0.0; 246 | for (int i = 0; i < a.length; i++) { 247 | sum = sum + a[i]; 248 | if (sum > r) return i; 249 | } 250 | } 251 | } 252 | 253 | /** 254 | * Returns a real number from an exponential distribution with rate lambda. 255 | * @throws IllegalArgumentException if lambda <= 0.0 256 | */ 257 | public static double exp(double lambda) { 258 | if (lambda <= 0.0) 259 | throw new IllegalArgumentException("Rate lambda must be positive"); 260 | return -Math.log(1 - uniform()) / lambda; 261 | } 262 | 263 | /** 264 | * Rearrange the elements of an array in random order. 265 | */ 266 | public static void shuffle(Object[] a) { 267 | int N = a.length; 268 | for (int i = 0; i < N; i++) { 269 | int r = i + uniform(N-i); // between i and N-1 270 | Object temp = a[i]; 271 | a[i] = a[r]; 272 | a[r] = temp; 273 | } 274 | } 275 | 276 | /** 277 | * Rearrange the elements of a double array in random order. 278 | */ 279 | public static void shuffle(double[] a) { 280 | int N = a.length; 281 | for (int i = 0; i < N; i++) { 282 | int r = i + uniform(N-i); // between i and N-1 283 | double temp = a[i]; 284 | a[i] = a[r]; 285 | a[r] = temp; 286 | } 287 | } 288 | 289 | /** 290 | * Rearrange the elements of an int array in random order. 291 | */ 292 | public static void shuffle(int[] a) { 293 | int N = a.length; 294 | for (int i = 0; i < N; i++) { 295 | int r = i + uniform(N-i); // between i and N-1 296 | int temp = a[i]; 297 | a[i] = a[r]; 298 | a[r] = temp; 299 | } 300 | } 301 | 302 | 303 | /** 304 | * Rearrange the elements of the subarray a[lo..hi] in random order. 305 | */ 306 | public static void shuffle(Object[] a, int lo, int hi) { 307 | if (lo < 0 || lo > hi || hi >= a.length) { 308 | throw new IndexOutOfBoundsException("Illegal subarray range"); 309 | } 310 | for (int i = lo; i <= hi; i++) { 311 | int r = i + uniform(hi-i+1); // between i and hi 312 | Object temp = a[i]; 313 | a[i] = a[r]; 314 | a[r] = temp; 315 | } 316 | } 317 | 318 | /** 319 | * Rearrange the elements of the subarray a[lo..hi] in random order. 320 | */ 321 | public static void shuffle(double[] a, int lo, int hi) { 322 | if (lo < 0 || lo > hi || hi >= a.length) { 323 | throw new IndexOutOfBoundsException("Illegal subarray range"); 324 | } 325 | for (int i = lo; i <= hi; i++) { 326 | int r = i + uniform(hi-i+1); // between i and hi 327 | double temp = a[i]; 328 | a[i] = a[r]; 329 | a[r] = temp; 330 | } 331 | } 332 | 333 | /** 334 | * Rearrange the elements of the subarray a[lo..hi] in random order. 335 | */ 336 | public static void shuffle(int[] a, int lo, int hi) { 337 | if (lo < 0 || lo > hi || hi >= a.length) { 338 | throw new IndexOutOfBoundsException("Illegal subarray range"); 339 | } 340 | for (int i = lo; i <= hi; i++) { 341 | int r = i + uniform(hi-i+1); // between i and hi 342 | int temp = a[i]; 343 | a[i] = a[r]; 344 | a[r] = temp; 345 | } 346 | } 347 | 348 | /** 349 | * Unit test. 350 | */ 351 | public static void main(String[] args) { 352 | int N = Integer.parseInt(args[0]); 353 | if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1])); 354 | double[] t = { .5, .3, .1, .1 }; 355 | 356 | StdOut.println("seed = " + StdRandom.getSeed()); 357 | for (int i = 0; i < N; i++) { 358 | StdOut.printf("%2d " , uniform(100)); 359 | StdOut.printf("%8.5f ", uniform(10.0, 99.0)); 360 | StdOut.printf("%5b " , bernoulli(.5)); 361 | StdOut.printf("%7.5f ", gaussian(9.0, .2)); 362 | StdOut.printf("%2d " , discrete(t)); 363 | StdOut.println(); 364 | } 365 | 366 | String[] a = "A B C D E F G".split(" "); 367 | for (String s : a) 368 | StdOut.print(s + " "); 369 | StdOut.println(); 370 | } 371 | 372 | } 373 | -------------------------------------------------------------------------------- /src/main/java/com/datastructure/Helper/StdInTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Test client for StdIn and In. 3 | **/ 4 | package com.datastructure.Helper; 5 | import java.util.Scanner; 6 | import java.lang.reflect.Array; 7 | import java.lang.reflect.Method; 8 | import java.io.ByteArrayInputStream; 9 | 10 | public class StdInTest { 11 | 12 | // make a printable/readable version of an object 13 | public static Object escape(Object original) { 14 | if (original instanceof Character) { 15 | char u = (char) ((Character)original); 16 | int idx = "\b\t\n\f\r\"\'\\".indexOf(u); 17 | if (idx >= 0) 18 | return "\\"+"btnfr\"\'\\".charAt(idx); 19 | if (u < 32) 20 | return "\\"+Integer.toOctalString(u); 21 | if (u > 126) 22 | return "\\u"+String.format("%04X", (int)u); 23 | return original; 24 | } 25 | else if (original instanceof String) { 26 | StringBuilder result = new StringBuilder(); 27 | for (char c : ((String)original).toCharArray()) 28 | result.append(escape(c)); 29 | return "\"" + result.toString() + "\""; 30 | } 31 | else if (original.getClass().isArray()) { 32 | StringBuilder result = new StringBuilder("["); 33 | int len = Array.getLength(original); 34 | for (int i=0; iInput. This class provides methods for reading strings 20 | * and numbers from standard input, file input, URLs, and sockets. 21 | *

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

27 | * For additional documentation, see 28 | * Section 3.1 of 29 | * Introduction to Programming in Java: An Interdisciplinary Approach 30 | * by Robert Sedgewick and Kevin Wayne. 31 | *

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

37 | * Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines 38 | * consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085; 39 | * see 40 | * Scanner.java (NB: Java 6u23 and earlier uses only \r, \r, \r\n). 41 | * 42 | * @author David Pritchard 43 | * @author Robert Sedgewick 44 | * @author Kevin Wayne 45 | */ 46 | public final class In { 47 | 48 | private Scanner scanner; 49 | 50 | /*** begin: section (1 of 2) of code duplicated from In to StdIn */ 51 | 52 | // assume Unicode UTF-8 encoding 53 | private static final String charsetName = "UTF-8"; 54 | 55 | // assume language = English, country = US for consistency with System.out. 56 | private static final java.util.Locale usLocale = 57 | new java.util.Locale("en", "US"); 58 | 59 | // the default token separator; we maintain the invariant that this value 60 | // is held by the scanner's delimiter between calls 61 | private static final Pattern WHITESPACE_PATTERN 62 | = Pattern.compile("\\p{javaWhitespace}+"); 63 | 64 | // makes whitespace characters significant 65 | private static final Pattern EMPTY_PATTERN 66 | = Pattern.compile(""); 67 | 68 | // used to read the entire input. source: 69 | // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html 70 | private static final Pattern EVERYTHING_PATTERN 71 | = Pattern.compile("\\A"); 72 | 73 | /*** end: section (1 of 2) of code duplicated from In to StdIn */ 74 | 75 | /** 76 | * Create an input stream from standard input. 77 | */ 78 | public In() { 79 | scanner = new Scanner(new BufferedInputStream(System.in), charsetName); 80 | scanner.useLocale(usLocale); 81 | } 82 | 83 | /** 84 | * Create an input stream from a socket. 85 | */ 86 | public In(java.net.Socket socket) { 87 | try { 88 | InputStream is = socket.getInputStream(); 89 | scanner = new Scanner(new BufferedInputStream(is), charsetName); 90 | scanner.useLocale(usLocale); 91 | } 92 | catch (IOException ioe) { 93 | System.err.println("Could not open " + socket); 94 | } 95 | } 96 | 97 | /** 98 | * Create an input stream from a URL. 99 | */ 100 | public In(URL url) { 101 | try { 102 | URLConnection site = url.openConnection(); 103 | InputStream is = site.getInputStream(); 104 | scanner = new Scanner(new BufferedInputStream(is), charsetName); 105 | scanner.useLocale(usLocale); 106 | } 107 | catch (IOException ioe) { 108 | System.err.println("Could not open " + url); 109 | } 110 | } 111 | 112 | /** 113 | * Create an input stream from a file. 114 | */ 115 | public In(File file) { 116 | try { 117 | scanner = new Scanner(file, charsetName); 118 | scanner.useLocale(usLocale); 119 | } 120 | catch (IOException ioe) { 121 | System.err.println("Could not open " + file); 122 | } 123 | } 124 | 125 | 126 | /** 127 | * Create an input stream from a filename or web page name. 128 | */ 129 | public In(String s) { 130 | try { 131 | // first try to read file from local file system 132 | File file = new File(s); 133 | if (file.exists()) { 134 | scanner = new Scanner(file, charsetName); 135 | scanner.useLocale(usLocale); 136 | return; 137 | } 138 | 139 | // next try for files included in jar 140 | URL url = getClass().getResource(s); 141 | 142 | // or URL from web 143 | if (url == null) { url = new URL(s); } 144 | 145 | URLConnection site = url.openConnection(); 146 | 147 | // in order to set User-Agent, replace above line with these two 148 | // HttpURLConnection site = (HttpURLConnection) url.openConnection(); 149 | // site.addRequestProperty("User-Agent", "Mozilla/4.76"); 150 | 151 | InputStream is = site.getInputStream(); 152 | scanner = new Scanner(new BufferedInputStream(is), charsetName); 153 | scanner.useLocale(usLocale); 154 | } 155 | catch (IOException ioe) { 156 | System.err.println("Could not open " + s); 157 | } 158 | } 159 | 160 | /** 161 | * Create an input stream from a given Scanner source; use with 162 | * new Scanner(String) to read from a string. 163 | *

164 | * Note that this does not create a defensive copy, so the 165 | * scanner will be mutated as you read on. 166 | */ 167 | public In(Scanner scanner) { 168 | this.scanner = scanner; 169 | } 170 | 171 | /** 172 | * Does the input stream exist? 173 | */ 174 | public boolean exists() { 175 | return scanner != null; 176 | } 177 | 178 | /*** begin: section (2 of 2) of code duplicated from In to StdIn, 179 | * with all methods changed from "public" to "public static" ***/ 180 | 181 | /** 182 | * Is the input empty (except possibly for whitespace)? Use this 183 | * to know whether the next call to {@link #readString()}, 184 | * {@link #readDouble()}, etc will succeed. 185 | */ 186 | public boolean isEmpty() { 187 | return !scanner.hasNext(); 188 | } 189 | 190 | /** 191 | * Does the input have a next line? Use this to know whether the 192 | * next call to {@link #readLine()} will succeed.

Functionally 193 | * equivalent to {@link #hasNextChar()}. 194 | */ 195 | public boolean hasNextLine() { 196 | return scanner.hasNextLine(); 197 | } 198 | 199 | /** 200 | * Is the input empty (including whitespace)? Use this to know 201 | * whether the next call to {@link #readChar()} will succeed.

Functionally 202 | * equivalent to {@link #hasNextLine()}. 203 | */ 204 | public boolean hasNextChar() { 205 | scanner.useDelimiter(EMPTY_PATTERN); 206 | boolean result = scanner.hasNext(); 207 | scanner.useDelimiter(WHITESPACE_PATTERN); 208 | return result; 209 | } 210 | 211 | 212 | /** 213 | * Read and return the next line. 214 | */ 215 | public String readLine() { 216 | String line; 217 | try { line = scanner.nextLine(); } 218 | catch (Exception e) { line = null; } 219 | return line; 220 | } 221 | 222 | /** 223 | * Read and return the next character. 224 | */ 225 | public char readChar() { 226 | scanner.useDelimiter(EMPTY_PATTERN); 227 | String ch = scanner.next(); 228 | assert (ch.length() == 1) : "Internal (Std)In.readChar() error!" 229 | + " Please contact the authors."; 230 | scanner.useDelimiter(WHITESPACE_PATTERN); 231 | return ch.charAt(0); 232 | } 233 | 234 | 235 | /** 236 | * Read and return the remainder of the input as a string. 237 | */ 238 | public String readAll() { 239 | if (!scanner.hasNextLine()) 240 | return ""; 241 | 242 | String result = scanner.useDelimiter(EVERYTHING_PATTERN).next(); 243 | // not that important to reset delimeter, since now scanner is empty 244 | scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway 245 | return result; 246 | } 247 | 248 | 249 | /** 250 | * Read and return the next string. 251 | */ 252 | public String readString() { 253 | return scanner.next(); 254 | } 255 | 256 | /** 257 | * Read and return the next int. 258 | */ 259 | public int readInt() { 260 | return scanner.nextInt(); 261 | } 262 | 263 | /** 264 | * Read and return the next double. 265 | */ 266 | public double readDouble() { 267 | return scanner.nextDouble(); 268 | } 269 | 270 | /** 271 | * Read and return the next float. 272 | */ 273 | public float readFloat() { 274 | return scanner.nextFloat(); 275 | } 276 | 277 | /** 278 | * Read and return the next long. 279 | */ 280 | public long readLong() { 281 | return scanner.nextLong(); 282 | } 283 | 284 | /** 285 | * Read and return the next short. 286 | */ 287 | public short readShort() { 288 | return scanner.nextShort(); 289 | } 290 | 291 | /** 292 | * Read and return the next byte. 293 | */ 294 | public byte readByte() { 295 | return scanner.nextByte(); 296 | } 297 | 298 | /** 299 | * Read and return the next boolean, allowing case-insensitive 300 | * "true" or "1" for true, and "false" or "0" for false. 301 | */ 302 | public boolean readBoolean() { 303 | String s = readString(); 304 | if (s.equalsIgnoreCase("true")) return true; 305 | if (s.equalsIgnoreCase("false")) return false; 306 | if (s.equals("1")) return true; 307 | if (s.equals("0")) return false; 308 | throw new java.util.InputMismatchException(); 309 | } 310 | 311 | /** 312 | * Read all strings until the end of input is reached, and return them. 313 | */ 314 | public String[] readAllStrings() { 315 | // we could use readAll.trim().split(), but that's not consistent 316 | // since trim() uses characters 0x00..0x20 as whitespace 317 | String[] tokens = WHITESPACE_PATTERN.split(readAll()); 318 | if (tokens.length == 0 || tokens[0].length() > 0) 319 | return tokens; 320 | String[] decapitokens = new String[tokens.length-1]; 321 | for (int i = 0; i < tokens.length-1; i++) 322 | decapitokens[i] = tokens[i+1]; 323 | return decapitokens; 324 | } 325 | 326 | /** 327 | * Read all ints until the end of input is reached, and return them. 328 | */ 329 | public int[] readAllInts() { 330 | String[] fields = readAllStrings(); 331 | int[] vals = new int[fields.length]; 332 | for (int i = 0; i < fields.length; i++) 333 | vals[i] = Integer.parseInt(fields[i]); 334 | return vals; 335 | } 336 | 337 | /** 338 | * Read all doubles until the end of input is reached, and return them. 339 | */ 340 | public double[] readAllDoubles() { 341 | String[] fields = readAllStrings(); 342 | double[] vals = new double[fields.length]; 343 | for (int i = 0; i < fields.length; i++) 344 | vals[i] = Double.parseDouble(fields[i]); 345 | return vals; 346 | } 347 | 348 | /*** end: section (2 of 2) of code duplicated from In to StdIn */ 349 | 350 | /** 351 | * Close the input stream. 352 | */ 353 | public void close() { 354 | scanner.close(); 355 | } 356 | 357 | /** 358 | * Reads all ints from a file 359 | * @deprecated Clearer to use 360 | * new In(filename).{@link #readAllInts()} 361 | */ 362 | public static int[] readInts(String filename) { 363 | return new In(filename).readAllInts(); 364 | } 365 | 366 | /** 367 | * Reads all doubles from a file 368 | * @deprecated Clearer to use 369 | * new In(filename).{@link #readAllDoubles()} 370 | */ 371 | public static double[] readDoubles(String filename) { 372 | return new In(filename).readAllDoubles(); 373 | } 374 | 375 | /** 376 | * Reads all strings from a file 377 | * @deprecated Clearer to use 378 | * new In(filename).{@link #readAllStrings()} 379 | */ 380 | public static String[] readStrings(String filename) { 381 | return new In(filename).readAllStrings(); 382 | } 383 | 384 | /** 385 | * Reads all ints from stdin 386 | * @deprecated Clearer to use {@link StdIn#readAllInts()} 387 | */ 388 | public static int[] readInts() { 389 | return new In().readAllInts(); 390 | } 391 | 392 | /** 393 | * Reads all doubles from stdin 394 | * @deprecated Clearer to use {@link StdIn#readAllDoubles()} 395 | */ 396 | public static double[] readDoubles() { 397 | return new In().readAllDoubles(); 398 | } 399 | 400 | /** 401 | * Reads all strings from stdin 402 | * @deprecated Clearer to use {@link StdIn#readAllStrings()} 403 | */ 404 | public static String[] readStrings() { 405 | return new In().readAllStrings(); 406 | } 407 | 408 | /** 409 | * Test client. 410 | */ 411 | public static void main(String[] args) { 412 | In in; 413 | String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt"; 414 | 415 | // read from a URL 416 | System.out.println("readAll() from URL " + urlName); 417 | System.out.println("---------------------------------------------------------------------------"); 418 | try { 419 | in = new In(urlName); 420 | System.out.println(in.readAll()); 421 | } 422 | catch (Exception e) { System.out.println(e); } 423 | System.out.println(); 424 | 425 | // read one line at a time from URL 426 | System.out.println("readLine() from URL " + urlName); 427 | System.out.println("---------------------------------------------------------------------------"); 428 | try { 429 | in = new In(urlName); 430 | while (!in.isEmpty()) { 431 | String s = in.readLine(); 432 | System.out.println(s); 433 | } 434 | } 435 | catch (Exception e) { System.out.println(e); } 436 | System.out.println(); 437 | 438 | // read one string at a time from URL 439 | System.out.println("readString() from URL " + urlName); 440 | System.out.println("---------------------------------------------------------------------------"); 441 | try { 442 | in = new In(urlName); 443 | while (!in.isEmpty()) { 444 | String s = in.readString(); 445 | System.out.println(s); 446 | } 447 | } 448 | catch (Exception e) { System.out.println(e); } 449 | System.out.println(); 450 | 451 | 452 | // read one line at a time from file in current directory 453 | System.out.println("readLine() from current directory"); 454 | System.out.println("---------------------------------------------------------------------------"); 455 | try { 456 | in = new In("./InTest.txt"); 457 | while (!in.isEmpty()) { 458 | String s = in.readLine(); 459 | System.out.println(s); 460 | } 461 | } 462 | catch (Exception e) { System.out.println(e); } 463 | System.out.println(); 464 | 465 | 466 | // read one line at a time from file using relative path 467 | System.out.println("readLine() from relative path"); 468 | System.out.println("---------------------------------------------------------------------------"); 469 | try { 470 | in = new In("../stdlib/InTest.txt"); 471 | while (!in.isEmpty()) { 472 | String s = in.readLine(); 473 | System.out.println(s); 474 | } 475 | } 476 | catch (Exception e) { System.out.println(e); } 477 | System.out.println(); 478 | 479 | // read one char at a time 480 | System.out.println("readChar() from file"); 481 | System.out.println("---------------------------------------------------------------------------"); 482 | try { 483 | in = new In("InTest.txt"); 484 | while (!in.isEmpty()) { 485 | char c = in.readChar(); 486 | System.out.print(c); 487 | } 488 | } 489 | catch (Exception e) { System.out.println(e); } 490 | System.out.println(); 491 | System.out.println(); 492 | 493 | // read one line at a time from absolute OS X / Linux path 494 | System.out.println("readLine() from absolute OS X / Linux path"); 495 | System.out.println("---------------------------------------------------------------------------"); 496 | in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt"); 497 | try { 498 | while (!in.isEmpty()) { 499 | String s = in.readLine(); 500 | System.out.println(s); 501 | } 502 | } 503 | catch (Exception e) { System.out.println(e); } 504 | System.out.println(); 505 | 506 | 507 | // read one line at a time from absolute Windows path 508 | System.out.println("readLine() from absolute Windows path"); 509 | System.out.println("---------------------------------------------------------------------------"); 510 | try { 511 | in = new In("G:\\www\\introcs\\stdlib\\InTest.txt"); 512 | while (!in.isEmpty()) { 513 | String s = in.readLine(); 514 | System.out.println(s); 515 | } 516 | System.out.println(); 517 | } 518 | catch (Exception e) { System.out.println(e); } 519 | System.out.println(); 520 | 521 | } 522 | 523 | } 524 | --------------------------------------------------------------------------------