├── 9781430266198.jpg ├── BinaryTree.class ├── BinaryTree.java ├── Index.class ├── LICENSE.txt ├── LinkedList$Node.class ├── LinkedList.class ├── LinkedList.java ├── Node.class ├── NodeData.class ├── NodeData.java ├── NodeDataCh.java ├── P10_1DistinctNumbers.class ├── P10_1DistinctNumbers.java ├── P10_2HashChain.class ├── P10_2HashChain.java ├── P10_3WordFrequencyHash.class ├── P10_3WordFrequencyHash.java ├── P1_1SelectSortTest.java ├── P1_2InsertSortTest.java ├── P1_2aInsertSort1Test.java ├── P1_2bInsertSort2Test.java ├── P1_3SortStrings.java ├── P1_4ParallelSort.java ├── P1_5BinarySearchTest.java ├── P1_6BinarySearchString.java ├── P1_7WordFrequency.java ├── P1_7WordFrequency1.java ├── P1_8MergeTest.java ├── P1_8aMergeTest.class ├── P1_8aMergeTest.java ├── P2_1Sum.java ├── P2_2PartTest.java ├── P2_3SearchTest.java ├── P2_4WordFrequency.java ├── P2_5Voting.class ├── P2_5Voting.java ├── P2_5aVoting.java ├── P3_1BuildList1.java ├── P3_2BuildList2.java ├── P3_3BuildList3.java ├── P3_4LinkedListTest.java ├── P3_5Palindrome.java ├── P3_6MergeLists.class ├── P3_6MergeLists.java ├── P3_7CountOut.java ├── P4_1StackTest.java ├── P4_2StackTest.java ├── P4_3StackTest.java ├── P4_4DecimalToBinary.java ├── P4_5InfixToPostfix.class ├── P4_5InfixToPostfix.java ├── P4_6EvalExpression.java ├── P4_7QueueTest.java ├── P4_8QueueTest.java ├── P5_1MergeSortTest.java ├── P5_2Organisms.java ├── P5_3Maze.java ├── P6_1RandomTest.java ├── P6_2GuessTheNumber.java ├── P6_3Arithmetic.java ├── P6_4Nim.class ├── P6_4Nim.java ├── P6_5BottleCaps.java ├── P6_6SimulateQueue.java ├── P6_7Root5.java ├── P6_8Pi.class ├── P6_8Pi.java ├── P7_10UpdateFile.java ├── P7_1CompareFiles.java ├── P7_2CreateBinaryFile.java ├── P7_3ReadBinaryFile.java ├── P7_4CreateBinaryFile1.java ├── P7_5CreateBinaryFile2.java ├── P7_6CreateRandomAccess.java ├── P7_7ReadRandomAccess.java ├── P7_8CreateIndex.java ├── P7_9UseIndex.java ├── P7_xPrintFileInOrder.java ├── P8_1BinaryTreeTest.java ├── P8_2WordFrequencyBST.java ├── P8_3BinarySearchTreeTest.java ├── P8_4LevelOrderTest.java ├── P9_1HeapSortTest.java ├── P9_2SiftUpTest.java ├── P9_3QuicksortTest.java ├── P9_4Quicksort3Test.class ├── P9_4Quicksort3Test.java ├── P9_5ShellSortTest.class ├── P9_5ShellSortTest.java ├── Part.class ├── Person.class ├── QNode.class ├── Queue.class ├── QueueData.class ├── README.md ├── Stack.class ├── TreeNode.class ├── VoteCount.class ├── WordInfo.class ├── btree.in ├── compfile1.txt ├── compfile2.txt ├── contributing.md ├── heap.in ├── index.bin ├── maze.in ├── maze.out ├── num.bin ├── num.txt ├── numbers.in ├── orgs.in ├── orgs.out ├── output.txt ├── parts.bin ├── parts.txt ├── passage.txt ├── quick.in ├── results.txt ├── shell.in ├── votes.txt ├── wordFreq.in ├── wordFreq.out └── words.in /9781430266198.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/9781430266198.jpg -------------------------------------------------------------------------------- /BinaryTree.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/BinaryTree.class -------------------------------------------------------------------------------- /BinaryTree.java: -------------------------------------------------------------------------------- 1 | // The BinaryTree class 2 | import java.util.*; 3 | public class BinaryTree { 4 | TreeNode root; 5 | 6 | public BinaryTree() { 7 | root = null; 8 | } 9 | public BinaryTree(Scanner in) { 10 | root = buildTree(in); 11 | } 12 | 13 | public static TreeNode buildTree(Scanner in) { 14 | String str = in.next(); 15 | if (str.equals("@")) return null; 16 | TreeNode p = new TreeNode(new NodeData(str)); 17 | p.left = buildTree(in); 18 | p.right = buildTree(in); 19 | return p; 20 | } //end buildTree 21 | 22 | public void preOrder() { 23 | preOrderTraversal(root); 24 | } 25 | public void preOrderTraversal(TreeNode node) { 26 | if (node!= null) { 27 | node.data.visit(); 28 | preOrderTraversal(node.left); 29 | preOrderTraversal(node.right); 30 | } 31 | } //end preOrderTraversal 32 | 33 | public void inOrder() { 34 | inOrderTraversal(root); 35 | } 36 | 37 | public void inOrderTraversal(TreeNode node) { 38 | if (node!= null) { 39 | inOrderTraversal(node.left); 40 | node.data.visit(); 41 | inOrderTraversal(node.right); 42 | } 43 | } //end inOrderTraversal 44 | 45 | public void postOrder() { 46 | postOrderTraversal(root); 47 | } 48 | 49 | public void postOrderTraversal(TreeNode node) { 50 | if (node!= null) { 51 | postOrderTraversal(node.left); 52 | postOrderTraversal(node.right); 53 | node.data.visit(); 54 | } 55 | } //end postOrderTraversal 56 | 57 | } //end class BinaryTree 58 | -------------------------------------------------------------------------------- /Index.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/Index.class -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/LICENSE.txt -------------------------------------------------------------------------------- /LinkedList$Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/LinkedList$Node.class -------------------------------------------------------------------------------- /LinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/LinkedList.class -------------------------------------------------------------------------------- /LinkedList.java: -------------------------------------------------------------------------------- 1 | public class LinkedList { 2 | Node head = null; 3 | 4 | public boolean empty() { 5 | return head == null; 6 | } 7 | 8 | //The method addHead adds an item at the head of the linked list 9 | public void addHead(NodeData nd) { 10 | Node p = new Node(nd); 11 | p.next = head; 12 | head = p; 13 | } 14 | 15 | //The method addInPlace adds an item to a sorted linked list 16 | //so that the list remains sorted 17 | public void addInPlace(NodeData nd) { 18 | Node np, curr, prev; 19 | 20 | np = new Node(nd); 21 | prev = null; 22 | curr = head; 23 | while (curr != null && nd.compareTo(curr.data) > 0) { //nd is bigger 24 | prev = curr; 25 | curr = curr.next; 26 | } 27 | np.next = curr; 28 | if (prev == null) head = np; 29 | else prev.next = np; 30 | } //end addInPlace 31 | 32 | //The method printList prints the contents of a list using 33 | //the toString() method (implicitly) of the NodeData class 34 | public void printList() { 35 | Node curr = head; 36 | while (curr != null) { 37 | System.out.printf("%s", curr.data); //invokes curr.data.toString() 38 | curr = curr.next; 39 | } 40 | System.out.printf("\n"); 41 | } //end printList 42 | 43 | //The function getHeadData returns the data at the head of the list 44 | public NodeData getHeadData() { 45 | if (head == null) return null; 46 | return head.data; 47 | } 48 | 49 | //The method deleteHead removes the first node, if any, in the list. 50 | public void deleteHead() { 51 | if (head != null) head = head.next; 52 | } 53 | 54 | //The method addTail adds a new node at the end of the list. 55 | //It finds the last node (for which next is null) and sets it 56 | //to point to the new node. 57 | public void addTail(NodeData nd) { 58 | Node p = new Node(nd); 59 | if (head == null) head = p; 60 | else { 61 | Node curr = head; 62 | while (curr.next != null) curr = curr.next; 63 | curr.next = p; 64 | } 65 | } //end addTail 66 | 67 | //The function copyList makes a copy of the list used to call it and returns the copy. 68 | public LinkedList copyList() { 69 | LinkedList temp = new LinkedList(); 70 | Node curr = this.head; 71 | while (curr != null) { 72 | temp.addTail(curr.data); 73 | curr = curr.next; 74 | } 75 | return temp; 76 | } //end copyList 77 | 78 | //The method reverseList reverses the order of the nodes in the given list. 79 | //It works on the original list, not a copy. 80 | public void reverseList() { 81 | Node p1, p2, p3; 82 | if (head == null || head.next == null) return; 83 | p1 = head; 84 | p2 = p1.next; 85 | p1.next = null; 86 | while (p2 != null) { 87 | p3 = p2.next; 88 | p2.next = p1; 89 | p1 = p2; 90 | p2 = p3; 91 | } 92 | head = p1; 93 | } //end reverseList 94 | 95 | //The function equals compares two linked lists. 96 | //If L1 and L2 are two linked lists, the expression L1.equals(L2) is true 97 | //if they contain identical elements in the same order and false, otherwise. 98 | public boolean equals(LinkedList LL) { 99 | Node t1 = this.head; 100 | Node t2 = LL.head; 101 | while (t1 != null && t2 != null) { 102 | if (t1.data.compareTo(t2.data) != 0) return false; 103 | t1 = t1.next; 104 | t2 = t2.next; 105 | } 106 | if (t1 != null || t2 != null) return false; //if one ended but not the other 107 | return true; 108 | } //end equals 109 | 110 | //If A and B are two sorted linked lists, A.merge(B) will return a 111 | //LinkedList containing the merged elements of A and B. 112 | public LinkedList merge(LinkedList LL) { 113 | Node A = this.head; 114 | Node B = LL.head; 115 | LinkedList C = new LinkedList(); 116 | while (A != null && B != null) { 117 | if (A.data.compareTo(B.data) < 0) { 118 | C.addTail(A.data); 119 | A = A.next; 120 | } 121 | else { 122 | C.addTail(B.data); 123 | B = B.next; 124 | } 125 | } 126 | while (A != null) { 127 | C.addTail(A.data); 128 | A = A.next; 129 | } 130 | while (B != null) { 131 | C.addTail(B.data); 132 | B = B.next; 133 | } 134 | return C; 135 | } //end merge 136 | 137 | 138 | //If needed, the class Node can be declared public and stored in its own file 139 | class Node { 140 | NodeData data; 141 | Node next; 142 | 143 | public Node(NodeData d) { 144 | data = d; 145 | next = null; 146 | } 147 | } //end class Node 148 | 149 | } //end class LinkedList 150 | 151 | -------------------------------------------------------------------------------- /Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/Node.class -------------------------------------------------------------------------------- /NodeData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/NodeData.class -------------------------------------------------------------------------------- /NodeData.java: -------------------------------------------------------------------------------- 1 | //For a linked list of integers 2 | 3 | public class NodeData { 4 | int num; 5 | 6 | public NodeData(int n) { 7 | num = n; 8 | } 9 | 10 | public int compareTo(NodeData nd) { 11 | if (this.num == nd.num) return 0; 12 | if (this.num < nd.num) return -1; 13 | return 1; 14 | } 15 | 16 | public String toString() { 17 | return num + " "; 18 | //" " needed to convert num to a string; may also use "" (empty string) 19 | } 20 | } //end class NodeData 21 | -------------------------------------------------------------------------------- /NodeDataCh.java: -------------------------------------------------------------------------------- 1 | public class NodeData { 2 | char ch; 3 | 4 | public NodeData(char c) { 5 | ch = c; 6 | } 7 | 8 | public char getData() {return ch;} 9 | 10 | public int compareTo(NodeData nd) { 11 | if (this.ch == nd.ch) return 0; 12 | if (this.ch < nd.ch) return -1; 13 | return 1; 14 | } 15 | 16 | public String toString() { 17 | return ch + ""; 18 | } 19 | } //end class NodeData 20 | -------------------------------------------------------------------------------- /P10_1DistinctNumbers.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P10_1DistinctNumbers.class -------------------------------------------------------------------------------- /P10_1DistinctNumbers.java: -------------------------------------------------------------------------------- 1 | // Program P10.1 2 | import java.util.*; 3 | import java.io.*; 4 | public class P10_1DistinctNumbers { 5 | final static int MaxDistinctNumbers = 20; 6 | final static int N = 23; 7 | final static int Empty = 0; 8 | 9 | public static void main(String[] args) throws IOException { 10 | Scanner in = new Scanner(new FileReader("numbers.in")); 11 | int[] num = new int[N + 1]; 12 | for (int j = 1; j <= N; j++) num[j] = Empty; 13 | int distinct = 0; 14 | while (in.hasNextInt()) { 15 | int key = in.nextInt(); 16 | int loc = key % N + 1; 17 | while (num[loc] != Empty && num[loc] != key) loc = loc % N + 1; 18 | 19 | if (num[loc] == Empty) { //key is not in the table 20 | if (distinct == MaxDistinctNumbers) { 21 | System.out.printf("\nTable full: %d not added\n", key); 22 | System.exit(1); 23 | } 24 | num[loc] = key; 25 | distinct++; 26 | } 27 | } 28 | System.out.printf("\nThere are %d distinct numbers\n", distinct); 29 | in.close(); 30 | } //end main 31 | 32 | } //end class P10_1DistinctNumbers 33 | -------------------------------------------------------------------------------- /P10_2HashChain.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P10_2HashChain.class -------------------------------------------------------------------------------- /P10_2HashChain.java: -------------------------------------------------------------------------------- 1 | // Program P10.2 2 | import java.util.*; 3 | import java.io.*; 4 | public class P10_2HashChain { 5 | final static int N = 13; 6 | public static void main(String[] args) throws IOException { 7 | Scanner in = new Scanner(new FileReader("numbers.in")); 8 | 9 | Node[] hash = new Node[N+1]; 10 | for (int h = 1; h <= N; h++) hash[h] = null; 11 | int distinct = 0; 12 | while (in.hasNextInt()) { 13 | int key = in.nextInt(); 14 | if (!search(key, hash, N)) distinct++; 15 | } 16 | System.out.printf("\nThere are %d distinct numbers\n\n", distinct); 17 | for (int h = 1; h <= N; h++) 18 | if (hash[h] != null) { 19 | System.out.printf("hash[%d]: ", h); 20 | printList(hash[h]); 21 | } 22 | in.close(); 23 | } //end main 24 | 25 | public static boolean search(int inKey, Node[] hash, int n) { 26 | //return true if inKey is found; false, otherwise 27 | //insert a new key in its appropriate list so list is in order 28 | int k = inKey % n + 1; 29 | Node curr = hash[k]; 30 | Node prev = null; 31 | while (curr != null && inKey > curr.num) { 32 | prev = curr; 33 | curr = curr.next; 34 | } 35 | if (curr != null && inKey == curr.num) return true; //found 36 | //not found; inKey is a new key; add it so list is in order 37 | Node np = new Node(inKey); 38 | np.next = curr; 39 | if (prev == null) hash[k] = np; 40 | else prev.next = np; 41 | return false; 42 | } //end search 43 | 44 | public static void printList(Node top) { 45 | while (top != null) { 46 | System.out.printf("%2d ", top.num); 47 | top = top.next; 48 | } 49 | System.out.printf("\n"); 50 | } //end printList 51 | 52 | } //end class P10_2HashChain 53 | 54 | class Node { 55 | int num; 56 | Node next; 57 | 58 | public Node(int n) { 59 | num = n; 60 | next = null; 61 | } 62 | } //end class Node 63 | -------------------------------------------------------------------------------- /P10_3WordFrequencyHash.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P10_3WordFrequencyHash.class -------------------------------------------------------------------------------- /P10_3WordFrequencyHash.java: -------------------------------------------------------------------------------- 1 | // Program P10.3 2 | import java.io.*; 3 | import java.util.*; 4 | public class P10_3WordFrequencyHash { 5 | static Scanner in; 6 | static PrintWriter out; 7 | final static int N = 13; //table size 8 | final static int MaxWords = 10; 9 | final static String Empty = ""; 10 | 11 | public static void main(String[] args) throws IOException { 12 | in = new Scanner(new FileReader("wordFreq.in")); 13 | out = new PrintWriter(new FileWriter("wordFreq.out")); 14 | 15 | WordInfo[] wordTable = new WordInfo[N+1]; 16 | for (int h = 1; h <= N; h++) wordTable[h] = new WordInfo(); 17 | 18 | int first = -1; //points to first word in alphabetical order 19 | int numWords = 0; 20 | 21 | in.useDelimiter("[^a-zA-Z]+"); 22 | while (in.hasNext()) { 23 | String word = in.next().toLowerCase(); 24 | int loc = search(wordTable, word); 25 | if (loc > 0) wordTable[loc].freq++; 26 | else //this is a new word 27 | if (numWords < MaxWords) { //if table is not full 28 | first = addToTable(wordTable, word, -loc, first); 29 | ++numWords; 30 | } 31 | else out.printf("'%s' not added to table\n", word); 32 | } 33 | printResults(wordTable, first); 34 | in.close(); 35 | out.close(); 36 | } // end main 37 | 38 | public static int search(WordInfo[] table, String key) { 39 | //search for key in table; if found, return its location; if not, 40 | //return -loc if it must be inserted in location loc 41 | int wordNum = convertToNumber(key); 42 | int loc = wordNum % N + 1; 43 | int k = wordNum % (N - 2) + 1; 44 | 45 | while (!table[loc].word.equals(Empty) && !table[loc].word.equals(key)) { 46 | loc = loc + k; 47 | if (loc > N) loc = loc - N; 48 | } 49 | if (table[loc].word.equals(Empty)) return -loc; 50 | return loc; 51 | } // end search 52 | 53 | public static int convertToNumber(String key) { 54 | int wordNum = 0; 55 | int w = 3; 56 | for (int h = 0; h < key.length(); h++) { 57 | wordNum += key.charAt(h) * w; 58 | w = w + 2; 59 | } 60 | return wordNum; 61 | } //end convertToNumber 62 | 63 | public static int addToTable(WordInfo[] table, String key, int loc, int head) { 64 | //stores key in table[loc] and links it in alphabetical order 65 | table[loc].word = key; 66 | table[loc].freq = 1; 67 | int curr = head; 68 | int prev = -1; 69 | while (curr != -1 && key.compareTo(table[curr].word) > 0) { 70 | prev = curr; 71 | curr = table[curr].next; 72 | } 73 | table[loc].next = curr; 74 | if (prev == -1) return loc; //new first item 75 | table[prev].next = loc; 76 | return head; //first item did not change 77 | } //end addToTable 78 | 79 | public static void printResults(WordInfo[] table, int head) { 80 | out.printf("\nWords Frequency\n\n"); 81 | while (head != -1) { 82 | out.printf("%-15s %2d\n", table[head].word, table[head].freq); 83 | head = table[head].next; 84 | } 85 | } //end printResults 86 | 87 | } //end class P10_3WordFrequencyHash 88 | 89 | class WordInfo { 90 | String word = ""; 91 | int freq = 0; 92 | int next = -1; 93 | } //end class WordInfo 94 | 95 | -------------------------------------------------------------------------------- /P1_1SelectSortTest.java: -------------------------------------------------------------------------------- 1 | //Program P1.1 2 | import java.util.*; 3 | public class P1_1SelectSortTest { 4 | final static int MaxNumbers = 10; 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | int[] num = new int[10]; 8 | System.out.printf("Type up to %d numbers followed by 0\n", MaxNumbers); 9 | int n = 0; 10 | int v = in.nextInt(); 11 | while (v != 0 && n < MaxNumbers) { 12 | num[n++] = v; 13 | v = in.nextInt(); 14 | } 15 | if (v != 0) { 16 | System.out.printf("\nMore than %d numbers entered\n", MaxNumbers); 17 | System.out.printf("First %d used\n", MaxNumbers); 18 | } 19 | if (n == 0) { 20 | System.out.printf("\nNo numbers supplied\n"); 21 | System.exit(1); 22 | } 23 | //n numbers are stored from num[0] to num[n-1] 24 | selectionSort(num, 0, n-1); 25 | System.out.printf("\nThe sorted numbers are\n"); 26 | for (v = 0; v < n; v++) System.out.printf("%d ", num[v]); 27 | System.out.printf("\n"); 28 | } //end main 29 | 30 | public static void selectionSort(int[] list, int lo, int hi) { 31 | //sort list[lo] to list[hi] in ascending order 32 | for (int h = lo; h < hi; h++) { 33 | int s = getSmallest(list, h, hi); 34 | swap(list, h, s); 35 | } 36 | } 37 | 38 | public static int getSmallest(int list[], int lo, int hi) { 39 | //return location of smallest from list[lo..hi] 40 | int small = lo; 41 | for (int h = lo + 1; h <= hi; h++) 42 | if (list[h] < list[small]) small = h; 43 | return small; 44 | } 45 | 46 | public static void swap(int list[], int i, int j) { 47 | //swap elements list[i] and list[j] 48 | int hold = list[i]; 49 | list[i] = list[j]; 50 | list[j] = hold; 51 | } 52 | } //end class P1_1SelectSortTest 53 | -------------------------------------------------------------------------------- /P1_2InsertSortTest.java: -------------------------------------------------------------------------------- 1 | //Program P1.2 2 | import java.util.*; 3 | public class P1_2InsertSortTest { 4 | final static int MaxNumbers = 10; 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | int[] num = new int[MaxNumbers]; 8 | System.out.printf("Type up to %d numbers followed by 0\n", MaxNumbers); 9 | int n = 0; 10 | int v = in.nextInt(); 11 | while (v != 0 && n < MaxNumbers) { 12 | num[n++] = v; 13 | v = in.nextInt(); 14 | } 15 | if (v != 0) { 16 | System.out.printf("\nMore than %d numbers entered\n", MaxNumbers); 17 | System.out.printf("First %d used\n", MaxNumbers); 18 | } 19 | if (n == 0) { 20 | System.out.printf("\nNo numbers supplied\n"); 21 | System.exit(1); 22 | } 23 | //n numbers are stored from num[0] to num[n-1] 24 | insertionSort(num, n); 25 | System.out.printf("\nThe sorted numbers are\n"); 26 | for (v = 0; v < n; v++) System.out.printf("%d ", num[v]); 27 | System.out.printf("\n"); 28 | } //end main 29 | 30 | public static void insertionSort(int list[], int n) { 31 | //sort list[0] to list[n-1] in ascending order 32 | for (int h = 1; h < n; h++) { 33 | int key = list[h]; 34 | int k = h - 1; //start comparing with previous item 35 | while (k >= 0 && key < list[k]) { 36 | list[k + 1] = list[k]; 37 | --k; 38 | } 39 | list[k + 1] = key; 40 | } //end for 41 | } //end insertionSort 42 | 43 | } //end class P1_2InsertSortTest 44 | -------------------------------------------------------------------------------- /P1_2aInsertSort1Test.java: -------------------------------------------------------------------------------- 1 | //Program P1.2a 2 | import java.util.*; 3 | public class P1_2aInsertSort1Test { 4 | final static int MaxNumbers = 10; 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | int[] num = new int[MaxNumbers]; 8 | System.out.printf("Type up to %d numbers followed by 0\n", MaxNumbers); 9 | int n = 0; 10 | int v = in.nextInt(); 11 | while (v != 0 && n < MaxNumbers) { 12 | num[n++] = v; 13 | v = in.nextInt(); 14 | } 15 | if (v != 0) { 16 | System.out.printf("\nMore than %d numbers entered\n", MaxNumbers); 17 | System.out.printf("First %d used\n", MaxNumbers); 18 | } 19 | if (n == 0) { 20 | System.out.printf("\nNo numbers supplied\n"); 21 | System.exit(1); 22 | } 23 | //n numbers are stored from num[0] to num[n-1] 24 | insertionSort1(num, 0, n-1); 25 | System.out.printf("\nThe sorted numbers are\n"); 26 | for (v = 0; v < n; v++) System.out.printf("%d ", num[v]); 27 | System.out.printf("\n"); 28 | } //end main 29 | 30 | public static void insertionSort1(int list[], int lo, int hi) { 31 | //sort list[lo] to list[hi] in ascending order 32 | for (int h = lo + 1; h <= hi; h++) { 33 | int key = list[h]; 34 | int k = h - 1; //start comparing with previous item 35 | while (k >= lo && key < list[k]) { 36 | list[k + 1] = list[k]; 37 | --k; 38 | } 39 | list[k + 1] = key; 40 | } //end for 41 | } //end insertionSort1 42 | 43 | } //end class P1_2aInsertSort1Test 44 | -------------------------------------------------------------------------------- /P1_2bInsertSort2Test.java: -------------------------------------------------------------------------------- 1 | //Program P1.2b 2 | import java.util.*; 3 | public class P1_2bInsertSort2Test { 4 | final static int MaxNumbers = 10; 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | int[] num = new int[MaxNumbers]; 8 | System.out.printf("Type up to %d numbers followed by 0\n", MaxNumbers); 9 | int n = 0; 10 | int v = in.nextInt(); 11 | while (v != 0 && n < MaxNumbers) { 12 | num[n++] = v; 13 | v = in.nextInt(); 14 | } 15 | if (v != 0) { 16 | System.out.printf("\nMore than %d numbers entered\n", MaxNumbers); 17 | System.out.printf("First %d used\n", MaxNumbers); 18 | } 19 | if (n == 0) { 20 | System.out.printf("\nNo numbers supplied\n"); 21 | System.exit(1); 22 | } 23 | //n numbers are stored from num[0] to num[n-1] 24 | insertionSort2(num, 0, n-1); 25 | System.out.printf("\nThe sorted numbers are\n"); 26 | for (v = 0; v < n; v++) System.out.printf("%d ", num[v]); 27 | System.out.printf("\n"); 28 | } //end main 29 | 30 | public static void insertionSort2(int list[], int lo, int hi) { 31 | //sort list[lo] to list[hi] in ascending order 32 | for (int h = lo + 1; h <= hi; h++) 33 | insertInPlace(list[h], list, lo, h - 1); 34 | } //end insertionSort2 35 | 36 | public static void insertInPlace(int newItem, int list[], int m, int n) { 37 | //list[m] to list[n] are sorted 38 | //insert newItem so that list[m] to list[n+1] are sorted 39 | int k = n; 40 | while (k >= m && newItem < list[k]) { 41 | list[k + 1] = list[k]; 42 | --k; 43 | } 44 | list[k + 1] = newItem; 45 | } //end insertInPlace 46 | 47 | } //end class P1_2bInsertSort2Test 48 | -------------------------------------------------------------------------------- /P1_3SortStrings.java: -------------------------------------------------------------------------------- 1 | //Program P1.3 2 | import java.util.*; 3 | public class P1_3SortStrings { 4 | final static int MaxNames = 8; 5 | public static void main(String[] args) { 6 | String name[] = {"Graham, Ariel", "Perrott, Chloe", 7 | "Charles, Kandice", "Seecharan, Anella", "Reyes, Aaliyah", 8 | "Graham, Ashleigh", "Reyes, Ayanna", "Greaves, Sherrelle" }; 9 | 10 | insertionSort3(name, 0, MaxNames - 1); 11 | 12 | System.out.printf("\nThe sorted names are\n\n"); 13 | for (int h = 0; h < MaxNames; h++) 14 | System.out.printf("%s\n", name[h]); 15 | } //end main 16 | 17 | public static void insertionSort3(String[] list, int lo, int hi) { 18 | //sort list[lo] to list[hi] in ascending order 19 | for (int h = lo + 1; h <= hi; h++) { 20 | String key = list[h]; 21 | int k = h - 1; //start comparing with previous item 22 | while (k >= lo && key.compareToIgnoreCase(list[k]) < 0) { 23 | list[k + 1] = list[k]; 24 | --k; 25 | } 26 | list[k + 1] = key; 27 | } //end for 28 | } //end insertionSort3 29 | 30 | } //end class P1_3SortStrings 31 | -------------------------------------------------------------------------------- /P1_4ParallelSort.java: -------------------------------------------------------------------------------- 1 | //Program P1.4 2 | import java.util.*; 3 | public class P1_4ParallelSort { 4 | final static int MaxNames = 8; 5 | public static void main(String[] args) { 6 | String name[] = {"Graham, Ariel", "Perrott, Chloe", 7 | "Charles, Kandice", "Seecharan, Anella", "Reyes, Aaliyah", 8 | "Graham, Ashleigh", "Reyes, Ayanna", "Greaves, Sherrelle" }; 9 | int id[] = {3050,2795,4455,7824,6669,5000,5464,6050}; 10 | 11 | parallelSort(name, id, 0, MaxNames - 1); 12 | 13 | System.out.printf("\nThe sorted names and IDs are\n\n"); 14 | for (int h = 0; h < MaxNames; h++) 15 | System.out.printf("%-20s %d\n", name[h], id[h]); 16 | } //end main 17 | 18 | public static void parallelSort(String[] list, int id[], int lo, int hi) { 19 | //Sort the names in list[lo] to list[hi] in alphabetical order, 20 | //ensuring that each name remains with its original id number. 21 | for (int h = lo + 1; h <= hi; h++) { 22 | String key = list[h]; 23 | int m = id[h]; // extract the id number 24 | int k = h - 1; //start comparing with previous item 25 | while (k >= lo && key.compareToIgnoreCase(list[k]) < 0) { 26 | list[k + 1] = list[k]; 27 | id[k+ 1] = id[k]; //move up id number when we move a name 28 | --k; 29 | } 30 | list[k + 1] = key; 31 | id[k + 1] = m; //store the id number in the same position as the name 32 | } //end for 33 | } //end parallelSort 34 | 35 | 36 | } //end class P1_4ParallelSort 37 | -------------------------------------------------------------------------------- /P1_5BinarySearchTest.java: -------------------------------------------------------------------------------- 1 | //Program P1.3 2 | 3 | import java.util.*; 4 | public class P1_5BinarySearchTest { 5 | public static void main(String[] args) { 6 | int[] num = {17, 24, 31, 39, 44, 49, 56, 66, 72, 78, 83, 89, 96}; 7 | int n = binarySearch(66, num, 0, 12); 8 | System.out.printf("%d\n", n); //will print 7; 66 in pos. 7 9 | n = binarySearch(66, num, 0, 6); 10 | System.out.printf("%d\n", n); //will print -1; 66 not in 0 to 6 11 | n = binarySearch(70, num, 0, 12); 12 | System.out.printf("%d\n", n); //will print -1; 70 not in list 13 | n = binarySearch(89, num, 5, 12); 14 | System.out.printf("%d\n", n); //will print 11; 89 in pos. 11 15 | } //end main 16 | 17 | public static int binarySearch(int key, int[] list, int lo, int hi) { 18 | //search for key from list[lo] to list[hi] 19 | //if found, return its location; otherwise, return -1 20 | while (lo <= hi) { 21 | int mid = (lo + hi) / 2; 22 | if (key == list[mid]) return mid; // found 23 | if (key < list[mid]) hi = mid - 1; 24 | else lo = mid + 1; 25 | } 26 | return -1; //lo and hi have crossed; key not found 27 | } 28 | 29 | } //end class P1_5BinarySearchTest 30 | -------------------------------------------------------------------------------- /P1_6BinarySearchString.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P1_6BinarySearchString.java -------------------------------------------------------------------------------- /P1_7WordFrequency.java: -------------------------------------------------------------------------------- 1 | // Program P1.7 2 | import java.io.*; 3 | import java.util.*; 4 | public class P1_7WordFrequency { 5 | final static int MaxWords = 50; 6 | public static void main(String[] args) throws IOException { 7 | String[] wordList = new String[MaxWords]; 8 | int[] frequency = new int[MaxWords]; 9 | FileReader in = new FileReader("passage.txt"); 10 | PrintWriter out = new PrintWriter(new FileWriter("output.txt")); 11 | 12 | for (int h = 0; h < MaxWords; h++) { 13 | frequency[h] = 0; 14 | wordList[h] = ""; 15 | } 16 | int numWords = 0; 17 | String word = getWord(in).toLowerCase(); 18 | while (!word.equals("")) { 19 | int loc = binarySearch(word, wordList, 0, numWords-1); 20 | if (word.compareTo(wordList[loc]) == 0) ++frequency[loc]; //word found 21 | else //this is a new word 22 | if (numWords < MaxWords) { //if table is not full 23 | addToList(word, wordList, frequency, loc, numWords-1); 24 | ++numWords; 25 | } 26 | else out.printf("'%s' not added to table\n", word); 27 | word = getWord(in).toLowerCase(); 28 | } 29 | printResults(out, wordList, frequency, numWords); 30 | in.close(); 31 | out.close(); 32 | } // end main 33 | 34 | public static int binarySearch(String key, String[] list, int lo, int hi){ 35 | //search for key from list[lo] to list[hi]; if found, return its location; 36 | //otherwise, return -lo if it must be inserted in location lo 37 | while (lo <= hi) { 38 | int mid = (lo + hi) / 2; 39 | int cmp = key.compareTo(list[mid]); 40 | if (cmp == 0) return mid; // search succeeds 41 | if (cmp < 0) hi = mid -1; // key is 'less than' list[mid] 42 | else lo = mid + 1; // key is 'greater than' list[mid] 43 | } 44 | return lo; //key must be inserted in location lo 45 | } //end binarySearch 46 | 47 | public static void addToList(String item, String[] list, int[] freq, int p, int n) { 48 | //adds item in position list[p]; sets freq[p] to 1 49 | //shifts list[n] down to list[p] to the right 50 | for (int h = n; h >= p; h--) { 51 | list[h + 1] = list[h]; 52 | freq[h + 1] = freq[h]; 53 | } 54 | list[p] = item; 55 | freq[p] = 1; 56 | } //end addToList 57 | 58 | public static void printResults(PrintWriter out, String[] list, int freq[], int n) { 59 | out.printf("\nWords Frequency\n\n"); 60 | for (int h = 0; h < n; h++) 61 | out.printf("%-20s %2d\n", list[h], freq[h]); 62 | } //end printResults 63 | 64 | public static String getWord(FileReader in) throws IOException { 65 | //returns the next word found 66 | final int MaxLen = 255; 67 | int c, n = 0; 68 | char[] word = new char[MaxLen]; 69 | // read over non-letters 70 | while (!Character.isLetter((char) (c = in.read())) && (c != -1)) ; 71 | //empty while body 72 | if (c == -1) return ""; //no letter found 73 | word[n++] = (char) c; 74 | while (Character.isLetter(c = in.read())) 75 | if (n < MaxLen) word[n++] = (char) c; 76 | return new String(word, 0, n); 77 | } // end getWord 78 | 79 | } //end class WordFrequency 80 | -------------------------------------------------------------------------------- /P1_7WordFrequency1.java: -------------------------------------------------------------------------------- 1 | // Program P1.7 2 | import java.io.*; 3 | import java.util.*; 4 | public class P1_7WordFrequency { 5 | final static int MaxWords = 50; 6 | public static void main(String[] args) throws IOException { 7 | String[] wordList = new String[MaxWords]; 8 | int[] frequency = new int[MaxWords]; 9 | 10 | 11 | try { 12 | FileReader in = new FileReader("passage.txt"); 13 | PrintWriter out = new PrintWriter(new FileWriter("output.txt")); 14 | for (int h = 0; h < MaxWords; h++) { 15 | frequency[h] = 0; 16 | wordList[h] = ""; 17 | 18 | int numWords = 0; 19 | String word = getWord(in).toLowerCase(); 20 | while (!word.equals("")) { 21 | int loc = binarySearch(word, wordList, 0, numWords-1); 22 | if (word.compareTo(wordList[loc]) == 0) ++frequency[loc]; //word found 23 | else //this is a new word 24 | if (numWords < MaxWords) { //if table is not full 25 | addToList(word, wordList, frequency, loc, numWords-1); 26 | ++numWords; 27 | } 28 | else out.printf("'%s' not added to table\n", word); 29 | word = getWord(in).toLowerCase(); 30 | } 31 | printResults(out, wordList, frequency, numWords); 32 | in.close(); 33 | out.close(); } 34 | } 35 | catch (FileNotFoundException e) { 36 | System.out.printf("%s\n", e); 37 | System.out.printf("Correct the problem and try again\n"); 38 | System.exit(1); 39 | } 40 | 41 | 42 | } //end main 43 | 44 | public static int binarySearch(String key, String[] list, int lo, int hi){ 45 | //search for key from list[lo] to list[hi]; if found, return its location; 46 | //otherwise, return -lo if it must be inserted in location lo 47 | while (lo <= hi) { 48 | int mid = (lo + hi) / 2; 49 | int cmp = key.compareToIgnoreCase(list[mid]); 50 | if (cmp == 0) return mid; // search succeeds 51 | if (cmp < 0) hi = mid -1; // key is 'less than' list[mid] 52 | else lo = mid + 1; // key is 'greater than' list[mid] 53 | } 54 | return lo; //key must be inserted in location lo 55 | } //end binarySearch 56 | 57 | public static void addToList(String item, String[] list, int[] freq, int p, int n) { 58 | //adds item in position list[p]; sets freq[p] to 1 59 | //shifts list[n] down to list[p] to the right 60 | for (int h = n; h >= p; h--) { 61 | list[h + 1] = list[h]; 62 | freq[h + 1] = freq[h]; 63 | } 64 | list[p] = item; 65 | freq[p] = 1; 66 | } //end addToList 67 | 68 | public static void printResults(PrintWriter out, String[] list, int freq[], int n) { 69 | out.printf("\nWords Frequency\n\n"); 70 | for (int h = 0; h < n; h++) 71 | out.printf("%-20s %2d\n", list[h], freq[h]); 72 | } //end printResults 73 | 74 | public static String getWord(FileReader in) throws IOException { 75 | //returns the next word found 76 | final int MaxLen = 255; 77 | int c, n = 0; 78 | char[] word = new char[MaxLen]; 79 | // read over non-letters 80 | while (!Character.isLetter((char) (c = in.read())) && (c != -1)) ; 81 | //empty while body 82 | if (c == -1) return ""; //no letter found 83 | word[n++] = (char) c; 84 | while (Character.isLetter(c = in.read())) 85 | if (n < MaxLen) word[n++] = (char) c; 86 | return new String(word, 0, n); 87 | } //end getWord 88 | 89 | } //end class P1_7WordFrequency 90 | -------------------------------------------------------------------------------- /P1_8MergeTest.java: -------------------------------------------------------------------------------- 1 | // Program P1.8 2 | public class P1_8MergeTest { 3 | public static void main(String[] args) { 4 | int[] A = {21, 28, 35, 40, 61, 75}; //size 6 5 | int[] B = {16, 25, 47, 54}; //size 4 6 | int[] C = new int[20]; //enough to hold all the elements 7 | int n = merge(A, 6, B, 4, C); 8 | for (int h = 0; h < n; h++) System.out.printf("%d ", C[h]); 9 | System.out.printf("\n"); 10 | } //end main 11 | 12 | public static int merge(int[] A, int m, int[] B, int n, int[] C) { 13 | int i = 0; //i points to the first (smallest) number in A 14 | int j = 0; //j points to the first (smallest) number in B 15 | int k = -1; //k will be incremented before storing a number in C[k] 16 | while (i < m && j < n) { 17 | if (A[i] < B[j]) C[++k] = A[i++]; 18 | else C[++k] = B[j++]; 19 | } 20 | if (i == m) ///copy B[j] to B[n-1] to C 21 | for ( ; j < n; j++) C[++k] = B[j]; 22 | else // j == n, copy A[i] to A[m-1] to C 23 | for ( ; i < m; i++) C[++k] = A[i]; 24 | return m + n; 25 | } //end merge 26 | 27 | } //end class P1_8MergeTest 28 | -------------------------------------------------------------------------------- /P1_8aMergeTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P1_8aMergeTest.class -------------------------------------------------------------------------------- /P1_8aMergeTest.java: -------------------------------------------------------------------------------- 1 | // Program P1.8 2 | public class P1_8aMergeTest { 3 | public static void main(String[] args) { 4 | int[] A = {21, 28, 35, 40, 61, 75}; //size 6 5 | int[] B = {16, 25, 47, 54}; //size 4 6 | int[] C = new int[20]; //enough to hold all the elements 7 | int n = merge(A, 6, B, 4, C); 8 | for (int h = 0; h < n; h++) System.out.printf("%d ", C[h]); 9 | System.out.printf("\n"); 10 | } //end main 11 | 12 | public static int merge(int[] A, int m, int[] B, int n, int[] C) { 13 | int i = 0; //i points to the first (smallest) number in A 14 | int j = 0; //j points to the first (smallest) number in B 15 | int k = -1; //k will be incremented before storing a number in C[k] 16 | while (i < m || j < n) { 17 | if (i == m) C[++k] = B[j++]; 18 | else if (j == n) C[++k] = A[i++]; 19 | else if (A[i] < B[j]) C[++k] = A[i++]; 20 | else C[++k] = B[j++]; 21 | } 22 | return m + n; 23 | } 24 | 25 | } //end class P1_8aMergeTest 26 | -------------------------------------------------------------------------------- /P2_1Sum.java: -------------------------------------------------------------------------------- 1 | // Program P2.1 2 | //prompt for two numbers and find their sum 3 | import java.util.*; 4 | public class P2_1Sum { 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | System.out.printf("Enter first number: "); 8 | int a = in.nextInt(); 9 | System.out.printf("Enter second number: "); 10 | int b = in.nextInt(); 11 | System.out.printf("%d + %d = %d\n", a, b, a + b); 12 | } //end main 13 | } //end class P2_1Sum 14 | -------------------------------------------------------------------------------- /P2_2PartTest.java: -------------------------------------------------------------------------------- 1 | //Program P2.2 2 | public class P2_2PartTest { 3 | // a program for testing the class Part 4 | 5 | public static void main(String[] args) { 6 | Part a, b, c; // declare 3 Part variables 7 | 8 | // create 3 Part objects 9 | a = new Part("Air Filter", 8.75); 10 | b = new Part("Ball Joint", 29.95); 11 | c = new Part("Headlamp", 199.99); // invalid price 12 | 13 | a.printPart(); // should print Air Filter, $8.75 14 | b.printPart(); // should print Ball Joint, $29.95 15 | c.printPart(); // should print Headlamp, $-1.0 16 | 17 | c.setPrice(36.99); 18 | c.printPart(); // should print Headlamp, $36.99 19 | 20 | // print the number of parts; should print 3 21 | System.out.printf("\nNumber of parts: %d\n", Part.GetNumParts()); 22 | } 23 | } //end class P2_2PartTest 24 | 25 | class Part { 26 | // class constants 27 | private static final double MinPrice = 0.0; 28 | private static final double MaxPrice = 99.99; 29 | private static final double NullPrice = -1.0; 30 | private static int NumParts = 0; // class variable 31 | 32 | private String name; // instance variable 33 | private double price; // instance variable 34 | 35 | public Part(String n, double p) { // constructor 36 | name = n; 37 | if (p < MinPrice || p > MaxPrice) { 38 | System.out.printf("Part: %s\n", name); 39 | System.out.printf("Invalid price: %3.2f; Set to %3.2f\n", p, NullPrice); 40 | price = NullPrice; 41 | } 42 | else price = p; 43 | NumParts++; 44 | } 45 | 46 | public static int GetNumParts() { // accessor 47 | return NumParts; 48 | } 49 | 50 | public String getName() { // accessor 51 | return name; 52 | } 53 | 54 | public double getPrice() { // accessor 55 | return price; 56 | } 57 | 58 | public void setPrice(double p) { // mutator 59 | if (p < MinPrice || p > MaxPrice) { 60 | System.out.printf("Part: %s\n", name); 61 | System.out.printf("Invalid price: %3.2f; Set to %3.2f\n", p, NullPrice); 62 | price = NullPrice; 63 | } 64 | else price = p; 65 | } 66 | 67 | public void printPart() { 68 | System.out.printf("\nName of part: %s\n", name); 69 | System.out.printf("Price: $%3.2f\n", price); 70 | } 71 | 72 | 73 | public String toString() { 74 | return "\nName of part: " + name + "\nPrice: $" + price + "\n"; 75 | } 76 | } //end class Part 77 | -------------------------------------------------------------------------------- /P2_3SearchTest.java: -------------------------------------------------------------------------------- 1 | // Program P2.3 2 | import java.util.*; 3 | public class P2_3SearchTest { 4 | public static void main(String[] args) { 5 | // set up an array with 7 persons 6 | Person[] person = new Person[7]; 7 | person[0] = new Person("Gary", 25, 'M'); 8 | person[1] = new Person("Inga", 21, 'F'); 9 | person[2] = new Person("Abel", 30, 'M'); 10 | person[3] = new Person("Olga", 36, 'F'); 11 | person[4] = new Person("Nora", 19, 'F'); 12 | person[5] = new Person("Mary", 27, 'F'); 13 | person[6] = new Person("Bert", 32, 'M'); 14 | 15 | Scanner in = new Scanner(System.in); 16 | String s; 17 | System.out.printf("Enter names, one at a time, and I'll tell you\n"); 18 | System.out.printf("their age and gender. To end, press Enter\n\n"); 19 | while (!(s = in.nextLine()).equals("")) { 20 | int n = sequentialSearch(s, person, person.length); 21 | if (n >= 0) 22 | System.out.printf("%d %c\n\n", person[n].age, person[n].gender); 23 | else System.out.printf("Not found\n\n"); 24 | } 25 | }//end main 26 | 27 | // search for key in the first n elements of the array person ; 28 | // if found, return the position, else return -1 29 | public static int sequentialSearch(String key, Person[] person, int n) { 30 | for (int h = 0; h < n; h++) 31 | if (key.equalsIgnoreCase(person[h].name)) return h; 32 | return -1; 33 | } //end of sequentialSearch 34 | 35 | } //end class P2_3SearchTest 36 | 37 | class Person { 38 | String name; 39 | int age; 40 | char gender; 41 | Person(String n, int a, char g) { 42 | name = n; 43 | age = a; 44 | gender = g; 45 | } 46 | } //end class Person 47 | -------------------------------------------------------------------------------- /P2_4WordFrequency.java: -------------------------------------------------------------------------------- 1 | //Program P2.4 2 | 3 | import java.io.*; 4 | import java.util.*; 5 | public class P2_4WordFrequency { 6 | final static int MaxWords = 50; 7 | 8 | public static void main(String[] args) throws IOException { 9 | WordInfo[] wordTable = new WordInfo[MaxWords]; 10 | 11 | FileReader in = new FileReader("passage.txt"); 12 | PrintWriter out = new PrintWriter(new FileWriter("output.txt")); 13 | 14 | for (int h = 0; h < MaxWords; h++) wordTable[h] = new WordInfo("", 0); 15 | int numWords = 0; 16 | 17 | String word = getWord(in).toLowerCase(); 18 | while (!word.equals("")) { 19 | int loc = binarySearch(word, wordTable, 0, numWords-1); 20 | if (word.compareTo(wordTable[loc].word) == 0) wordTable[loc].incrFreq(); 21 | else //this is a new word 22 | if (numWords < MaxWords) { //if table is not full 23 | addToList(word, wordTable, loc, numWords-1); 24 | ++numWords; 25 | } 26 | else out.printf("'%s' not added to table\n", word); 27 | word = getWord(in).toLowerCase(); 28 | } 29 | 30 | printResults(out, wordTable, numWords); 31 | in.close(); 32 | out.close(); 33 | } //end main 34 | 35 | public static int binarySearch(String key, WordInfo[] list, int lo, int hi) { 36 | //search for key from list[lo] to list[hi] 37 | //if found, return its location; 38 | //if not found, return the location in which it should be inserted 39 | //the calling program will check the location to determine if found 40 | while (lo <= hi) { 41 | int mid = (lo + hi) / 2; 42 | int cmp = key.compareToIgnoreCase(list[mid].word); 43 | if (cmp == 0) return mid; // search succeeds 44 | if (cmp < 0) hi = mid -1; // key is 'less than' list[mid].word 45 | else lo = mid + 1; // key is 'greater than' list[mid].word 46 | } 47 | return lo; //key must be inserted in location lo 48 | } //end binarySearch 49 | 50 | public static void addToList(String item, WordInfo[] list, int p, int n) { 51 | //sets list[p].word to item; sets list[p].freq to 1 52 | //shifts list[n] down to list[p] to the right 53 | for (int h = n; h >= p; h--) list[h + 1] = list[h]; 54 | list[p] = new WordInfo(item, 1); 55 | } //end addToList 56 | 57 | public static void printResults(PrintWriter out, WordInfo[] list, int n) { 58 | out.printf("\nWords Frequency\n\n"); 59 | for (int h = 0; h < n; h++) 60 | out.printf("%-20s %2d\n", list[h].word, list[h].freq); 61 | } //end printResults 62 | 63 | public static String getWord(FileReader in) throws IOException { 64 | //returns the next word found 65 | final int MaxLen = 255; 66 | int c, n = 0; 67 | char[] word = new char[MaxLen]; 68 | // read over non-letters 69 | while (!Character.isLetter((char) (c = in.read())) && (c != -1)) ; 70 | //empty while body 71 | if (c == -1) return ""; //no letter found 72 | 73 | word[n++] = (char) c; 74 | while (Character.isLetter(c = in.read())) 75 | if (n < MaxLen) word[n++] = (char) c; 76 | return new String(word, 0, n); 77 | } //end getWord 78 | 79 | } //end class P2_4WordFrequency 80 | 81 | class WordInfo { 82 | String word; 83 | int freq = 0; 84 | 85 | WordInfo(String w, int f) { 86 | word = w; 87 | freq = f; 88 | } 89 | 90 | void incrFreq() { 91 | freq++; 92 | } 93 | } //end class WordInfo 94 | -------------------------------------------------------------------------------- /P2_5Voting.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P2_5Voting.class -------------------------------------------------------------------------------- /P2_5Voting.java: -------------------------------------------------------------------------------- 1 | //Program P2.5 2 | import java.util.*; 3 | import java.io.*; 4 | public class P2_5Voting { 5 | final static int MaxCandidates = 7; 6 | 7 | public static void main(String[] args) throws IOException { 8 | Scanner in = new Scanner(new FileReader("votes.txt")); 9 | PrintWriter out = new PrintWriter(new FileWriter("results.txt")); 10 | Person[] candidate = new Person[MaxCandidates+1]; 11 | 12 | //get the names and set the scores to 0 13 | for (int h = 1; h <= MaxCandidates; h++) 14 | candidate[h] = new Person(in.nextLine(), 0); 15 | 16 | VoteCount count = processVotes(candidate, MaxCandidates, in, out); 17 | printResults(out, candidate, MaxCandidates, count); 18 | in.close(); 19 | out.close(); 20 | } //end main 21 | 22 | public static VoteCount processVotes(Person[] list, int max, Scanner in, PrintWriter out) { 23 | VoteCount votes = new VoteCount(0, 0); //set valid, spoilt counts to 0 24 | int v = in.nextInt(); 25 | while (v != 0) { 26 | if (v < 1 || v > max) { 27 | out.printf("Invalid vote: %d\n", v); 28 | ++votes.spoilt; 29 | } 30 | else { 31 | ++list[v].numVotes; 32 | ++votes.valid; 33 | } 34 | v = in.nextInt(); 35 | } //end while 36 | return votes; 37 | } //end processVotes 38 | 39 | public static void printResults(PrintWriter out, Person[] list, 40 | int max, VoteCount votes) { 41 | out.printf("\nNumber of voters: %d\n", votes.valid + votes.spoilt); 42 | out.printf("Number of valid votes: %d\n", votes.valid); 43 | out.printf("Number of spoilt votes: %d\n", votes.spoilt); 44 | out.printf("\nCandidate Score\n\n"); 45 | 46 | for (int h = 1; h <= MaxCandidates; h++) 47 | out.printf("%-18s %3d\n", list[h].name, list[h].numVotes); 48 | 49 | out.printf("\nThe winner(s)\n"); 50 | int win = getLargest(list, 1, MaxCandidates); 51 | int winningVote = list[win].numVotes; 52 | for (int h = 1; h <= MaxCandidates; h++) 53 | if (list[h].numVotes == winningVote) out.printf(" %s\n", list[h].name); 54 | } //end printResults 55 | 56 | public static int getLargest(Person[] list, int lo, int hi) { 57 | int big = lo; 58 | for (int h = lo + 1; h <= hi; h++) 59 | if (list[h].numVotes > list[big].numVotes) big = h; 60 | return big; 61 | } //end getLargest 62 | } //end class P2_5Voting 63 | 64 | class Person { 65 | String name; 66 | int numVotes; 67 | 68 | Person(String s, int n) { 69 | name = s; 70 | numVotes = n; 71 | } 72 | } //end class Person 73 | 74 | class VoteCount { 75 | int valid, spoilt; 76 | 77 | VoteCount(int v, int s) { 78 | valid = v; 79 | spoilt = s; 80 | } 81 | } //end class VoteCount 82 | -------------------------------------------------------------------------------- /P2_5aVoting.java: -------------------------------------------------------------------------------- 1 | //Program P2.5 2 | import java.util.*; 3 | import java.io.*; 4 | public class P2_5aVoting { 5 | final static int MaxCandidates = 7; 6 | 7 | public static void main(String[] args) throws IOException { 8 | Scanner in = new Scanner(new FileReader("votes.txt")); 9 | PrintWriter out = new PrintWriter(new FileWriter("results.txt")); 10 | Person[] candidate = new Person[MaxCandidates+1]; 11 | 12 | //get the names and set the scores to 0 13 | for (int h = 1; h <= MaxCandidates; h++) 14 | candidate[h] = new Person(in.nextLine(), 0); 15 | 16 | VoteCount count = processVotes(candidate, MaxCandidates, in, out); 17 | sortByVote(candidate, 1, MaxCandidates); 18 | printResults(out, candidate, MaxCandidates, count); 19 | in.close(); 20 | out.close(); 21 | } //end main 22 | 23 | public static VoteCount processVotes(Person[] list, int max, Scanner in, PrintWriter out) { 24 | VoteCount votes = new VoteCount(0, 0); //set valid, spoilt counts to 0 25 | int v = in.nextInt(); 26 | while (v != 0) { 27 | if (v < 1 || v > max) { 28 | out.printf("Invalid vote: %d\n", v); 29 | ++votes.spoilt; 30 | } 31 | else { 32 | ++list[v].numVotes; 33 | ++votes.valid; 34 | } 35 | v = in.nextInt(); 36 | } //end while 37 | return votes; 38 | } //end processVotes 39 | 40 | public static void printResults(PrintWriter out, Person[] list, 41 | int max, VoteCount votes) { 42 | out.printf("\nNumber of voters: %d\n", votes.valid + votes.spoilt); 43 | out.printf("Number of valid votes: %d\n", votes.valid); 44 | out.printf("Number of spoilt votes: %d\n", votes.spoilt); 45 | out.printf("\nCandidate Score\n\n"); 46 | 47 | for (int h = 1; h <= MaxCandidates; h++) 48 | out.printf("%-18s %3d\n", list[h].name, list[h].numVotes); 49 | 50 | out.printf("\nThe winner(s)\n"); 51 | int win = getLargest(list, 1, MaxCandidates); 52 | int winningVote = list[win].numVotes; 53 | for (int h = 1; h <= MaxCandidates; h++) 54 | if (list[h].numVotes == winningVote) out.printf(" %s\n", list[h].name); 55 | } //end printResults 56 | 57 | public static void sortByVote(Person[] list, int lo, int hi) { 58 | //sort list[lo] to list[hi] in descending order by numVotes 59 | for (int h = lo + 1; h <= hi; h++) { 60 | Person hold = list[h]; 61 | int k = h - 1; //start comparing with previous item 62 | while (k >= lo && hold.numVotes > list[k].numVotes) { 63 | list[k + 1] = list[k]; 64 | --k; 65 | } 66 | list[k + 1] = hold; 67 | } //end for 68 | } //end sortByVote 69 | 70 | public static int getLargest(Person[] list, int lo, int hi) { 71 | int big = lo; 72 | for (int h = lo + 1; h <= hi; h++) 73 | if (list[h].numVotes > list[big].numVotes) big = h; 74 | return big; 75 | } //end getLargest 76 | } //end class P2_5aVoting 77 | 78 | class Person { 79 | String name; 80 | int numVotes; 81 | 82 | Person(String s, int n) { 83 | name = s; 84 | numVotes = n; 85 | } 86 | } //end class Person 87 | 88 | class VoteCount { 89 | int valid, spoilt; 90 | 91 | VoteCount(int v, int s) { 92 | valid = v; 93 | spoilt = s; 94 | } 95 | } //end class VoteCount 96 | -------------------------------------------------------------------------------- /P3_1BuildList1.java: -------------------------------------------------------------------------------- 1 | //Program P3.1 2 | import java.util.*; 3 | public class P3_1BuildList1 { 4 | 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | Node top, np, last = null; 8 | 9 | top = null; 10 | System.out.printf("Enter some integers ending with 0\n"); 11 | int n = in.nextInt(); 12 | while (n != 0) { 13 | np = new Node(n); //create a new node containing n 14 | if (top == null) top = np; //set top if first node 15 | else last.next = np; //set last.next for other nodes 16 | last = np; //update last to new node 17 | n = in.nextInt(); 18 | } 19 | System.out.printf("\nThe items in the list are\n"); 20 | printList(top); 21 | } //end main 22 | 23 | public static void printList(Node top) { 24 | while (top != null) { //as long as there's a node 25 | System.out.printf("%d ", top.num); 26 | top = top.next; //go on to the next node 27 | } 28 | System.out.printf("\n"); 29 | } //end printList 30 | 31 | } //end class P3_1BuildList1 32 | 33 | class Node { 34 | int num; 35 | Node next; 36 | 37 | public Node(int n) { 38 | num = n; 39 | next = null; 40 | } 41 | } //end class Node 42 | -------------------------------------------------------------------------------- /P3_2BuildList2.java: -------------------------------------------------------------------------------- 1 | //Program P3.2 2 | import java.util.*; 3 | public class P3_2BuildList2 { 4 | 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | Node top, np, last = null; 8 | 9 | top = null; 10 | System.out.printf("Enter some integers ending with 0\n"); 11 | int n = in.nextInt(); 12 | while (n != 0) { 13 | np = new Node(n); //create a new node containing n 14 | np.next = top; //set it to point to first node 15 | top = np; //update top to point to new node 16 | n = in.nextInt(); 17 | } 18 | System.out.printf("\nThe items in the list are\n"); 19 | printList(top); 20 | } //end main 21 | 22 | public static void printList(Node top) { 23 | while (top != null) { //as long as there's a node 24 | System.out.printf("%d ", top.num); 25 | top = top.next; //go on to the next node 26 | } 27 | System.out.printf("\n"); 28 | } //end printList 29 | 30 | } //end class P3_2BuildList2 31 | 32 | class Node { 33 | int num; 34 | Node next; 35 | 36 | public Node(int n) { 37 | num = n; 38 | next = null; 39 | } 40 | } //end class Node 41 | -------------------------------------------------------------------------------- /P3_3BuildList3.java: -------------------------------------------------------------------------------- 1 | // Program P3.3 2 | import java.util.*; 3 | public class P3_3BuildList3 { 4 | 5 | public static void main(String[] args) { 6 | Scanner in = new Scanner(System.in); 7 | Node top, np, last = null; 8 | 9 | top = null; 10 | System.out.printf("Enter some integers ending with 0\n"); 11 | int n = in.nextInt(); 12 | while (n != 0) { 13 | top = addInPlace(top, n); 14 | n = in.nextInt(); 15 | } 16 | printList(top); 17 | } //end main 18 | 19 | public static Node addInPlace(Node top, int n) { 20 | // This functions inserts n in its ordered position in a (possibly empty) 21 | // list pointed to by top, and returns a pointer to the new list 22 | Node np, curr, prev; 23 | 24 | np = new Node(n); 25 | prev = null; 26 | curr = top; 27 | while (curr != null && n > curr.num) { 28 | prev = curr; 29 | curr = curr.next; 30 | } 31 | np.next = curr; 32 | if (prev == null) return np; //top of list is now the new node 33 | prev.next = np; 34 | return top; //the top of the list has not changed 35 | } //end addInPlace 36 | 37 | public static void printList(Node top) { 38 | while (top != null) { //as long as there's a node 39 | System.out.printf("%d ", top.num); 40 | top = top.next; //go on to the next node 41 | } 42 | System.out.printf("\n"); 43 | } //end printList 44 | 45 | } //end class P3_3BuildList3 46 | 47 | class Node { 48 | int num; 49 | Node next; 50 | 51 | public Node(int n) { 52 | num = n; 53 | next = null; 54 | } 55 | } //end class Node 56 | -------------------------------------------------------------------------------- /P3_4LinkedListTest.java: -------------------------------------------------------------------------------- 1 | // Program P3.4 2 | import java.util.*; 3 | public class P3_4LinkedListTest { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | LinkedList LL = new LinkedList(); 7 | System.out.printf("Enter some integers ending with 0\n"); 8 | int n = in.nextInt(); 9 | while (n != 0) { 10 | LL.addInPlace(new NodeData(n)); 11 | n = in.nextInt(); 12 | } 13 | LL.printList(); 14 | } //end main 15 | } //end P3_4LinkedListTest 16 | 17 | class NodeData { 18 | int num; 19 | 20 | public NodeData(int n) { 21 | num = n; 22 | } 23 | 24 | public int compareTo(NodeData nd) { 25 | if (this.num == nd.num) return 0; 26 | if (this.num < nd.num) return -1; 27 | return 1; 28 | } //end compareTo 29 | 30 | public String toString() { 31 | return num + " "; 32 | //" " needed to convert num to a string; may also use "" (empty string) 33 | } 34 | } //end class NodeData 35 | 36 | class Node { 37 | NodeData data; 38 | Node next; 39 | 40 | public Node(NodeData nd) { 41 | data = nd; 42 | next = null; 43 | } 44 | } //end class Node 45 | 46 | class LinkedList { 47 | Node head = null; 48 | 49 | public boolean empty() { 50 | return head == null; 51 | } 52 | 53 | public void addHead(NodeData nd) { 54 | Node p = new Node(nd); 55 | p.next = head; 56 | head = p; 57 | } 58 | 59 | public void addInPlace(NodeData nd) { 60 | Node np, curr, prev; 61 | 62 | np = new Node(nd); 63 | prev = null; 64 | curr = head; 65 | while (curr != null && nd.compareTo(curr.data) > 0) { //new value is bigger 66 | prev = curr; 67 | curr = curr.next; 68 | } 69 | np.next = curr; 70 | if (prev == null) head = np; 71 | else prev.next = np; 72 | } //end addInPlace 73 | 74 | public void printList() { 75 | Node curr = head; 76 | while (curr != null) { 77 | System.out.printf("%s", curr.data); //invokes curr.data.toString() 78 | curr = curr.next; 79 | } 80 | System.out.printf("\n"); 81 | } //end printList 82 | 83 | } //end class LinkedList 84 | -------------------------------------------------------------------------------- /P3_5Palindrome.java: -------------------------------------------------------------------------------- 1 | // Program P3.5 2 | import java.util.*; 3 | public class P3_5Palindrome { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | System.out.printf("Type a phrase. (To stop, press 'Enter' only): "); 7 | LinkedList aPhrase = getPhrase(in); 8 | while (!aPhrase.empty()) { 9 | LinkedList w1 = lettersLower(aPhrase); 10 | System.out.printf("Converted to: "); 11 | w1.printList(); 12 | LinkedList w2 = w1.copyList(); 13 | w2.reverseList(); 14 | if (w1.equals(w2)) System.out.printf("is a palindrome\n"); 15 | else System.out.printf("is not a palindrome\n"); 16 | System.out.printf("Type a phrase. (To stop, press 'Enter' only): "); 17 | aPhrase = getPhrase(in); 18 | } 19 | } //end main 20 | 21 | public static LinkedList getPhrase(Scanner in) { 22 | LinkedList phrase = new LinkedList(); 23 | String str = in.nextLine(); 24 | for (int h = str.length() - 1; h >= 0; h--) 25 | phrase.addHead(new NodeData(str.charAt(h))); 26 | return phrase; 27 | } 28 | 29 | public static LinkedList lettersLower(LinkedList phrase) { 30 | LinkedList word = new LinkedList(); 31 | 32 | while (!phrase.empty()) { 33 | char ch = phrase.getHeadData().getData(); 34 | if (Character.isLetter(ch)) word.addTail(new NodeData(Character.toLowerCase(ch))); 35 | phrase.deleteHead(); 36 | } 37 | return word; 38 | } 39 | 40 | } //end class P3_5Palindrome 41 | -------------------------------------------------------------------------------- /P3_6MergeLists.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P3_6MergeLists.class -------------------------------------------------------------------------------- /P3_6MergeLists.java: -------------------------------------------------------------------------------- 1 | // Program P3.6 2 | import java.util.*; 3 | public class P3_6MergeLists { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | LinkedList A = createSortedList(in); 7 | LinkedList B = createSortedList(in); 8 | System.out.printf("\nWhen we merge\n"); 9 | A.printList(); 10 | System.out.printf("with\n"); 11 | B.printList(); 12 | System.out.printf("we get\n"); 13 | A.merge(B).printList(); 14 | } //end main 15 | 16 | public static LinkedList createSortedList(Scanner in) { 17 | LinkedList LL = new LinkedList(); 18 | System.out.printf("Enter some integers ending with 0\n"); 19 | int n = in.nextInt(); 20 | while (n != 0) { 21 | LL.addInPlace(new NodeData(n)); 22 | n = in.nextInt(); 23 | } 24 | return LL; 25 | } //end createSortedList 26 | 27 | } //end P3_6MergeLists 28 | -------------------------------------------------------------------------------- /P3_7CountOut.java: -------------------------------------------------------------------------------- 1 | // Program P3.7 2 | import java.util.*; 3 | public class P3_7CountOut { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | int m, n; 7 | do { 8 | System.out.printf("Enter number of children and length of count-out: "); 9 | n = in.nextInt(); 10 | m = in.nextInt(); 11 | } while (n < 1 || m < 1); 12 | 13 | Node last = linkCircular(n); //link children in a circular list 14 | Node winner = playGame(last, n-1, m); //eliminate n-1 children 15 | System.out.printf("The winning child: %d\n", winner.num); 16 | } //end main 17 | 18 | public static Node linkCircular(int n) { 19 | //link n children in a circular list; 20 | //return pointer to last child; this will point to the first 21 | Node first, np; 22 | 23 | first = np = new Node(1); //first child 24 | for (int h = 2; h <= n; h++) { //link the others 25 | np.next = new Node(h); 26 | np = np.next; 27 | } 28 | np.next = first; //set last child to point to first 29 | return np; 30 | } //end linkCircular 31 | 32 | public static Node playGame(Node last, int x, int m) { 33 | //Eliminate x children with countout length of m; 34 | //last points to the last child which points to the first child 35 | Node prev = last, curr = last.next; //curr points to first child 36 | //eliminate x children 37 | for (int h = 1; h <= x; h++) { 38 | //curr is pointing at the first child to be counted; 39 | //count m-1 more to get to the mth child 40 | for (int c = 1; c < m; c++) { 41 | prev = curr; 42 | curr = curr.next; 43 | } 44 | //delete the mth child 45 | prev.next = curr.next; 46 | curr = prev.next; //set curr to the child after the one eliminated 47 | } 48 | return curr; 49 | } //end playGame 50 | 51 | } //end class P3_7CountOut 52 | 53 | class Node { 54 | int num; 55 | Node next; 56 | 57 | public Node(int n) { 58 | num = n; 59 | next = null; 60 | } 61 | } //end class Node 62 | -------------------------------------------------------------------------------- /P4_1StackTest.java: -------------------------------------------------------------------------------- 1 | //Program P4.1 2 | import java.util.*; 3 | public class P4_1StackTest { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | Stack S = new Stack(); 7 | System.out.printf("Enter some integers ending with 0\n"); 8 | int n = in.nextInt(); 9 | while (n != 0) { 10 | S.push(n); 11 | n = in.nextInt(); 12 | } 13 | System.out.printf("\nNumbers in reverse order\n"); 14 | while (!S.empty()) 15 | System.out.printf("%d ", S.pop()); 16 | System.out.printf("\n"); 17 | } //end main 18 | } //end P4_1StackTest 19 | 20 | class Stack { 21 | final static int MaxStack = 100; 22 | final static int RogueValue = -999999; 23 | int top = -1; 24 | int[] ST = new int[MaxStack]; 25 | 26 | public boolean empty() { 27 | return top == -1; 28 | } 29 | 30 | public void push(int n) { 31 | if (top == MaxStack - 1) { 32 | System.out.printf("\nStack Overflow\n"); 33 | System.exit(1); 34 | } 35 | ++top; 36 | ST[top] = n; 37 | } //end push 38 | 39 | public int pop() { 40 | if (this.empty())return RogueValue; //a symbolic constant 41 | int hold = ST[top]; 42 | --top; 43 | return hold; 44 | } 45 | 46 | } //end class Stack 47 | -------------------------------------------------------------------------------- /P4_2StackTest.java: -------------------------------------------------------------------------------- 1 | //Program P4.2 2 | import java.util.*; 3 | public class P4_2StackTest { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | Stack S = new Stack(); 7 | System.out.printf("Enter some integers ending with 0\n"); 8 | int n = in.nextInt(); 9 | while (n != 0) { 10 | S.push(n); 11 | n = in.nextInt(); 12 | } 13 | System.out.printf("\nNumbers in reverse order\n"); 14 | while (!S.empty()) 15 | System.out.printf("%d ", S.pop()); 16 | System.out.printf("\n"); 17 | } //end main 18 | } //end P4_2StackTest 19 | 20 | class Node { 21 | int data; 22 | Node next; 23 | 24 | public Node(int d) { 25 | data = d; 26 | next = null; 27 | } 28 | } //end class Node 29 | 30 | class Stack { 31 | final static int RogueValue = -999999; 32 | Node top = null; 33 | 34 | public boolean empty() { 35 | return top == null; 36 | } 37 | 38 | public void push(int n) { 39 | Node p = new Node(n); 40 | p.next = top; 41 | top = p; 42 | } //end push 43 | 44 | public int pop() { 45 | if (this.empty()) return RogueValue; //a symbolic constant 46 | int hold = top.data; 47 | top = top.next; 48 | return hold; 49 | } //end pop 50 | 51 | } //end class Stack 52 | -------------------------------------------------------------------------------- /P4_3StackTest.java: -------------------------------------------------------------------------------- 1 | // Program P4.3 2 | import java.util.*; 3 | public class P4_3StackTest { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | Stack S = new Stack(); 7 | System.out.printf("Enter some integers ending with 0\n"); 8 | int n = in.nextInt(); 9 | while (n != 0) { 10 | S.push(new NodeData(n)); 11 | n = in.nextInt(); 12 | } 13 | System.out.printf("\nNumbers in reverse order\n"); 14 | while (!S.empty()) 15 | System.out.printf("%d ", S.pop().getData()); 16 | System.out.printf("\n"); 17 | } //end main 18 | } //end P4_3StackTest 19 | 20 | class NodeData { 21 | int num; 22 | 23 | public NodeData(int n) { 24 | num = n; 25 | } 26 | 27 | public int getData() {return num;} 28 | 29 | public static NodeData getRogueValue() {return new NodeData(-999999);} 30 | 31 | } //end class NodeData 32 | 33 | class Node { 34 | NodeData data; 35 | Node next; 36 | 37 | public Node(NodeData d) { 38 | data = d; 39 | next = null; 40 | } 41 | } //end class Node 42 | 43 | class Stack { 44 | Node top = null; 45 | 46 | public boolean empty() { 47 | return top == null; 48 | } 49 | 50 | public void push(NodeData nd) { 51 | Node p = new Node(nd); 52 | p.next = top; 53 | top = p; 54 | } //end push 55 | 56 | public NodeData pop() { 57 | if (this.empty())return NodeData.getRogueValue(); 58 | NodeData hold = top.data; 59 | top = top.next; 60 | return hold; 61 | } //end pop 62 | 63 | } //end class Stack 64 | 65 | -------------------------------------------------------------------------------- /P4_4DecimalToBinary.java: -------------------------------------------------------------------------------- 1 | // Program P4.4 2 | import java.util.*; 3 | public class P4_4DecimalToBinary { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | Stack S = new Stack(); 7 | System.out.printf("Enter a positive integer: "); 8 | int n = in.nextInt(); 9 | while (n > 0) { 10 | S.push(new NodeData(n % 2)); 11 | n = n / 2; 12 | } 13 | System.out.printf("\nIts binary equivalent is "); 14 | while (!S.empty()) 15 | System.out.printf("%d", S.pop().getData()); 16 | System.out.printf("\n"); 17 | } //end main 18 | } //end class P4_4DecimalToBinary 19 | 20 | class NodeData { 21 | int num; 22 | 23 | public NodeData(int n) { 24 | num = n; 25 | } 26 | 27 | public int getData() {return num;} 28 | 29 | public static NodeData getRogueValue() {return new NodeData(-999999);} 30 | 31 | } //end class NodeData 32 | 33 | class Node { 34 | NodeData data; 35 | Node next; 36 | 37 | public Node(NodeData d) { 38 | data = d; 39 | next = null; 40 | } 41 | } //end class Node 42 | 43 | class Stack { 44 | Node top = null; 45 | 46 | public boolean empty() { 47 | return top == null; 48 | } 49 | 50 | public void push(NodeData nd) { 51 | Node p = new Node(nd); 52 | p.next = top; 53 | top = p; 54 | } //end push 55 | 56 | public NodeData pop() { 57 | if (this.empty())return NodeData.getRogueValue(); 58 | NodeData hold = top.data; 59 | top = top.next; 60 | return hold; 61 | } //end pop 62 | 63 | } //end class Stack 64 | -------------------------------------------------------------------------------- /P4_5InfixToPostfix.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P4_5InfixToPostfix.class -------------------------------------------------------------------------------- /P4_5InfixToPostfix.java: -------------------------------------------------------------------------------- 1 | //Program P4.5 2 | import java.io.*; 3 | public class P4_5InfixToPostfix { 4 | public static void main(String[] args) throws IOException { 5 | char[] post = new char[255]; 6 | int n = readConvert(post); 7 | printPostfix(post, n); 8 | } //end main 9 | 10 | public static int readConvert(char[] post) throws IOException { 11 | //Read the expression and convert to postfix. Return the size of postfix. 12 | Stack S = new Stack(); 13 | int h = 0; 14 | char c; 15 | System.out.printf("Type an infix expression and press Enter\n"); 16 | char token = getToken(); 17 | while (token != '\0') { 18 | if (Character.isDigit(token)) post[h++] = token; 19 | else if (token == '(') S.push(new NodeData('(')); 20 | else if (token == ')') 21 | while ((c = S.pop().getData()) != '(') post[h++] = c; 22 | else { 23 | while (!S.empty() && 24 | precedence(S.peek().getData()) >= precedence(token)) 25 | post[h++] = S.pop().getData(); 26 | S.push(new NodeData(token)); 27 | } 28 | token = getToken(); 29 | } 30 | while (!S.empty()) post[h++] = S.pop().getData(); 31 | return h; 32 | } //end readConvert 33 | 34 | public static void printPostfix(char[] post, int n) { 35 | System.out.printf("\nThe postfix form is \n"); 36 | for (int h = 0; h < n; h++) System.out.printf("%c ", post[h]); 37 | System.out.printf("\n"); 38 | } //end printPostfix 39 | 40 | public static char getToken() throws IOException { 41 | int n; 42 | while ((n = System.in.read()) == ' ') ; //read over blanks 43 | if (n == '\r') return '\0'; 44 | return (char) n; 45 | } //end getToken 46 | 47 | public static int precedence(char c) { 48 | //Returns the precedence of the given operator 49 | if (c == '(') return 0; 50 | if (c == '+' || c == '-') return 3; 51 | if (c == '*' || c == '/') return 5; 52 | return -99; //error 53 | } //end precedence 54 | 55 | } //end class P4_5InfixToPostfix 56 | 57 | class NodeData { 58 | char ch; 59 | 60 | public NodeData(char c) { 61 | ch = c; 62 | } 63 | 64 | public char getData() {return ch;} 65 | 66 | public static NodeData getRogueValue() {return new NodeData('$');} 67 | 68 | public int compareTo(NodeData nd) { 69 | if (this.ch == nd.ch) return 0; 70 | if (this.ch < nd.ch) return -1; 71 | return 1; 72 | } 73 | 74 | public String toString() { 75 | return ch + ""; 76 | } 77 | } //end class NodeData 78 | 79 | class Node { 80 | NodeData data; 81 | Node next; 82 | 83 | public Node(NodeData d) { 84 | data = d; 85 | next = null; 86 | } 87 | } //end class Node 88 | 89 | class Stack { 90 | Node top = null; 91 | 92 | public boolean empty() { 93 | return top == null; 94 | } 95 | 96 | public void push(NodeData nd) { 97 | Node p = new Node(nd); 98 | p.next = top; 99 | top = p; 100 | } //end push 101 | 102 | public NodeData pop() { 103 | if (this.empty())return NodeData.getRogueValue(); 104 | NodeData hold = top.data; 105 | top = top.next; 106 | return hold; 107 | } //end pop 108 | 109 | public NodeData peek() { 110 | if (!this.empty()) return top.data; 111 | return null; 112 | } //end peek 113 | 114 | } //end class Stack 115 | -------------------------------------------------------------------------------- /P4_6EvalExpression.java: -------------------------------------------------------------------------------- 1 | //Program P4.6 2 | import java.io.*; 3 | public class P4_6EvalExpression { 4 | public static void main(String[] args) throws IOException { 5 | char[] post = new char[255]; 6 | int n = readConvert(post); 7 | printPostfix(post, n); 8 | System.out.printf("\nIts value is %d\n", eval(post, n)); 9 | } //end main 10 | 11 | public static int readConvert(char[] post) throws IOException { 12 | //Read the expression and convert to postfix. Return the size of postfix. 13 | Stack S = new Stack(); 14 | int h = 0; 15 | char c; 16 | System.out.printf("Type an infix expression and press Enter\n"); 17 | char token = getToken(); 18 | while (token != '\0') { 19 | if (Character.isDigit(token)) post[h++] = token; 20 | else if (token == '(') S.push(new NodeData('(')); 21 | else if (token == ')') 22 | while ((c = S.pop().getCharData()) != '(') post[h++] = c; 23 | else { 24 | while (!S.empty() && 25 | precedence(S.peek().getCharData()) >= precedence(token)) 26 | post[h++] = S.pop().getCharData(); 27 | S.push(new NodeData(token)); 28 | } 29 | token = getToken(); 30 | } 31 | while (!S.empty()) post[h++] = S.pop().getCharData(); 32 | return h; 33 | } //end readConvert 34 | 35 | public static void printPostfix(char[] post, int n) { 36 | System.out.printf("\nThe postfix form is \n"); 37 | for (int h = 0; h < n; h++) System.out.printf("%c ", post[h]); 38 | System.out.printf("\n"); 39 | } //end printPostfix 40 | 41 | public static char getToken() throws IOException { 42 | int n; 43 | while ((n = System.in.read()) == ' ') ; //read over blanks 44 | if (n == '\r') return '\0'; 45 | return (char) n; 46 | } //end getToken 47 | 48 | public static int precedence(char c) { 49 | //Returns the precedence of the given operator 50 | if (c == '(') return 0; 51 | if (c == '+' || c == '-') return 3; 52 | if (c == '*' || c == '/') return 5; 53 | return -99; //error 54 | } //end precedence 55 | 56 | public static int eval(char[] post, int n) { 57 | //Given the postfix form of an expression, returns its value 58 | int a, b, c; 59 | Stack S = new Stack(); 60 | for (int h = 0; h < n; h++) { 61 | if (Character.isDigit(post[h])) 62 | S.push(new NodeData(post[h] - '0')); 63 | else { 64 | b = S.pop().getIntData(); 65 | a = S.pop().getIntData(); 66 | if (post[h] == '+') c = a + b; 67 | else if (post[h] == '-') c = a - b; 68 | else if (post[h] == '*') c = a * b; 69 | else c = a / b; 70 | S.push(new NodeData(c)); 71 | } 72 | } 73 | return S.pop().getIntData(); 74 | } //end eval 75 | 76 | } //end class P4_6EvalExpression 77 | 78 | class NodeData { 79 | char ch; 80 | int num; 81 | 82 | public NodeData(char c) { 83 | ch = c; 84 | } 85 | 86 | public NodeData(int n) { 87 | num = n; 88 | } 89 | 90 | public NodeData(char c, int n) { 91 | ch = c; 92 | num = n; 93 | } 94 | 95 | public char getCharData() {return ch;} 96 | 97 | public int getIntData() {return num;} 98 | 99 | public static NodeData getRogueValue() { 100 | return new NodeData('$', -999999); 101 | } 102 | 103 | } //end class NodeData 104 | 105 | class Node { 106 | NodeData data; 107 | Node next; 108 | 109 | public Node(NodeData d) { 110 | data = d; 111 | next = null; 112 | } 113 | } //end class Node 114 | 115 | class Stack { 116 | Node top = null; 117 | 118 | public boolean empty() { 119 | return top == null; 120 | } 121 | 122 | public void push(NodeData nd) { 123 | Node p = new Node(nd); 124 | p.next = top; 125 | top = p; 126 | } //end push 127 | 128 | public NodeData pop() { 129 | if (this.empty())return NodeData.getRogueValue(); 130 | NodeData hold = top.data; 131 | top = top.next; 132 | return hold; 133 | } //end pop 134 | 135 | public NodeData peek() { 136 | if (!this.empty()) return top.data; 137 | return null; 138 | } //end peek 139 | 140 | } //end class Stack 141 | -------------------------------------------------------------------------------- /P4_7QueueTest.java: -------------------------------------------------------------------------------- 1 | //Program P4.7 2 | import java.util.*; 3 | public class P4_7QueueTest { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | Queue Q = new Queue(); 7 | System.out.printf("Enter a positive integer: "); 8 | int n = in.nextInt(); 9 | while (n > 0) { 10 | Q.enqueue(n % 10); 11 | n = n / 10; 12 | } 13 | System.out.printf("\nDigits in reverse order: "); 14 | while (!Q.empty()) 15 | System.out.printf("%d", Q.dequeue()); 16 | System.out.printf("\n"); 17 | } //end main 18 | 19 | } //end P4_7QueueTest 20 | 21 | class Queue { 22 | final static int MaxQ = 100; 23 | int head = 0, tail = 0; 24 | int[] QA = new int[MaxQ]; 25 | 26 | public boolean empty() { 27 | return head == tail; 28 | } 29 | 30 | public void enqueue(int n) { 31 | tail = (tail + 1) % MaxQ; //increment tail circularly 32 | if (tail == head) { 33 | System.out.printf("\nQueue is full\n"); 34 | System.exit(1); 35 | } 36 | QA[tail] = n; 37 | } //end enqueue 38 | 39 | public int dequeue() { 40 | if (this.empty()) { 41 | System.out.printf("\nAttempt to remove from an empty queue\n"); 42 | System.exit(2); 43 | } 44 | head = (head + 1) % MaxQ; //increment head circularly 45 | return QA[head]; 46 | } //end dequeue 47 | 48 | } //end class Queue 49 | -------------------------------------------------------------------------------- /P4_8QueueTest.java: -------------------------------------------------------------------------------- 1 | //Program P4.8 2 | import java.util.*; 3 | public class P4_8QueueTest { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | Queue Q = new Queue(); 7 | System.out.printf("Enter a positive integer: "); 8 | int n = in.nextInt(); 9 | while (n > 0) { 10 | Q.enqueue(new NodeData(n % 10)); 11 | n = n / 10; 12 | } 13 | System.out.printf("\nDigits in reverse order: "); 14 | while (!Q.empty()) 15 | System.out.printf("%d", Q.dequeue().getIntData()); 16 | System.out.printf("\n"); 17 | } //end main 18 | } //end P4_8QueueTest 19 | 20 | class NodeData { 21 | int num; 22 | 23 | public NodeData(int n) { 24 | num = n; 25 | } 26 | 27 | public int getIntData() {return num;} 28 | 29 | } //end class NodeData 30 | 31 | class Node { 32 | NodeData data; 33 | Node next; 34 | 35 | public Node(NodeData d) { 36 | data = d; 37 | next = null; 38 | } 39 | } //end class Node 40 | 41 | class Queue { 42 | Node head = null, tail = null; 43 | 44 | public boolean empty() { 45 | return head == null; 46 | } 47 | 48 | public void enqueue(NodeData nd) { 49 | Node p = new Node(nd); 50 | if (this.empty()) { 51 | head = p; 52 | tail = p; 53 | } 54 | else { 55 | tail.next = p; 56 | tail = p; 57 | } 58 | } //end enqueue 59 | 60 | public NodeData dequeue() { 61 | if (this.empty()) { 62 | System.out.printf("\nAttempt to remove from an empty queue\n"); 63 | System.exit(1); 64 | } 65 | NodeData hold = head.data; 66 | head = head.next; 67 | if (head == null) tail = null; 68 | return hold; 69 | } //end dequeue 70 | 71 | } //end class Queue 72 | -------------------------------------------------------------------------------- /P5_1MergeSortTest.java: -------------------------------------------------------------------------------- 1 | // Program P5.1 2 | public class P5_1MergeSortTest { 3 | public static void main(String[] args) { 4 | int[] num = {4,8,6,16,1,9,14,2,3,5,18,13,17,7,12,11,15,10}; 5 | int n = 18; 6 | mergeSort(num, 0, n-1); 7 | for (int h = 0; h < n; h++) System.out.printf("%d ", num[h]); 8 | System.out.printf("\n"); 9 | } // end main 10 | 11 | public static void mergeSort(int[] A, int lo, int hi) { 12 | if (lo < hi) { //list contains at least 2 elements 13 | int mid = (lo + hi) / 2; //get the mid-point subscript 14 | mergeSort(A, lo, mid); //sort first half 15 | mergeSort(A, mid + 1, hi); //sort second half 16 | merge(A, lo, mid, hi); //merge sorted halves 17 | } 18 | } //end mergeSort 19 | 20 | public static void merge(int[] A, int lo, int mid, int hi) { 21 | //A[lo..mid] and A[mid+1..hi] are sorted; 22 | //merge the pieces so that A[lo..hi] are sorted 23 | int[] T = new int[hi - lo + 1]; 24 | int i = lo, j = mid + 1; 25 | int k = 0; 26 | while (i <= mid || j <= hi) { 27 | if (i > mid) T[k++] = A[j++]; 28 | else if (j > hi) T[k++] = A[i++]; 29 | else if (A[i] < A[j]) T[k++] = A[i++]; 30 | else T[k++] = A[j++]; 31 | } 32 | for (j = 0; j < hi-lo+1; j++) A[lo + j] = T[j]; 33 | } //end merge 34 | 35 | } //end class P5_1MergeSortTest 36 | -------------------------------------------------------------------------------- /P5_2Organisms.java: -------------------------------------------------------------------------------- 1 | // Program P5.2 2 | import java.io.*; 3 | import java.util.*; 4 | public class P5_2Organisms { 5 | static int orgCount = 0; 6 | public static void main(String[] args) throws IOException { 7 | Scanner in = new Scanner(new FileReader("orgs.in")); 8 | PrintWriter out = new PrintWriter(new FileWriter("orgs.out")); 9 | int m = in.nextInt(), n = in.nextInt(); 10 | int[][] G = new int[m][n]; 11 | for (int i = 0; i < m; i++) 12 | for (int j = 0; j < n; j++) 13 | G[i][j] = in.nextInt(); 14 | for (int i = 0; i < m; i++) 15 | for (int j = 0; j < n; j++) 16 | if (G[i][j] == 1) { 17 | orgCount++; 18 | findOrg(G, i, j, m, n); 19 | } 20 | printOrg(out, G, m, n); 21 | in.close(); out.close(); 22 | } // end main 23 | 24 | public static void findOrg(int[][] G, int i, int j, int m, int n) { 25 | if (i < 0 || i >= m || j < 0 || j >= n) return; //outside of grid 26 | if (G[i][j] == 0 || G[i][j] > 1) return; //no cell or cell already seen 27 | // else G[i][j] = 1; 28 | G[i][j]= orgCount + 1; //so that this 1 is not considered again 29 | findOrg(G, i - 1, j, m, n); 30 | findOrg(G, i, j + 1, m, n); 31 | findOrg(G, i + 1, j, m, n); 32 | findOrg(G, i, j - 1, m, n); 33 | } //end findOrg 34 | 35 | public static void printOrg(PrintWriter out, int[][] G, int m, int n) { 36 | out.printf("\nNumber of organisms = %d\n", orgCount); 37 | out.printf("\nPosition of organisms are shown below\n\n"); 38 | for (int i = 0; i < m; i++) { 39 | for (int j = 0; j < n; j++) 40 | if (G[i][j] > 1) out.printf("%2d ", G[i][j] - 1); 41 | //organism labels are one more than they should be 42 | else out.printf("%2d ", G[i][j]); 43 | out.printf("\n"); 44 | } 45 | } //end printOrg 46 | 47 | } //end class P5_2Organisms 48 | -------------------------------------------------------------------------------- /P5_3Maze.java: -------------------------------------------------------------------------------- 1 | //Program P5.3 2 | import java.io.*; 3 | import java.util.*; 4 | public class P5_3Maze { 5 | static int[][]G; //known to all methods 6 | static int m, n, sr, sc; //known to all methods 7 | public static void main(String[] args) throws IOException { 8 | Scanner in = new Scanner(new FileReader("maze.in")); 9 | PrintWriter out = new PrintWriter(new FileWriter("maze.out")); 10 | getData(in); 11 | if (findPath(sr, sc)) printMaze(out); 12 | else out.printf("\nNo solution\n"); 13 | in.close(); out.close(); 14 | } // end main 15 | 16 | public static void getData(Scanner in) { 17 | m = in.nextInt(); n = in.nextInt(); 18 | G = new int[m+1][n+1]; 19 | sr = in.nextInt(); sc = in.nextInt(); 20 | for (int r = 1; r <= m; r++) 21 | for (int c = 1; c <= n; c++) 22 | G[r][c] = in.nextInt(); 23 | } //end getData 24 | 25 | public static boolean findPath(int r, int c) { 26 | if (r < 1 || r > m || c < 1 || c > n) return false; 27 | if (G[r][c] == 1) return false; //into a wall 28 | if (G[r][c] == 2) return false; //already considered 29 | // else G[r][c] = 0; 30 | G[r][c] = 2; //mark the path 31 | if (r == 1 || r == m || c == 1 || c == n) return true; 32 | //path found - space located on the border of the maze 33 | 34 | if (findPath(r-1, c)) return true; 35 | if (findPath(r, c+1)) return true; 36 | if (findPath(r+1, c)) return true; 37 | if (findPath(r, c-1)) return true; 38 | G[r][c] = 0; //no path found; unmark 39 | return false; 40 | } //end findPath 41 | 42 | public static void printMaze(PrintWriter out) { 43 | int r, c; 44 | for (r = 1; r <= m; r++) { 45 | for (c = 1; c <= n; c++) 46 | if (r == sr && c == sc) out.printf("S"); 47 | else if (G[r][c] == 0) out.printf(" "); 48 | else if (G[r][c] == 1) out.printf("#"); 49 | else out.printf("x"); 50 | out.printf("\n"); 51 | } 52 | } //end printMaze 53 | 54 | } //end class P5_3Maze 55 | -------------------------------------------------------------------------------- /P6_1RandomTest.java: -------------------------------------------------------------------------------- 1 | //Program P6.1 2 | import java.io.*; 3 | public class P6_1RandomTest { 4 | public static void main(String[] args) throws IOException { 5 | for (int j = 1; j <= 20; j++) System.out.printf("%2d", random(1, 6)); 6 | System.out.printf("\n"); 7 | } //end main 8 | 9 | public static int random(int m, int n) { 10 | //returns a random integer from m to n, inclusive 11 | return (int) (Math.random() * (n - m + 1)) + m; 12 | } //end random 13 | 14 | } //end class P6_1RandomTest 15 | 16 | -------------------------------------------------------------------------------- /P6_2GuessTheNumber.java: -------------------------------------------------------------------------------- 1 | // Program P6.2 2 | import java.util.*; 3 | public class P6_2GuessTheNumber { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | System.out.printf("\nI have thought of a number from 1 to 100.\n"); 7 | System.out.printf("Try to guess what it is.\n\n"); 8 | int answer = random(1, 100); 9 | 10 | System.out.printf("Your guess? "); 11 | int guess = in.nextInt(); 12 | while (guess != answer && guess != 0) { 13 | if (guess < answer) System.out.printf("Too low\n"); 14 | else System.out.printf("Too high\n"); 15 | System.out.printf("Your guess? "); 16 | guess = in.nextInt(); 17 | } 18 | if (guess == 0) System.out.printf("Sorry, answer is %d\n", answer); 19 | else System.out.printf("Congratulations, you've got it!\n"); 20 | } //end main 21 | 22 | public static int random(int m, int n) { 23 | //returns a random integer from m to n, inclusive 24 | return (int) (Math.random() * (n - m + 1)) + m; 25 | } 26 | } //end class P6_2GuessTheNumber 27 | -------------------------------------------------------------------------------- /P6_3Arithmetic.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P6_3Arithmetic.java -------------------------------------------------------------------------------- /P6_4Nim.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P6_4Nim.class -------------------------------------------------------------------------------- /P6_4Nim.java: -------------------------------------------------------------------------------- 1 | // Program P6.4 2 | import java.util.*; 3 | public class P6_4Nim { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | System.out.printf("\nNumber of matches on the table? "); 7 | int remain = in.nextInt(); 8 | System.out.printf("Maximum pickup per turn? "); 9 | int maxPick = in.nextInt(); 10 | playGame(in, remain, maxPick); 11 | } //end main 12 | 13 | public static void playGame(Scanner in, int remain, int maxPick) { 14 | int userPick; 15 | System.out.printf("\nMatches remaining: %d\n", remain); 16 | while (true) { //do forever...well, until the game ends 17 | do { 18 | System.out.printf("Your turn: "); 19 | userPick = in.nextInt(); 20 | if (userPick > remain) 21 | System.out.printf("Cannot pick up more than %d\n", Math.min(remain, maxPick)); 22 | else if (userPick < 1 || userPick > maxPick) 23 | System.out.printf("Invalid: must be between 1 and %d\n", maxPick); 24 | } while (userPick > remain || userPick < 1 || userPick > maxPick); 25 | 26 | remain = remain - userPick; 27 | System.out.printf("Matches remaining: %d\n", remain); 28 | if (remain == 0) { 29 | System.out.printf("You lose!!\n"); return; 30 | } 31 | if (remain == 1) { 32 | System.out.printf("You win!!\n"); return; 33 | } 34 | int compPick = bestPick(remain, maxPick); 35 | System.out.printf("I pick up %d\n", compPick); 36 | remain = remain - compPick; 37 | System.out.printf("Matches remaining: %d\n", remain); 38 | if (remain == 0) { 39 | System.out.printf("You win!!\n"); 40 | return; 41 | } 42 | if (remain == 1) { 43 | System.out.printf("I win!!\n"); 44 | return; 45 | } 46 | } //end while (true) 47 | } //end playGame 48 | 49 | public static int bestPick(int remain, int maxPick) { 50 | if (remain <= maxPick) return remain - 1; //put user in losing position 51 | int r = remain % (maxPick + 1); 52 | if (r == 0) return maxPick; //put user in losing position 53 | if (r == 1) return random(1, maxPick); //computer in losing position 54 | return r - 1; //put user in losing position 55 | } //end bestPick 56 | 57 | public static int random(int m, int n) { 58 | //returns a random integer from m to n, inclusive 59 | return (int) (Math.random() * (n - m + 1)) + m; 60 | } //end random 61 | 62 | } //end class P6_4Nim 63 | -------------------------------------------------------------------------------- /P6_5BottleCaps.java: -------------------------------------------------------------------------------- 1 | // Program P6.5 2 | public class P6_5BottleCaps { 3 | static int MaxSim = 20; 4 | static int MaxLetters = 5; 5 | public static void main(String[] args) { 6 | int sim, capsThisSim, totalCaps = 0; 7 | System.out.printf("\nSimulation Caps collected\n\n"); 8 | for (sim = 1; sim <= MaxSim; sim++) { 9 | capsThisSim = doOneSimulation(); 10 | System.out.printf("%6d %13d\n", sim, capsThisSim); 11 | totalCaps += capsThisSim; 12 | } 13 | System.out.printf("\nAverage caps per simulation: %d\n", totalCaps/MaxSim); 14 | } //end main 15 | 16 | public static int doOneSimulation() { 17 | boolean[] cap = new boolean[MaxLetters]; 18 | for (int j = 0; j < MaxLetters; j++) cap[j] = false; 19 | int numCaps = 0; 20 | while (!mango(cap)) { 21 | int c = random(1, 20); 22 | if (c <= 8) cap[0] = true; 23 | else if (c <= 13) cap[1] = true; 24 | else if (c <= 16) cap[2] = true; 25 | else if (c <= 19) cap[3] = true; 26 | else cap[4] = true; 27 | numCaps++; 28 | } //end while 29 | return numCaps; 30 | } //end doOneSimulation 31 | 32 | public static boolean mango(boolean[] cap) { 33 | for (int j = 0; j < MaxLetters; j++) 34 | if (cap[j] == false) return false; 35 | return true; 36 | } //end mango 37 | 38 | public static int random(int m, int n) { 39 | //returns a random integer from m to n, inclusive 40 | return (int) (Math.random() * (n - m + 1)) + m; 41 | } //end random 42 | 43 | } //end class P6_5BottleCaps 44 | -------------------------------------------------------------------------------- /P6_6SimulateQueue.java: -------------------------------------------------------------------------------- 1 | // Program P6.6 2 | import java.util.*; 3 | public class P6_6SimulateQueue { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | System.out.printf("\nHow many counters? "); 7 | int numCounters = in.nextInt(); 8 | System.out.printf("\nHow many customers? "); 9 | int numCustomers = in.nextInt(); 10 | 11 | doSimulation(numCounters, numCustomers); 12 | } //end main 13 | 14 | public static void doSimulation(int counters, int customers) { 15 | int m, arriveTime, startServe, serveTime, waitTime; 16 | int[] depart = new int[counters + 1]; 17 | for (int h = 1; h <= counters; h++) depart[h] = 0; 18 | System.out.printf("\n Start Service Wait\n"); 19 | System.out.printf("Customer Arrives Service Counter Time Departs Time\n\n"); 20 | arriveTime = 0; 21 | for (int h = 1; h <= customers; h++) { 22 | arriveTime += random(1, 5); 23 | m = smallest(depart, 1, counters); 24 | startServe = Math.max(arriveTime, depart[m]); 25 | serveTime = random(3, 10); 26 | depart[m] = startServe + serveTime; 27 | waitTime = startServe - arriveTime; 28 | System.out.printf("%5d %8d %7d %6d %7d %8d %5d\n", 29 | h, arriveTime, startServe, m, serveTime, depart[m], waitTime); 30 | } //end for h 31 | } //end doSimulation 32 | 33 | public static int smallest(int list[], int lo, int hi) { 34 | //returns the subscript of the smallest value from list[lo..hi] 35 | int h, k = lo; 36 | for (h = lo + 1; h <= hi; h++) 37 | if (list[h] < list[k]) k = h; 38 | return k; 39 | } 40 | 41 | public static int random(int m, int n) { 42 | //returns a random integer from m to n, inclusive 43 | return (int) (Math.random() * (n - m + 1)) + m; 44 | } //end random 45 | 46 | } //end class P6_6SimulateQueue 47 | -------------------------------------------------------------------------------- /P6_7Root5.java: -------------------------------------------------------------------------------- 1 | // Program P6.7 2 | import java.util.*; 3 | public class P6_7Root5 { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | System.out.printf("\nHow many numbers to use? "); 7 | int maxCount = in.nextInt(); 8 | 9 | int amountLess = 0; 10 | for (int j = 1; j <= maxCount; j++) { 11 | double r = 2 + Math.random(); 12 | if (r * r < 5) ++amountLess; 13 | } 14 | System.out.printf("\nThe square root of 5 is about %5.3f\n", 15 | 2 + (double) amountLess / maxCount); 16 | } //end main 17 | 18 | } //end class P6_7Root5 19 | -------------------------------------------------------------------------------- /P6_8Pi.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P6_8Pi.class -------------------------------------------------------------------------------- /P6_8Pi.java: -------------------------------------------------------------------------------- 1 | // Program P6.8 2 | import java.util.*; 3 | public class P6_8Pi { 4 | public static void main(String[] args) { 5 | Scanner in = new Scanner(System.in); 6 | int inC = 0; 7 | 8 | System.out.printf("\nHow many numbers to use? "); 9 | int inS = in.nextInt(); 10 | 11 | for (int j = 1; j <= inS; j++) { 12 | double x = Math.random(); 13 | double y = Math.random(); 14 | if (x * x + y * y <= 1) inC++; 15 | } 16 | System.out.printf("\nAn approximation to pi is %5.3f\n", 4.0 * inC/inS); 17 | } //end main 18 | 19 | } //end class P6_8Pi 20 | -------------------------------------------------------------------------------- /P7_10UpdateFile.java: -------------------------------------------------------------------------------- 1 | // Program P7.10 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_10UpdateFile { 5 | static final int StringFixedLength = 20; 6 | static final int PartNumSize = 6; 7 | static final int PartRecordSize = 64; 8 | static int MaxRecords; 9 | 10 | public static void main(String[] args) throws IOException { 11 | Scanner in = new Scanner(System.in); 12 | Index[] index = retrieveIndex(); 13 | int numRecords = index[0].recNum; 14 | 15 | System.out.printf("\nEnter part number (E to end): "); 16 | String pnum = in.next(); 17 | while (!pnum.equalsIgnoreCase("E")) { 18 | updateRecord(pnum, index, numRecords); 19 | System.out.printf("\nEnter part number (E to end): "); 20 | pnum = in.next(); 21 | } //end while 22 | } //end main 23 | 24 | public static void updateRecord(String pnum, Index[] index, int max) 25 | throws IOException { 26 | Scanner in = new Scanner(System.in); 27 | RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw"); 28 | 29 | int n = search(pnum, index, max); 30 | if (n < 0) System.out.printf("Part not found\n"); 31 | else { 32 | fp.seek(PartRecordSize * (index[n].recNum - 1)); 33 | Part part = readPartFromFile(fp); 34 | System.out.printf("Enter amount sold: "); 35 | int amtSold = in.nextInt(); 36 | if (amtSold > part.amtInStock) 37 | System.out.printf("You have %d: cannot sell more, ignored\n", 38 | part.amtInStock); 39 | else { 40 | part.amtInStock -= amtSold; 41 | System.out.printf("Amount remaining: %d\n", part.amtInStock); 42 | fp.seek(PartRecordSize * (index[n].recNum - 1)); 43 | writePartToFile(part, fp); 44 | System.out.printf("%s %-11s %2d %5.2f\n", part.partNum, part.name, part.amtInStock, part.price); 45 | } //end if 46 | } //end if 47 | fp.close(); 48 | } //end updateRecord 49 | 50 | public static Index[] retrieveIndex() throws IOException { 51 | RandomAccessFile f = new RandomAccessFile("index.bin", "rw"); 52 | int MaxRecords = f.readInt(); 53 | Index[] index = new Index[MaxRecords + 1]; 54 | for (int j = 0; j <= MaxRecords; j++) { 55 | String pnum = ""; 56 | for (int i = 0; i < PartNumSize; i++) pnum += f.readChar(); 57 | index[j] = new Index(pnum, f.readInt()); 58 | } 59 | f.close(); 60 | return index; 61 | } //end retrieveIndex 62 | 63 | public static Part readPartFromFile(RandomAccessFile f) throws IOException { 64 | String pname = ""; 65 | for (int h = 0; h < PartNumSize; h++) pname += f.readChar(); 66 | char[] name = new char[StringFixedLength]; 67 | for (int h = 0; h < StringFixedLength; h++) name[h] = f.readChar(); 68 | String hold = new String(name, 0, StringFixedLength); 69 | return new Part(pname, hold.trim(), f.readInt(), f.readDouble()); 70 | } //end readPartFromFile 71 | 72 | public static void writePartToFile(Part part, RandomAccessFile f) throws IOException { 73 | for (int h = 0; h < PartNumSize; h++) f.writeChar(part.partNum.charAt(h)); 74 | int n = Math.min(part.name.length(), StringFixedLength); 75 | for (int h = 0; h < n; h++) f.writeChar(part.name.charAt(h)); 76 | for (int h = n; h < StringFixedLength; h++) f.writeChar(' '); 77 | f.writeInt(part.amtInStock); 78 | f.writeDouble(part.price); 79 | } //end writePartToFile 80 | 81 | 82 | public static int search(String key, Index[] list, int n) { 83 | //searches list[1..n] for key. If found, it returns the location; otherwise 84 | //it returns the negative of the location in which key should be inserted. 85 | int lo = 1, hi = n; 86 | while (lo <= hi) { // as long as more elements remain to consider 87 | int mid = (lo + hi) / 2; 88 | int cmp = key.compareToIgnoreCase(list[mid].partNum); 89 | if (cmp == 0) return mid; // search succeeds 90 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 91 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 92 | } 93 | return -lo; // key not found; insert in location lo 94 | } // end search 95 | 96 | } //end class P7_10UpdateFile 97 | 98 | class Part { 99 | String partNum, name; 100 | int amtInStock; 101 | double price; 102 | 103 | public Part(String pn, String n, int a, double p) { 104 | partNum = pn; 105 | name = n; 106 | amtInStock = a; 107 | price = p; 108 | } 109 | 110 | public void printPart() { 111 | System.out.printf("Part number: %s\n", partNum); 112 | System.out.printf("Part name: %s\n", name); 113 | System.out.printf("Amount in stock: %d\n", amtInStock); 114 | System.out.printf("Price: $%3.2f\n", price); 115 | } 116 | 117 | } //end class Part 118 | 119 | class Index { 120 | String partNum; 121 | int recNum; 122 | 123 | public Index(String p, int r) { 124 | partNum = p; 125 | recNum = r; 126 | } 127 | } //end class Index 128 | -------------------------------------------------------------------------------- /P7_1CompareFiles.java: -------------------------------------------------------------------------------- 1 | // Program P7.1 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_1CompareFiles { 5 | public static void main(String[] args) throws IOException { 6 | Scanner kb = new Scanner(System.in); 7 | 8 | System.out.printf("First file? "); 9 | String file1 = kb.nextLine(); 10 | System.out.printf("Second file? "); 11 | String file2 = kb.nextLine(); 12 | 13 | Scanner f1 = new Scanner(new FileReader(file1)); 14 | Scanner f2 = new Scanner(new FileReader(file2)); 15 | 16 | String line1 = "", line2 = ""; 17 | int numMatch = 0; 18 | 19 | while (f1.hasNextLine() && f2.hasNextLine()) { 20 | line1 = f1.nextLine(); 21 | line2 = f2.nextLine(); 22 | if (!line1.equals(line2)) break; 23 | ++numMatch; 24 | } 25 | if (!f1.hasNextLine() && !f2.hasNextLine()) 26 | System.out.printf("\nThe files are identical\n"); 27 | else if (!f1.hasNextLine()) //first file ends, but not the second 28 | System.out.printf("\n%s, with %d lines, is a subset of %s\n", 29 | file1, numMatch, file2); 30 | else if (!f2.hasNextLine()) //second file ends, but not the first 31 | System.out.printf("\n%s, with %d lines, is a subset of %s\n", 32 | file2, numMatch, file1); 33 | else { //mismatch found 34 | System.out.printf("\nThe files differ at line %d\n", ++numMatch); 35 | System.out.printf("The lines are \n%s\n and \n%s\n", line1, line2); 36 | } 37 | f1.close(); 38 | f2.close(); 39 | } //end main 40 | 41 | } //end class P7_1CompareFiles 42 | -------------------------------------------------------------------------------- /P7_2CreateBinaryFile.java: -------------------------------------------------------------------------------- 1 | // Program P7.2 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_2CreateBinaryFile { 5 | public static void main(String[] args) throws IOException { 6 | Scanner in = new Scanner(new FileReader("num.txt")); 7 | DataOutputStream out = new DataOutputStream(new FileOutputStream("num.bin")); 8 | int n = in.nextInt(); 9 | while (n != 0) { 10 | out.writeInt(n); 11 | n = in.nextInt(); 12 | } 13 | out.close(); 14 | in.close(); 15 | } //end main 16 | } //end class P7_2CreateBinaryFile 17 | -------------------------------------------------------------------------------- /P7_3ReadBinaryFile.java: -------------------------------------------------------------------------------- 1 | // Program P7.3 2 | import java.io.*; 3 | public class P7_3ReadBinaryFile { 4 | public static void main(String[] args) throws IOException { 5 | DataInputStream in = 6 | new DataInputStream(new FileInputStream("num.bin")); 7 | int amt = 0; 8 | try { 9 | while (true) { 10 | int n = in.readInt(); 11 | System.out.printf("%d ", n); 12 | ++amt; 13 | } 14 | } 15 | catch (IOException e) { } 16 | System.out.printf("\n\n%d numbers were read\n", amt); 17 | } //end main 18 | } //end class P7_3ReadBinaryFile 19 | -------------------------------------------------------------------------------- /P7_4CreateBinaryFile1.java: -------------------------------------------------------------------------------- 1 | // Program P7.4 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_4CreateBinaryFile1 { 5 | public static void main(String[] args) throws IOException { 6 | Scanner in = new Scanner(new FileReader("parts.txt")); 7 | DataOutputStream out = new DataOutputStream(new FileOutputStream("parts.bin")); 8 | int n = in.nextInt(); 9 | while (n != 0) { 10 | out.writeInt(n); 11 | out.writeDouble(in.nextDouble()); 12 | n = in.nextInt(); 13 | } 14 | in.close(); out.close(); 15 | } //end main 16 | } //end P7_4CreateBinaryFile1 17 | -------------------------------------------------------------------------------- /P7_5CreateBinaryFile2.java: -------------------------------------------------------------------------------- 1 | // Program P7.5 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_5CreateBinaryFile2 { 5 | static final int EndOfData = 0; 6 | 7 | public static void main(String[] args) throws IOException { 8 | Scanner in = new Scanner(new FileReader("parts.txt")); 9 | DataOutputStream fp = 10 | new DataOutputStream(new FileOutputStream("parts.bin")); 11 | 12 | Part part = getPartData(in); 13 | while (part != null) { 14 | writePartToFile(part, fp); 15 | part = getPartData(in); 16 | } 17 | 18 | in.close(); 19 | fp.close(); 20 | } //end main 21 | 22 | public static Part getPartData(Scanner in) { 23 | int pnum = in.nextInt(); 24 | if (pnum == EndOfData) return null; 25 | return new Part(pnum, in.nextDouble()); 26 | } 27 | 28 | public static void writePartToFile(Part part, DataOutputStream f) throws IOException { 29 | f.writeInt(part.partNum); 30 | f.writeDouble(part.price); 31 | part.printPart(); //print data on standard input 32 | } //end writePartToFile 33 | } //end class P7_5CreateBinaryFile2 34 | 35 | class Part { 36 | int partNum; 37 | double price; 38 | 39 | public Part(int pn, double pr) { 40 | partNum = pn; 41 | price = pr; 42 | } 43 | 44 | public void printPart() { 45 | System.out.printf("\nPart number: %s\n", partNum); 46 | System.out.printf("Price: $%3.2f\n", price); 47 | } 48 | } //end class Part 49 | -------------------------------------------------------------------------------- /P7_6CreateRandomAccess.java: -------------------------------------------------------------------------------- 1 | // Program P7.6 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_6CreateRandomAccess { 5 | static final int StringFixedLength = 20; 6 | static final int PartNumSize = 6; 7 | static final int PartRecordSize = 64; 8 | static final String EndOfData = "END"; 9 | 10 | public static void main(String[] args) throws IOException { 11 | Scanner in = new Scanner(new FileReader("parts.txt")); 12 | RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw"); 13 | Part part = getPartData(in); 14 | while (part != null) { 15 | writePartToFile(part, fp); 16 | part = getPartData(in); 17 | } 18 | } //end main 19 | 20 | public static Part getPartData(Scanner in) { 21 | String pnum = in.next(); 22 | if (pnum.equals(EndOfData)) return null; 23 | return new Part(pnum, in.next(), in.nextInt(), in.nextDouble()); 24 | } //end getPartData 25 | 26 | public static void writePartToFile(Part part, RandomAccessFile f) throws IOException { 27 | System.out.printf("%s %-11s %2d %5.2f %3d\n", part.partNum, part.name, 28 | part.amtInStock, part.price, f.getFilePointer()); 29 | for (int h = 0; h < PartNumSize; h++) f.writeChar(part.partNum.charAt(h)); 30 | int n = Math.min(part.name.length(), StringFixedLength); 31 | for (int h = 0; h < n; h++) f.writeChar(part.name.charAt(h)); 32 | for (int h = n; h < StringFixedLength; h++) f.writeChar(' '); 33 | f.writeInt(part.amtInStock); 34 | f.writeDouble(part.price); 35 | } //end writePartToFile 36 | 37 | } //end class P7_6CreateRandomAccess 38 | 39 | class Part { 40 | String partNum, name; 41 | int amtInStock; 42 | double price; 43 | 44 | public Part(String pn, String n, int a, double p) { 45 | partNum = pn; 46 | name = n; 47 | amtInStock = a; 48 | price = p; 49 | } 50 | 51 | public void printPart() { 52 | System.out.printf("Part number: %s\n", partNum); 53 | System.out.printf("Part name: %s\n", name); 54 | System.out.printf("Amount in stock: %d\n", amtInStock); 55 | System.out.printf("Price: $%3.2f\n", price); 56 | } 57 | 58 | } //end class Part 59 | 60 | -------------------------------------------------------------------------------- /P7_7ReadRandomAccess.java: -------------------------------------------------------------------------------- 1 | // Program P7.7 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_7ReadRandomAccess { 5 | static final int StringFixedLength = 20; 6 | static final int PartNumSize = 6; 7 | static final int PartRecordSize = 64; 8 | 9 | public static void main(String[] args) throws IOException { 10 | RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw"); 11 | Scanner kb = new Scanner(System.in); 12 | System.out.printf("\nEnter a record number: "); 13 | int n = kb.nextInt(); 14 | while (n != 0) { 15 | fp.seek(PartRecordSize * (n - 1)); 16 | readPartFromFile(fp).printPart(); 17 | System.out.printf("\nEnter a record number: "); 18 | n = kb.nextInt(); 19 | } 20 | } //end main 21 | 22 | public static Part readPartFromFile(RandomAccessFile f) throws IOException { 23 | String pname = ""; 24 | for (int h = 0; h < PartNumSize; h++) pname += f.readChar(); 25 | char[] name = new char[StringFixedLength]; 26 | for (int h = 0; h < StringFixedLength; h++) name[h] = f.readChar(); 27 | String hold = new String(name, 0, StringFixedLength); 28 | return new Part(pname, hold.trim(), f.readInt(), f.readDouble()); 29 | } //end readPartFromFile 30 | 31 | } //end class P7_7ReadRandomAccess 32 | 33 | class Part { 34 | String partNum, name; 35 | int amtInStock; 36 | double price; 37 | 38 | public Part(String pn, String n, int a, double p) { 39 | partNum = pn; 40 | name = n; 41 | amtInStock = a; 42 | price = p; 43 | } 44 | 45 | public void printPart() { 46 | System.out.printf("Part number: %s\n", partNum); 47 | System.out.printf("Part name: %s\n", name); 48 | System.out.printf("Amount in stock: %d\n", amtInStock); 49 | System.out.printf("Price: $%3.2f\n", price); 50 | } 51 | 52 | } //end class Part 53 | 54 | -------------------------------------------------------------------------------- /P7_8CreateIndex.java: -------------------------------------------------------------------------------- 1 | // Program P7.8 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_8CreateIndex { 5 | static final int StringFixedLength = 20; 6 | static final int PartNumSize = 6; 7 | static final int PartRecordSize = 64; 8 | static final int MaxRecords = 100; 9 | static final String EndOfData = "END"; 10 | 11 | public static void main(String[] args) throws IOException { 12 | RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw"); 13 | Index[] index = new Index[MaxRecords + 1]; 14 | 15 | createMasterIndex(index, fp); 16 | saveIndex(index); 17 | printIndex(index); 18 | fp.close(); 19 | } //end main 20 | 21 | public static void createMasterIndex(Index[] index, 22 | RandomAccessFile f) throws IOException { 23 | Scanner in = new Scanner(new FileReader("parts.txt")); 24 | int numRecords = 0; 25 | Part part = getPartData(in); 26 | while (part != null) { 27 | int searchResult = search(part.partNum, index, numRecords); 28 | if (searchResult > 0) 29 | System.out.printf("Duplicate part: %s ignored\n", part.partNum); 30 | else { //this is a new part number; insert in location -searchResult 31 | if (numRecords == MaxRecords) { 32 | System.out.printf("Too many records: only %d allowed\n", MaxRecords); 33 | System.exit(1); 34 | } 35 | //the index has room; shift entries to accommodate new part 36 | for (int h = numRecords; h >= -searchResult; h--) 37 | index[h + 1] = index[h]; 38 | index[-searchResult] = new Index(part.partNum, ++numRecords); 39 | writePartToFile(part, f); 40 | } 41 | part = getPartData(in); 42 | } //end while 43 | index[0] = new Index("NOPART", numRecords); 44 | in.close(); 45 | } //end createMasterIndex 46 | 47 | public static Part getPartData(Scanner in) { 48 | String pnum = in.next(); 49 | if (pnum.equals(EndOfData)) return null; 50 | return new Part(pnum, in.next(), in.nextInt(), in.nextDouble()); 51 | } //end getPartData 52 | 53 | public static void writePartToFile(Part part, RandomAccessFile f) throws IOException { 54 | for (int h = 0; h < PartNumSize; h++) f.writeChar(part.partNum.charAt(h)); 55 | int n = Math.min(part.name.length(), StringFixedLength); 56 | for (int h = 0; h < n; h++) f.writeChar(part.name.charAt(h)); 57 | for (int h = n; h < StringFixedLength; h++) f.writeChar(' '); 58 | f.writeInt(part.amtInStock); 59 | f.writeDouble(part.price); 60 | } //end writePartToFile 61 | 62 | public static void saveIndex(Index[] index) throws IOException { 63 | RandomAccessFile f = new RandomAccessFile("index.bin", "rw"); 64 | int numRecords = index[0].recNum; 65 | //fill the unused index positions with dummy entries 66 | for (int h = numRecords+1; h <= MaxRecords; h++) 67 | index[h] = new Index("NOPART", 0); 68 | f.writeInt(MaxRecords); 69 | for (int h = 0; h <= MaxRecords; h++) { 70 | for (int i = 0; i < PartNumSize; i++) 71 | f.writeChar(index[h].partNum.charAt(i)); 72 | f.writeInt(index[h].recNum); 73 | } 74 | f.close(); 75 | } //end saveIndex 76 | 77 | public static int search(String key, Index[] list, int n) { 78 | //searches list[1..n] for key. If found, it returns the location; otherwise 79 | //it returns the negative of the location in which key should be inserted. 80 | int lo = 1, hi = n; 81 | while (lo <= hi) { // as long as more elements remain to consider 82 | int mid = (lo + hi) / 2; 83 | int cmp = key.compareToIgnoreCase(list[mid].partNum); 84 | if (cmp == 0) return mid; // search succeeds 85 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 86 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 87 | } 88 | return -lo; // key not found; insert in location lo 89 | } // end search 90 | 91 | public static void printIndex(Index[] index) { 92 | System.out.printf("\nThe index is as follows: \n\n"); 93 | int numRecords = index[0].recNum; 94 | for (int h = 1; h <= numRecords; h++) 95 | System.out.printf("%s %2d\n", index[h].partNum, index[h].recNum); 96 | } //end printIndex 97 | 98 | } //end class P7_8CreateIndex 99 | 100 | class Part { 101 | String partNum, name; 102 | int amtInStock; 103 | double price; 104 | 105 | public Part(String pn, String n, int a, double p) { 106 | partNum = pn; 107 | name = n; 108 | amtInStock = a; 109 | price = p; 110 | } 111 | 112 | public void printPart() { 113 | System.out.printf("Part number: %s\n", partNum); 114 | System.out.printf("Part name: %s\n", name); 115 | System.out.printf("Amount in stock: %d\n", amtInStock); 116 | System.out.printf("Price: $%3.2f\n", price); 117 | } 118 | 119 | } //end class Part 120 | 121 | class Index { 122 | String partNum; 123 | int recNum; 124 | 125 | public Index(String p, int r) { 126 | partNum = p; 127 | recNum = r; 128 | } 129 | } //end class Index 130 | 131 | -------------------------------------------------------------------------------- /P7_9UseIndex.java: -------------------------------------------------------------------------------- 1 | // Program P7.9 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_9UseIndex { 5 | static final int StringFixedLength = 20; 6 | static final int PartNumSize = 6; 7 | static final int PartRecordSize = 64; 8 | static int MaxRecords; 9 | 10 | public static void main(String[] args) throws IOException { 11 | RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw"); 12 | Index[] index = retrieveIndex(); 13 | int numRecords = index[0].recNum; 14 | Scanner kb = new Scanner(System.in); 15 | System.out.printf("\nEnter a part number (E to end): "); 16 | String pnum = kb.next(); 17 | while (!pnum.equalsIgnoreCase("E")) { 18 | int n = search(pnum, index, numRecords); 19 | if (n > 0) { 20 | fp.seek(PartRecordSize * (index[n].recNum - 1)); 21 | readPartFromFile(fp).printPart(); 22 | } 23 | else System.out.printf("Part not found\n"); 24 | System.out.printf("\nEnter a part number (E to end): "); 25 | pnum = kb.next(); 26 | } //end while 27 | fp.close(); 28 | } //end main 29 | 30 | public static Index[] retrieveIndex() throws IOException { 31 | RandomAccessFile f = new RandomAccessFile("index.bin", "rw"); 32 | int MaxRecords = f.readInt(); 33 | Index[] index = new Index[MaxRecords + 1]; 34 | for (int j = 0; j <= MaxRecords; j++) { 35 | String pnum = ""; 36 | for (int i = 0; i < PartNumSize; i++) pnum += f.readChar(); 37 | index[j] = new Index(pnum, f.readInt()); 38 | } 39 | f.close(); 40 | return index; 41 | } //end retrieveIndex 42 | 43 | public static Part readPartFromFile(RandomAccessFile f) throws IOException { 44 | String pname = ""; 45 | for (int h = 0; h < PartNumSize; h++) pname += f.readChar(); 46 | char[] name = new char[StringFixedLength]; 47 | for (int h = 0; h < StringFixedLength; h++) name[h] = f.readChar(); 48 | String hold = new String(name, 0, StringFixedLength); 49 | return new Part(pname, hold.trim(), f.readInt(), f.readDouble()); 50 | } //end readPartFromFile 51 | 52 | public static int search(String key, Index[] list, int n) { 53 | //searches list[1..n] for key. If found, it returns the location; otherwise 54 | //it returns the negative of the location in which key should be inserted. 55 | int lo = 1, hi = n; 56 | while (lo <= hi) { // as long as more elements remain to consider 57 | int mid = (lo + hi) / 2; 58 | int cmp = key.compareToIgnoreCase(list[mid].partNum); 59 | if (cmp == 0) return mid; // search succeeds 60 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 61 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 62 | } 63 | return -lo; // key not found; insert in location lo 64 | } // end search 65 | 66 | } //end class P7_9UseIndex 67 | 68 | class Part { 69 | String partNum, name; 70 | int amtInStock; 71 | double price; 72 | 73 | public Part(String pn, String n, int a, double p) { 74 | partNum = pn; 75 | name = n; 76 | amtInStock = a; 77 | price = p; 78 | } 79 | 80 | public void printPart() { 81 | System.out.printf("Part number: %s\n", partNum); 82 | System.out.printf("Part name: %s\n", name); 83 | System.out.printf("Amount in stock: %d\n", amtInStock); 84 | System.out.printf("Price: $%3.2f\n", price); 85 | } 86 | 87 | } //end class Part 88 | 89 | class Index { 90 | String partNum; 91 | int recNum; 92 | 93 | public Index(String p, int r) { 94 | partNum = p; 95 | recNum = r; 96 | } 97 | } //end class Index 98 | -------------------------------------------------------------------------------- /P7_xPrintFileInOrder.java: -------------------------------------------------------------------------------- 1 | // Program P7.x - print file in order 2 | import java.io.*; 3 | import java.util.*; 4 | public class P7_xPrintFileInOrder { 5 | static final int StringFixedLength = 20; 6 | static final int PartNumSize = 6; 7 | static final int PartRecordSize = 64; 8 | static final int MaxRecords = 100; 9 | static final String EndOfData = "END"; 10 | 11 | public static void main(String[] args) throws IOException { 12 | RandomAccessFile fp = new RandomAccessFile("parts.bin", "rw"); 13 | Index[] index = new Index[MaxRecords + 1]; 14 | 15 | createMasterIndex(index, fp); 16 | saveIndex(index); 17 | printFileInOrder(index, fp); 18 | fp.close(); 19 | } //end main 20 | 21 | public static void createMasterIndex(Index[] index, 22 | RandomAccessFile f) throws IOException { 23 | Scanner in = new Scanner(new FileReader("parts.txt")); 24 | int numRecords = 0; 25 | Part part = getPartData(in); 26 | while (part != null) { 27 | int searchResult = search(part.partNum, index, numRecords); 28 | if (searchResult > 0) 29 | System.out.printf("Duplicate part: %s ignored\n", part.partNum); 30 | else { //this is a new part number; insert in location -searchResult 31 | if (numRecords == MaxRecords) { 32 | System.out.printf("Too many records: only %d allowed\n", MaxRecords); 33 | System.exit(1); 34 | } 35 | //the index has room; shift entries to accommodate new part 36 | for (int h = numRecords; h >= -searchResult; h--) 37 | index[h + 1] = index[h]; 38 | index[-searchResult] = new Index(part.partNum, ++numRecords); 39 | writePartToFile(part, f); 40 | } 41 | part = getPartData(in); 42 | } //end while 43 | index[0] = new Index("NOPART", numRecords); 44 | in.close(); 45 | } //end createMasterIndex 46 | 47 | public static Part getPartData(Scanner in) { 48 | String pnum = in.next(); 49 | if (pnum.equals(EndOfData)) return null; 50 | return new Part(pnum, in.next(), in.nextInt(), in.nextDouble()); 51 | } //end getPartData 52 | 53 | public static void writePartToFile(Part part, RandomAccessFile f) throws IOException { 54 | for (int h = 0; h < PartNumSize; h++) f.writeChar(part.partNum.charAt(h)); 55 | int n = Math.min(part.name.length(), StringFixedLength); 56 | for (int h = 0; h < n; h++) f.writeChar(part.name.charAt(h)); 57 | for (int h = n; h < StringFixedLength; h++) f.writeChar(' '); 58 | f.writeInt(part.amtInStock); 59 | f.writeDouble(part.price); 60 | } //end writePartToFile 61 | 62 | public static void saveIndex(Index[] index) throws IOException { 63 | RandomAccessFile f = new RandomAccessFile("index.bin", "rw"); 64 | int numRecords = index[0].recNum; 65 | //fill the unused index positions with dummy entries 66 | for (int h = numRecords+1; h <= MaxRecords; h++) 67 | index[h] = new Index("NOPART", 0); 68 | f.writeInt(MaxRecords); 69 | for (int h = 0; h <= MaxRecords; h++) { 70 | for (int i = 0; i < PartNumSize; i++) 71 | f.writeChar(index[h].partNum.charAt(i)); 72 | f.writeInt(index[h].recNum); 73 | } 74 | f.close(); 75 | } //end saveIndex 76 | 77 | public static int search(String key, Index[] list, int n) { 78 | //searches list[1..n] for key. If found, it returns the location; otherwise 79 | //it returns the negative of the location in which key should be inserted. 80 | int lo = 1, hi = n; 81 | while (lo <= hi) { // as long as more elements remain to consider 82 | int mid = (lo + hi) / 2; 83 | int cmp = key.compareToIgnoreCase(list[mid].partNum); 84 | if (cmp == 0) return mid; // search succeeds 85 | if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum 86 | else lo = mid + 1; // key is 'greater than' list[mid].partNum 87 | } 88 | return -lo; // key not found; insert in location lo 89 | } // end search 90 | 91 | public static Part readPartFromFile(RandomAccessFile f) throws IOException { 92 | String pname = ""; 93 | for (int h = 0; h < PartNumSize; h++) pname += f.readChar(); 94 | char[] name = new char[StringFixedLength]; 95 | for (int h = 0; h < StringFixedLength; h++) name[h] = f.readChar(); 96 | String hold = new String(name, 0, StringFixedLength); 97 | return new Part(pname, hold.trim(), f.readInt(), f.readDouble()); 98 | } //end readPartFromFile 99 | 100 | public static void printFileInOrder(Index[] index, RandomAccessFile f) throws IOException { 101 | System.out.printf("\nFile sorted by part number: \n\n"); 102 | int numRecords = index[0].recNum; 103 | for (int h = 1; h <= numRecords; h++) { 104 | f.seek(PartRecordSize * (index[h].recNum - 1)); 105 | readPartFromFile(f).printPart(); 106 | System.out.printf("\n"); 107 | } 108 | } //end printFileInOrder 109 | 110 | } //end class P7_8CreateIndex 111 | 112 | class Part { 113 | String partNum, name; 114 | int amtInStock; 115 | double price; 116 | 117 | public Part(String pn, String n, int a, double p) { 118 | partNum = pn; 119 | name = n; 120 | amtInStock = a; 121 | price = p; 122 | } 123 | 124 | public void printPart() { 125 | System.out.printf("Part number: %s\n", partNum); 126 | System.out.printf("Part name: %s\n", name); 127 | System.out.printf("Amount in stock: %d\n", amtInStock); 128 | System.out.printf("Price: $%3.2f\n", price); 129 | } 130 | 131 | } //end class Part 132 | 133 | class Index { 134 | String partNum; 135 | int recNum; 136 | 137 | public Index(String p, int r) { 138 | partNum = p; 139 | recNum = r; 140 | } 141 | } //end class Index 142 | 143 | -------------------------------------------------------------------------------- /P8_1BinaryTreeTest.java: -------------------------------------------------------------------------------- 1 | // Program P8.1 2 | import java.io.*; 3 | import java.util.*; 4 | public class P8_1BinaryTreeTest { 5 | 6 | public static void main(String[] args) throws IOException { 7 | Scanner in = new Scanner(new FileReader("btree.in")); 8 | BinaryTree bt = new BinaryTree(in); 9 | System.out.printf("\nThe pre-order traversal is: "); 10 | bt.preOrder(); 11 | System.out.printf("\n\nThe in-order traversal is: "); 12 | bt.inOrder(); 13 | System.out.printf("\n\nThe post-order traversal is: "); 14 | bt.postOrder(); 15 | System.out.printf("\n\n"); 16 | in.close(); 17 | } // end main 18 | } //end class P8_1BinaryTreeTest 19 | 20 | //The NodeData class 21 | // class NodeData { 22 | // String word; 23 | // 24 | // public NodeData(String w) { 25 | // word = w; 26 | // } 27 | // 28 | // public void visit() { 29 | // System.out.printf("%s ", word); 30 | // } 31 | // } //end class NodeData 32 | // 33 | //// The TreeNode class 34 | // class TreeNode { 35 | // NodeData data; 36 | // TreeNode left, right; 37 | // 38 | // TreeNode(NodeData d) { 39 | // data = d; 40 | // left = right = null; 41 | // } 42 | // } 43 | // 44 | //// The BinaryTree class 45 | // class BinaryTree { 46 | // TreeNode root; 47 | // 48 | // public BinaryTree() { 49 | // root = null; 50 | // } 51 | // public BinaryTree(Scanner in) { 52 | // root = buildTree(in); 53 | // } 54 | // 55 | // public static TreeNode buildTree(Scanner in) { 56 | // String str = in.next(); 57 | // if (str.equals("@")) return null; 58 | // TreeNode p = new TreeNode(new NodeData(str)); 59 | // p.left = buildTree(in); 60 | // p.right = buildTree(in); 61 | // return p; 62 | // } //end buildTree 63 | // 64 | // public void preOrder() { 65 | // preOrderTraversal(root); 66 | // } 67 | // public void preOrderTraversal(TreeNode node) { 68 | // if (node!= null) { 69 | // node.data.visit(); 70 | // preOrderTraversal(node.left); 71 | // preOrderTraversal(node.right); 72 | // } 73 | // } //end preOrderTraversal 74 | // 75 | // public void inOrder() { 76 | // inOrderTraversal(root); 77 | // } 78 | // 79 | // public void inOrderTraversal(TreeNode node) { 80 | // if (node!= null) { 81 | // inOrderTraversal(node.left); 82 | // node.data.visit(); 83 | // inOrderTraversal(node.right); 84 | // } 85 | // } //end inOrderTraversal 86 | // 87 | // public void postOrder() { 88 | // postOrderTraversal(root); 89 | // } 90 | // 91 | // public void postOrderTraversal(TreeNode node) { 92 | // if (node!= null) { 93 | // postOrderTraversal(node.left); 94 | // postOrderTraversal(node.right); 95 | // node.data.visit(); 96 | // } 97 | // } //end postOrderTraversal 98 | // 99 | // } //end class BinaryTree 100 | 101 | 102 | -------------------------------------------------------------------------------- /P8_2WordFrequencyBST.java: -------------------------------------------------------------------------------- 1 | // Program P8.2 2 | import java.io.*; 3 | import java.util.*; 4 | public class P8_2WordFrequencyBST { 5 | static Scanner in; 6 | static PrintWriter out; 7 | 8 | public static void main(String[] args) throws IOException { 9 | in = new Scanner(new FileReader("wordFreq.in")); 10 | out = new PrintWriter(new FileWriter("wordFreq.out")); 11 | 12 | BinaryTree bst = new BinaryTree(); 13 | 14 | in.useDelimiter("[^a-zA-Z]+"); 15 | while (in.hasNext()) { 16 | String word = in.next().toLowerCase(); 17 | TreeNode node = bst.findOrInsert(new NodeData(word)); 18 | node.data.incrFreq(); 19 | } 20 | out.printf("\nWords Frequency\n\n"); 21 | bst.inOrder(); 22 | in.close(); out.close(); 23 | } // end main 24 | 25 | } //end class P8_2WordFrequencyBST 26 | 27 | class NodeData { 28 | String word; 29 | int freq; 30 | 31 | public NodeData(String w) { 32 | word = w; 33 | freq = 0; 34 | } 35 | public void incrFreq() { 36 | ++freq; 37 | } 38 | 39 | public int compareTo(NodeData d) { 40 | return this.word.compareTo(d.word); 41 | } 42 | 43 | public void visit() { 44 | P8_2WordFrequencyBST.out.printf("%-15s %2d\n", word, freq); 45 | } 46 | } //end class NodeData 47 | 48 | // The TreeNode class 49 | class TreeNode { 50 | NodeData data; 51 | TreeNode left, right; 52 | 53 | TreeNode(NodeData d) { 54 | data = d; 55 | left = right = null; 56 | } 57 | } 58 | 59 | // The BinaryTree class 60 | class BinaryTree { 61 | TreeNode root; 62 | 63 | public BinaryTree() { 64 | root = null; 65 | } 66 | public BinaryTree(Scanner in) { 67 | root = buildTree(in); 68 | } 69 | 70 | public static TreeNode buildTree(Scanner in) { 71 | String str = in.next(); 72 | if (str.equals("@")) return null; 73 | TreeNode p = new TreeNode(new NodeData(str)); 74 | p.left = buildTree(in); 75 | p.right = buildTree(in); 76 | return p; 77 | } //end buildTree 78 | 79 | public void preOrder() { 80 | preOrderTraversal(root); 81 | } 82 | public void preOrderTraversal(TreeNode node) { 83 | if (node!= null) { 84 | node.data.visit(); 85 | preOrderTraversal(node.left); 86 | preOrderTraversal(node.right); 87 | } 88 | } //end preOrderTraversal 89 | 90 | public void inOrder() { 91 | inOrderTraversal(root); 92 | } 93 | 94 | public void inOrderTraversal(TreeNode node) { 95 | if (node!= null) { 96 | inOrderTraversal(node.left); 97 | node.data.visit(); 98 | inOrderTraversal(node.right); 99 | } 100 | } //end inOrderTraversal 101 | 102 | public void postOrder() { 103 | postOrderTraversal(root); 104 | } 105 | 106 | public void postOrderTraversal(TreeNode node) { 107 | if (node!= null) { 108 | postOrderTraversal(node.left); 109 | postOrderTraversal(node.right); 110 | node.data.visit(); 111 | } 112 | } //end postOrderTraversal 113 | 114 | public TreeNode findOrInsert(NodeData d) { 115 | if (root == null) return root = new TreeNode(d); 116 | TreeNode curr = root; 117 | int cmp; 118 | while ((cmp = d.compareTo(curr.data)) != 0) { 119 | if (cmp < 0) { //try left 120 | if (curr.left == null) return curr.left = new TreeNode(d); 121 | curr = curr.left; 122 | } 123 | else { //try right 124 | if (curr.right == null) return curr.right = new TreeNode(d); 125 | curr = curr.right; 126 | } 127 | } 128 | //d is in the tree; return pointer to the node 129 | return curr; 130 | } //end findOrInsert 131 | 132 | 133 | } //end class BinaryTree 134 | -------------------------------------------------------------------------------- /P8_3BinarySearchTreeTest.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P8_3BinarySearchTreeTest.java -------------------------------------------------------------------------------- /P8_4LevelOrderTest.java: -------------------------------------------------------------------------------- 1 | // Program P8.4 2 | import java.io.*; 3 | import java.util.*; 4 | public class P8_4LevelOrderTest { 5 | public static void main(String[] args) throws IOException { 6 | 7 | Scanner in = new Scanner(new FileReader("btree.in")); 8 | BinaryTree bt = new BinaryTree(in); 9 | 10 | System.out.printf("\n\nThe level-order traversal is: "); 11 | bt.levelOrderTraversal(); 12 | System.out.printf("\n"); 13 | in.close(); 14 | } // end main 15 | 16 | } //end class P8_4LevelOrderTest 17 | 18 | class NodeData { 19 | String word; 20 | 21 | public NodeData(String w) { 22 | word = w; 23 | } 24 | 25 | public void visit() { 26 | System.out.printf("%s ", word); 27 | } 28 | } //end class NodeData 29 | 30 | class TreeNode { 31 | NodeData data; 32 | TreeNode left, right, parent; 33 | 34 | public TreeNode(NodeData d) { 35 | data = d; 36 | left = right = parent = null; 37 | } 38 | } //end class TreeNode 39 | 40 | //The BinaryTree class - only the methods relevant to this problem are shown 41 | class BinaryTree { 42 | TreeNode root; 43 | 44 | public BinaryTree() { 45 | root = null; 46 | } 47 | 48 | public BinaryTree(Scanner in) { 49 | root = buildTree(in); 50 | } 51 | 52 | public static TreeNode buildTree(Scanner in) { 53 | String str = in.next(); 54 | if (str.equals("@")) return null; 55 | TreeNode p = new TreeNode(new NodeData(str)); 56 | p.left = buildTree(in); 57 | p.right = buildTree(in); 58 | return p; 59 | } //end buildTree 60 | 61 | public void levelOrderTraversal() { 62 | Queue Q = new Queue(); 63 | Q.enqueue(new QueueData(root)); 64 | while (!Q.empty()) { 65 | QueueData temp = Q.dequeue(); 66 | temp.node.data.visit(); 67 | if (temp.node.left != null) Q.enqueue(new QueueData(temp.node.left)); 68 | if (temp.node.right != null) Q.enqueue(new QueueData(temp.node.right)); 69 | } 70 | } //end levelOrderTraversal 71 | 72 | } //end class BinaryTree 73 | 74 | class QueueData { 75 | TreeNode node; 76 | 77 | public QueueData(TreeNode n) { 78 | node = n; 79 | } 80 | } //end class QueueData 81 | 82 | class QNode { 83 | QueueData data; 84 | QNode next; 85 | 86 | public QNode(QueueData d) { 87 | data = d; 88 | next = null; 89 | } 90 | } //end class QNode 91 | 92 | class Queue { 93 | QNode head = null, tail = null; 94 | 95 | public boolean empty() { 96 | return head == null; 97 | } 98 | 99 | public void enqueue(QueueData nd) { 100 | QNode p = new QNode(nd); 101 | if (this.empty()) { 102 | head = p; 103 | tail = p; 104 | } 105 | else { 106 | tail.next = p; 107 | tail = p; 108 | } 109 | } //end enqueue 110 | 111 | public QueueData dequeue() { 112 | if (this.empty()) { 113 | System.out.printf("\nAttempt to remove from an empty queue\n"); 114 | System.exit(1); 115 | } 116 | QueueData hold = head.data; 117 | head = head.next; 118 | if (head == null) tail = null; 119 | return hold; 120 | } //end dequeue 121 | 122 | } //end class Queue 123 | -------------------------------------------------------------------------------- /P9_1HeapSortTest.java: -------------------------------------------------------------------------------- 1 | // Program P9.1 2 | import java.io.*; 3 | public class P9_1HeapSortTest { 4 | public static void main(String[] args) throws IOException { 5 | int[] num = {0, 37, 25, 43, 65, 48, 84, 73, 18, 79, 56, 69, 32}; 6 | int n = 12; 7 | heapSort(num, n); 8 | for (int h = 1; h <= n; h++) System.out.printf("%d ", num[h]); 9 | System.out.printf("\n"); 10 | } 11 | 12 | public static void heapSort(int[] num, int n) { 13 | //sort num[1] to num[n] 14 | //convert the array to a heap 15 | for (int k = n / 2; k >= 1; k--) siftDown(num[k], num, k, n); 16 | 17 | for (int k = n; k > 1; k--) { 18 | int item = num[k]; //extract current last item 19 | num[k] = num[1]; //move top of heap to current last node 20 | siftDown(item, num, 1, k-1); //restore heap properties from 1 to k-1 21 | } 22 | } //end heapSort 23 | 24 | public static void siftDown(int key, int[] num, int root, int last) { 25 | int bigger = 2 * root; 26 | while (bigger <= last) { //while there is at least one child 27 | if (bigger < last) //there is a right child as well; find the bigger 28 | if (num[bigger+1] > num[bigger]) bigger++; 29 | //'bigger' holds the index of the bigger child 30 | if (key >= num[bigger]) break; 31 | //key is smaller; promote num[bigger] 32 | num[root] = num[bigger]; 33 | root = bigger; 34 | bigger = 2 * root; 35 | } 36 | num[root] = key; 37 | } //end siftDown 38 | 39 | } //end class P9_1HeapSortTest 40 | 41 | -------------------------------------------------------------------------------- /P9_2SiftUpTest.java: -------------------------------------------------------------------------------- 1 | // Program P9.2 2 | import java.io.*; 3 | import java.util.*; 4 | public class P9_2SiftUpTest { 5 | final static int MaxHeapSize = 100; 6 | public static void main (String[] args) throws IOException { 7 | Scanner in = new Scanner(new FileReader("heap.in")); 8 | int[] num = new int[MaxHeapSize + 1]; 9 | int n = 0, number; 10 | 11 | while (in.hasNextInt()) { 12 | number = in.nextInt(); 13 | if (n < MaxHeapSize) { //check if array has room 14 | num[++n] = number; 15 | siftUp(num, n); 16 | } 17 | } 18 | 19 | for (int h = 1; h <= n; h++) System.out.printf("%d ", num[h]); 20 | System.out.printf("\n"); 21 | in.close(); 22 | } //end main 23 | 24 | public static void siftUp(int[] heap, int n) { 25 | //heap[1] to heap[n-1] contain a heap 26 | //sifts up the value in heap[n] so that heap[1..n] contains a heap 27 | int siftItem = heap[n]; 28 | int child = n; 29 | int parent = child / 2; 30 | while (parent > 0) { 31 | if (siftItem <= heap[parent]) break; 32 | heap[child] = heap[parent]; //move down parent 33 | child = parent; 34 | parent = child / 2; 35 | } 36 | heap[child] = siftItem; 37 | } //end siftUp 38 | 39 | } //end class P9_2SiftUpTest 40 | -------------------------------------------------------------------------------- /P9_3QuicksortTest.java: -------------------------------------------------------------------------------- 1 | // Program P9.3 2 | import java.io.*; 3 | public class P9_3QuicksortTest { 4 | 5 | public static void main(String[] args) throws IOException { 6 | int[] num = {0, 37, 25, 43, 65, 48, 84, 73, 18, 79, 56, 69, 32}; 7 | int n = 12; 8 | quicksort(num, 1, n); 9 | for (int h = 1; h <= n; h++) System.out.printf("%d ", num[h]); 10 | System.out.printf("\n"); 11 | } 12 | 13 | public static void quicksort(int[] A, int lo, int hi) { 14 | //sorts A[lo] to A[hi] in ascending order 15 | if (lo < hi) { 16 | int dp = partition1(A, lo, hi); 17 | quicksort(A, lo, dp-1); 18 | quicksort(A, dp+1, hi); 19 | } 20 | } //end quicksort 21 | 22 | public static int partition1(int[] A, int lo, int hi) { 23 | //partition A[lo] to A[hi] using A[lo] as the pivot 24 | int pivot = A[lo]; 25 | int lastSmall = lo; 26 | for (int j = lo + 1; j <= hi; j++) 27 | if (A[j] < pivot) { 28 | ++lastSmall; 29 | swap(A, lastSmall, j); 30 | } 31 | //end for 32 | swap(A, lo, lastSmall); 33 | return lastSmall; //return the division point 34 | } //end partition1 35 | 36 | public static void swap(int[] list, int i, int j) { 37 | //swap list[i] and list[j] 38 | int hold = list[i]; 39 | list[i] = list[j]; 40 | list[j] = hold; 41 | } 42 | 43 | } //end class P9_3QuicksortTest 44 | 45 | -------------------------------------------------------------------------------- /P9_4Quicksort3Test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P9_4Quicksort3Test.class -------------------------------------------------------------------------------- /P9_4Quicksort3Test.java: -------------------------------------------------------------------------------- 1 | // Program P9.4 2 | import java.io.*; 3 | import java.util.*; 4 | public class P9_4Quicksort3Test { 5 | final static int MaxNumbers = 100; 6 | public static void main (String[] args) throws IOException { 7 | Scanner in = new Scanner(new FileReader("quick.in")); 8 | int[] num = new int[MaxNumbers+1]; 9 | int n = 0, number; 10 | 11 | while (in.hasNextInt()) { 12 | number = in.nextInt(); 13 | if (n < MaxNumbers) num[++n] = number; //store if array has room 14 | } 15 | 16 | quicksort3(num, 1, n); 17 | for (int h = 1; h <= n; h++) { 18 | System.out.printf("%d ", num[h]); 19 | if (h % 10 == 0) System.out.printf("\n"); //print 10 numbers per line 20 | } 21 | System.out.printf("\n"); 22 | } //end main 23 | 24 | public static void quicksort3(int[] A, int lo, int hi) { 25 | Stack S = new Stack(); 26 | S.push(new NodeData(lo, hi)); 27 | int stackItems = 1, maxStackItems = 1; 28 | while (!S.empty()) { 29 | --stackItems; 30 | NodeData d = S.pop(); 31 | if (d.left < d.right) { //if the sublist is > 1 element 32 | int dp = partition2(A, d.left, d.right); 33 | if (dp - d.left + 1 < d.right - dp) { //compare lengths of sublists 34 | S.push(new NodeData(dp+1, d.right)); 35 | S.push(new NodeData(d.left, dp)); 36 | } 37 | else { 38 | S.push(new NodeData(d.left, dp)); 39 | S.push(new NodeData(dp+1, d.right)); 40 | } 41 | stackItems += 2; //two items added to stack 42 | } //end if 43 | if (stackItems > maxStackItems) maxStackItems = stackItems; 44 | } //end while 45 | System.out.printf("Max stack items: %d\n\n", maxStackItems); 46 | } //end quicksort3 47 | 48 | public static int partition2(int[] A, int lo, int hi) { 49 | //return dp such that A[lo..dp] <= A[dp+1..hi] 50 | int pivot = A[lo]; 51 | --lo; ++hi; 52 | while (lo < hi) { 53 | do --hi; while (A[hi] > pivot); 54 | do ++lo; while (A[lo] < pivot); 55 | if (lo < hi) swap(A, lo, hi); 56 | } 57 | return hi; 58 | } //end partition2 59 | 60 | public static void swap(int[] list, int i, int j) { 61 | //swap list[i] and list[j] 62 | int hold = list[i]; 63 | list[i] = list[j]; 64 | list[j] = hold; 65 | } //end swap 66 | 67 | } //end class P9_4Quicksort3Test 68 | 69 | class NodeData { 70 | int left, right; 71 | 72 | public NodeData(int a, int b) { 73 | left = a; 74 | right = b; 75 | } 76 | 77 | public static NodeData getRogueValue() {return new NodeData(-1, -1);} 78 | 79 | } //end class NodeData 80 | 81 | class Node { 82 | NodeData data; 83 | Node next; 84 | 85 | public Node(NodeData d) { 86 | data = d; 87 | next = null; 88 | } 89 | } //end class Node 90 | 91 | class Stack { 92 | Node top = null; 93 | 94 | public boolean empty() { 95 | return top == null; 96 | } 97 | 98 | public void push(NodeData nd) { 99 | Node p = new Node(nd); 100 | p.next = top; 101 | top = p; 102 | } //end push 103 | 104 | public NodeData pop() { 105 | if (this.empty())return NodeData.getRogueValue(); 106 | NodeData hold = top.data; 107 | top = top.next; 108 | return hold; 109 | } //end pop 110 | 111 | } //end class Stack 112 | 113 | -------------------------------------------------------------------------------- /P9_5ShellSortTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/P9_5ShellSortTest.class -------------------------------------------------------------------------------- /P9_5ShellSortTest.java: -------------------------------------------------------------------------------- 1 | // Program P9.5 2 | import java.io.*; 3 | import java.util.*; 4 | public class P9_5ShellSortTest { 5 | final static int MaxNumbers = 100; 6 | public static void main (String[] args) throws IOException { 7 | Scanner in = new Scanner(new FileReader("shell.in")); 8 | int[] num = new int[MaxNumbers+1]; 9 | int n = 0, number; 10 | 11 | while (in.hasNextInt()) { 12 | number = in.nextInt(); 13 | if (n < MaxNumbers) num[++n] = number; //store if array has room 14 | } 15 | 16 | //perform Shell sort with increments 8, 3 and 1 17 | hsort(num, n, 8); 18 | hsort(num, n, 3); 19 | hsort(num, n, 1); 20 | 21 | for (int h = 1; h <= n; h++) { 22 | System.out.printf("%d ", num[h]); 23 | if (h % 10 == 0) System.out.printf("\n"); //print 10 numbers per line 24 | } 25 | System.out.printf("\n"); 26 | } //end main 27 | 28 | public static void hsort(int[] A, int n, int h) { 29 | for (int k = h + 1; k <= n; k++) { 30 | int j = k - h; 31 | int key = A[k]; 32 | while (j > 0 && key < A[j]) { 33 | A[j + h] = A[j]; 34 | j = j - h; 35 | } 36 | A[j + h] = key; 37 | } 38 | } //end hsort 39 | 40 | } //end class P9_5ShellSortTest 41 | 42 | -------------------------------------------------------------------------------- /Part.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/Part.class -------------------------------------------------------------------------------- /Person.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/Person.class -------------------------------------------------------------------------------- /QNode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/QNode.class -------------------------------------------------------------------------------- /Queue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/Queue.class -------------------------------------------------------------------------------- /QueueData.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/QueueData.class -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Advanced Topics in Java*](http://www.apress.com/9781430266198) by Noel Kalicharan (Apress, 2014). 4 | 5 | ![Cover image](9781430266198.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /Stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/Stack.class -------------------------------------------------------------------------------- /TreeNode.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/TreeNode.class -------------------------------------------------------------------------------- /VoteCount.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/VoteCount.class -------------------------------------------------------------------------------- /WordInfo.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/WordInfo.class -------------------------------------------------------------------------------- /btree.in: -------------------------------------------------------------------------------- 1 | C E @ B F @ @ @ G A @ @ N J @ @ @ 2 | 3 | hat din bun @ @ fan @ @ rum kit @ @ win @ @ 4 | 5 | C E F @ H @ @ B @ @ G A @ @ N J @ @ K @ @ 6 | -------------------------------------------------------------------------------- /compfile1.txt: -------------------------------------------------------------------------------- 1 | one and one are two 2 | two and two are four 3 | three and three are six 4 | four and four are eight 5 | five and five are ten 6 | six and six are twelve 7 | 8 | -------------------------------------------------------------------------------- /compfile2.txt: -------------------------------------------------------------------------------- 1 | one and one are two 2 | two and two are four 3 | three and three are six 4 | four and four are eight 5 | this is the fifth line 6 | six and six are twelve 7 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! -------------------------------------------------------------------------------- /heap.in: -------------------------------------------------------------------------------- 1 | 37 25 43 65 48 84 73 18 79 56 69 32 2 | -------------------------------------------------------------------------------- /index.bin: -------------------------------------------------------------------------------- 1 | dNOPARTBLJ375DKP080FLT015GSF555PKL070NOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPARTNOPART -------------------------------------------------------------------------------- /maze.in: -------------------------------------------------------------------------------- 1 | 8 10 6 6 2 | 1 1 1 1 1 1 1 1 1 1 3 | 1 0 1 0 0 0 1 0 0 1 4 | 1 0 1 0 1 0 1 1 0 1 5 | 1 0 0 0 1 0 0 0 0 1 6 | 1 0 1 1 1 1 1 1 0 1 7 | 1 0 1 0 1 0 1 1 0 0 8 | 1 0 0 0 0 0 1 1 0 1 9 | 1 1 1 1 1 1 1 1 1 1 10 | -------------------------------------------------------------------------------- /maze.out: -------------------------------------------------------------------------------- 1 | ########## 2 | # #xxx# # 3 | # #x#x## # 4 | #xxx#xxxx# 5 | #x######x# 6 | #x# #S##xx 7 | #xxxxx## # 8 | ########## 9 | -------------------------------------------------------------------------------- /num.bin: -------------------------------------------------------------------------------- 1 | /`IYR ' -------------------------------------------------------------------------------- /num.txt: -------------------------------------------------------------------------------- 1 | 25 18 47 96 73 89 82 13 39 0 2 | -------------------------------------------------------------------------------- /numbers.in: -------------------------------------------------------------------------------- 1 | 24 57 35 37 31 98 85 47 60 32 48 82 16 96 87 46 53 92 71 56 2 | 73 85 47 46 22 40 95 32 54 67 31 44 74 40 58 42 88 29 78 87 3 | 45 13 73 29 84 48 85 29 66 73 87 17 10 83 95 25 44 93 32 39 4 | -------------------------------------------------------------------------------- /orgs.in: -------------------------------------------------------------------------------- 1 | 5 7 2 | 0 1 0 1 1 1 0 3 | 0 0 1 1 0 0 0 4 | 1 1 0 1 0 0 1 5 | 1 0 1 0 0 1 1 6 | 1 1 0 0 0 1 0 7 | -------------------------------------------------------------------------------- /orgs.out: -------------------------------------------------------------------------------- 1 | 2 | Number of organisms = 5 3 | 4 | Position of organisms are shown below 5 | 6 | 0 1 0 2 2 2 0 7 | 0 0 2 2 0 0 0 8 | 3 3 0 2 0 0 4 9 | 3 0 5 0 0 4 4 10 | 3 3 0 0 0 4 0 11 | -------------------------------------------------------------------------------- /output.txt: -------------------------------------------------------------------------------- 1 | 2 | Words Frequency 3 | 4 | a 1 5 | achieve 1 6 | and 2 7 | avoid 1 8 | be 3 9 | believe 1 10 | but 1 11 | can 2 12 | conceive 1 13 | criticism 1 14 | do 1 15 | is 1 16 | it 1 17 | mind 1 18 | not 1 19 | nothing 3 20 | of 1 21 | one 1 22 | only 1 23 | rather 1 24 | say 1 25 | strive 1 26 | success 1 27 | the 1 28 | there 1 29 | to 3 30 | value 1 31 | way 1 32 | whatever 1 33 | -------------------------------------------------------------------------------- /parts.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/adv-topics-in-java/119ad473f19a7188b96165f52cd31bf7ec256f15/parts.bin -------------------------------------------------------------------------------- /parts.txt: -------------------------------------------------------------------------------- 1 | PKL070 Park-Lens 8 6.50 2 | BLJ375 Ball-Joint 12 11.95 3 | PKL070 Park-Lens 8 6.50 4 | FLT015 Oil-Filter 23 7.95 5 | DKP080 Disc-Pads 16 9.99 6 | GSF555 Gas-Filter 9 4.50 7 | FLT015 Oil-Filter 23 7.95 8 | END 9 | -------------------------------------------------------------------------------- /passage.txt: -------------------------------------------------------------------------------- 1 | Strive not to be a success, but rather to be of value. 2 | Whatever the mind can conceive and believe, it can achieve. 3 | There is only one way to avoid criticism: do nothing, say nothing, and be nothing. 4 | 5 | -------------------------------------------------------------------------------- /quick.in: -------------------------------------------------------------------------------- 1 | 43 25 66 37 65 48 84 73 60 79 56 69 32 87 23 99 85 28 14 78 39 51 44 35 2 | 46 90 26 96 88 31 17 81 42 54 93 38 22 63 40 68 50 86 75 21 77 58 72 19 3 | -------------------------------------------------------------------------------- /results.txt: -------------------------------------------------------------------------------- 1 | Invalid vote: 8 2 | Invalid vote: 9 3 | 4 | Number of voters: 30 5 | Number of valid votes: 28 6 | Number of spoilt votes: 2 7 | 8 | Candidate Score 9 | 10 | Nirvan Singh 4 11 | Denise Duncan 2 12 | Avasa Tawari 6 13 | Torrique Granger 4 14 | Saskia Kalicharan 6 15 | Dawren Greenidge 3 16 | Jordon Cato 3 17 | 18 | The winner(s) 19 | Avasa Tawari 20 | Saskia Kalicharan 21 | -------------------------------------------------------------------------------- /shell.in: -------------------------------------------------------------------------------- 1 | 43 25 66 37 65 48 84 73 60 79 56 69 32 87 23 99 85 28 14 78 39 51 44 35 2 | 46 90 26 96 88 31 17 81 42 54 93 38 22 63 40 68 50 86 75 21 77 58 72 19 3 | -------------------------------------------------------------------------------- /votes.txt: -------------------------------------------------------------------------------- 1 | Nirvan Singh 2 | Denise Duncan 3 | Avasa Tawari 4 | Torrique Granger 5 | Saskia Kalicharan 6 | Dawren Greenidge 7 | Jordon Cato 8 | 9 | 3 1 6 5 4 3 5 3 5 3 2 8 1 6 7 7 3 5 10 | 6 9 3 4 7 1 2 4 5 5 1 4 0 11 | -------------------------------------------------------------------------------- /wordFreq.in: -------------------------------------------------------------------------------- 1 | If you can trust yourself when all men doubt you; 2 | If you can dream - and not make dreams your master; 3 | -------------------------------------------------------------------------------- /wordFreq.out: -------------------------------------------------------------------------------- 1 | 'and' not added to table 2 | 'not' not added to table 3 | 'make' not added to table 4 | 'dreams' not added to table 5 | 'your' not added to table 6 | 'master' not added to table 7 | 8 | Words Frequency 9 | 10 | all 1 11 | can 2 12 | doubt 1 13 | dream 1 14 | if 2 15 | men 1 16 | trust 1 17 | when 1 18 | you 3 19 | yourself 1 20 | -------------------------------------------------------------------------------- /words.in: -------------------------------------------------------------------------------- 1 | mac tee ode era ria lea vim 2 | --------------------------------------------------------------------------------