Bladeren bron

raw entry

Kr Younger 6 jaren geleden
commit
535948df0e
43 gewijzigde bestanden met toevoegingen van 3603 en 0 verwijderingen
  1. 153
    0
      CodeSamples/GenericList.java
  2. 152
    0
      CodeSamples/LinkedList/IList.java
  3. 121
    0
      CodeSamples/codeSamples/AirlineProblem.java
  4. 149
    0
      CodeSamples/codeSamples/ArrayExamples.java
  5. 53
    0
      CodeSamples/codeSamples/BinaryConverter.java
  6. 23
    0
      CodeSamples/codeSamples/CallingMethodsInSameClass.java
  7. 74
    0
      CodeSamples/codeSamples/CreateASet.java
  8. 103
    0
      CodeSamples/codeSamples/DemoClass.java
  9. 126
    0
      CodeSamples/codeSamples/Die.java
  10. 183
    0
      CodeSamples/codeSamples/EightQueens.java
  11. 69
    0
      CodeSamples/codeSamples/EnhancedFor.java
  12. 15
    0
      CodeSamples/codeSamples/Factorial.java
  13. 75
    0
      CodeSamples/codeSamples/FilterExample.java
  14. 134
    0
      CodeSamples/codeSamples/FreqTableExampleOriginal.java
  15. 163
    0
      CodeSamples/codeSamples/GenericList.java
  16. 208
    0
      CodeSamples/codeSamples/GenericListVersion2.java
  17. 9
    0
      CodeSamples/codeSamples/HelloWorld.java
  18. 12
    0
      CodeSamples/codeSamples/IntListTesterVer1.java
  19. 44
    0
      CodeSamples/codeSamples/IntListTesterVer2.java
  20. 41
    0
      CodeSamples/codeSamples/IntListVer1.java
  21. 131
    0
      CodeSamples/codeSamples/IntListVer2.java
  22. 190
    0
      CodeSamples/codeSamples/IntListVer3.java
  23. 81
    0
      CodeSamples/codeSamples/Life.java
  24. 147
    0
      CodeSamples/codeSamples/LinkedList.java
  25. 75
    0
      CodeSamples/codeSamples/ListNode.java
  26. 20
    0
      CodeSamples/codeSamples/MineSweeper.java
  27. 35
    0
      CodeSamples/codeSamples/ObjectVarsAsParameters.java
  28. 102
    0
      CodeSamples/codeSamples/PrimeEx.java
  29. 33
    0
      CodeSamples/codeSamples/PrimitiveParameters.java
  30. 18
    0
      CodeSamples/codeSamples/ReadAndPrintScores.java
  31. 110
    0
      CodeSamples/codeSamples/RecursionExampleDirectory.java
  32. 12
    0
      CodeSamples/codeSamples/ScannerAndKeyboard.java
  33. 34
    0
      CodeSamples/codeSamples/SimpleWordCounter.java
  34. 22
    0
      CodeSamples/codeSamples/SortedIntList.java
  35. 27
    0
      CodeSamples/codeSamples/StringExample.java
  36. 26
    0
      CodeSamples/codeSamples/URLExpSimple.java
  37. 46
    0
      CodeSamples/codeSamples/UnsortedHashSet.java
  38. 136
    0
      CodeSamples/codeSamples/UnsortedSetTest.java
  39. 25
    0
      CodeSamples/codeSamples/WriteToFile.java
  40. 19
    0
      CodeSamples/codeSamples/airlines.txt
  41. 363
    0
      CodeSamples/utilities/Stopwatch.html
  42. 43
    0
      CodeSamples/utilities/Stopwatch.java
  43. 1
    0
      README.md

+ 153
- 0
CodeSamples/GenericList.java Bestand weergeven

@@ -0,0 +1,153 @@
1
+package Fall0811;
2
+import java.util.Iterator;
3
+
4
+public class GenericList<E> implements Iterable<E>{
5
+ // class constant
6
+    private static final int DEFAULT_CAP = 10;
7
+ 
8
+    // instance variables
9
+    protected E[] container; // the array is NOT the list
10
+    private int listSize;
11
+    
12
+    public Iterator<E> iterator(){
13
+        return new GenListIterator();
14
+    }
15
+    
16
+    // inner class
17
+    private class GenListIterator implements Iterator<E>{
18
+        private int indexOfNextElement;
19
+        private boolean okToRemove;
20
+        
21
+        private GenListIterator(){
22
+            indexOfNextElement = 0;
23
+            okToRemove = false;
24
+        }
25
+        
26
+        public boolean hasNext(){
27
+            return indexOfNextElement < size();
28
+        }
29
+        
30
+        public E next(){
31
+            assert hasNext();
32
+            okToRemove = true;
33
+            indexOfNextElement++;
34
+            return container[indexOfNextElement - 1];
35
+        }
36
+        
37
+        public void remove(){
38
+            assert okToRemove;
39
+            okToRemove = false;
40
+            indexOfNextElement--;
41
+            GenericList.this.remove(indexOfNextElement);
42
+        }
43
+        
44
+    }
45
+    
46
+    public boolean equals(Object obj){
47
+        assert this != null;
48
+        if(obj == null)
49
+            return false;
50
+        else if (this == obj)
51
+            return true;
52
+        else if( this.getClass() != obj.getClass() )
53
+            return false;
54
+        else{
55
+            // obj is a non null GenericList
56
+            GenericList list = (GenericList)obj;
57
+            if( list.size() != size() )
58
+                return false;
59
+            for(int i = 0; i < size(); i++)
60
+                if( (get(i) == null && list.get(i) != null) || !get(i).equals(list.get(i)) )
61
+                    return false;
62
+            return true;
63
+        }
64
+        
65
+            
66
+    }
67
+    
68
+
69
+    // creates an empty IntList
70
+    public GenericList(){
71
+        this(DEFAULT_CAP);
72
+    }
73
+
74
+    // pre: initialCap >= 0
75
+    public GenericList(int initialCap){
76
+        assert initialCap >= 0 : "failed precondition";
77
+        container = (E[])(new Object[initialCap]);
78
+        listSize = 0;        
79
+    }
80
+    
81
+    public void insertAll(int pos, GenericList<E> otherList){
82
+        
83
+        for(int i = 0; i < otherList.listSize; i++){
84
+            this.insert(pos + i, otherList.container[i]);
85
+        }
86
+    }
87
+    
88
+    // pre: 0 <= pos < size()
89
+    public E remove(int pos){
90
+        E result = container[pos];
91
+        listSize--;
92
+        for(int index = pos; index < size(); index++){
93
+            container[index] = container[index + 1];
94
+        }
95
+        container[listSize] = null;
96
+        return result;
97
+    }
98
+    
99
+    // pre: 0 <= pos <= size()
100
+    public void insert(int pos, E element){
101
+        assert 0 <= pos && pos <= size();
102
+        if( size() == container.length )
103
+            resize();
104
+        for(int index = size(); index > pos; index--){
105
+            assert index > 0;
106
+            container[index] = container[index - 1];
107
+        }
108
+        container[pos] = element;
109
+        listSize++;
110
+    }
111
+    
112
+    // get size of list
113
+    public int size(){
114
+        return listSize;
115
+    }
116
+    
117
+    // access elements
118
+    // pre: 0 <= position < size()
119
+    public E get(int position){
120
+        assert 0 <= position && position < size();
121
+        return container[position];
122
+    }
123
+    
124
+    // pre: none
125
+    public void add(E element){    
126
+        insert(size(), element);
127
+    }
128
+
129
+    private void resize() {
130
+        E[] temp = (E[])(new Object[container.length * 2 + 1]);
131
+        System.arraycopy(container, 0, temp, 0, size());
132
+        container = temp;
133
+    }
134
+    
135
+    public String toString(){
136
+        StringBuffer result = new StringBuffer("[");
137
+        final int LIMIT = size() - 1;
138
+        for(int i = 0; i < LIMIT; i++){
139
+            if( this == this.get(i) )
140
+                result.append("this list");
141
+            else{
142
+                result.append(get(i));
143
+            }
144
+            result.append(", ");
145
+        }
146
+        if( size() != 0)
147
+            result.append(get(size() - 1));
148
+        result.append("]");
149
+        return result.toString();
150
+    }
151
+   
152
+}
153
+

+ 152
- 0
CodeSamples/LinkedList/IList.java Bestand weergeven

@@ -0,0 +1,152 @@
1
+import java.util.Iterator;
2
+
3
+/**
4
+ * Interface for a simple List. Random access to all items in the list is provided. 
5
+ * The numbering of elements in the list begins at 0.
6
+ *
7
+ */
8
+public interface IList<E> extends Iterable<E>{
9
+
10
+	/**
11
+	 * Add an item to the end of this list.
12
+	 * <br>pre: none
13
+	 * <br>post: size() = old size() + 1, get(size() - 1) = item
14
+	 * @param item the data to be added to the end of this list
15
+	 */
16
+	void add(E item);
17
+
18
+	/**
19
+	 * Insert an item at a specified position in the list.
20
+	 * <br>pre: 0 <= pos <= size()
21
+	 * <br>post: size() = old size() + 1, get(pos) = item, all elements in
22
+	 * the list with a positon >= pos have a position = old position + 1
23
+	 * @param pos the position to insert the data at in the list
24
+	 * @param item the data to add to the list
25
+	*/
26
+	void insert(int pos, E item);
27
+
28
+	/**
29
+	 * Change the data at the specified position in the list.
30
+	 * the old data at that position is returned.
31
+	 * <br>pre: 0 <= pos < size()
32
+	 * <br>post: get(pos) = item, return the
33
+	 * old get(pos)
34
+     * @param pos the position in the list to overwrite	 
35
+	 * @param item the new item that will overwrite the old item
36
+	 * @return the old data at the specified position
37
+	 */
38
+	E set(int pos, E item);
39
+
40
+	/**
41
+	 * Get an element from the list.
42
+	 * <br>pre: 0 <= pos < size()
43
+	 * <br>post: return the item at pos
44
+	 * @param pos specifies which element to get
45
+	 * @return the element at the specified position in the list
46
+	 */
47
+	E get(int pos);
48
+
49
+
50
+	/**
51
+	 * Remove an element in the list based on position.
52
+	 * <br>pre: 0 <= pos < size()
53
+	 * <br>post: size() = old size() - 1, all elements of
54
+	 * list with a positon > pos have a position = old position - 1
55
+	 * @param pos the position of the element to remove from the list
56
+	 * @return the data at position pos
57
+	 */
58
+	E remove(int pos);
59
+	
60
+	/**
61
+	 * Remove the first occurrence of obj in this list.
62
+	 * Return <tt>true</tt> if this list changed as a result of this call, <tt>false</tt> otherwise.
63
+	 * <br>pre: none
64
+	 * <br>post: if obj is in this list the first occurence has been removed and size() = old size() - 1. 
65
+	 * If obj is not present the list is not altered in any way.
66
+	 * @param obj The item to remove from this list.
67
+	 * @return Return <tt>true</tt> if this list changed as a result of this call, <tt>false</tt> otherwise.
68
+	 */
69
+	boolean remove(E obj);
70
+	
71
+	/**
72
+	 * Return a sublist of elements in this list from <tt>start</tt> inclusive to <tt>stop</tt> exclusive.
73
+	 * This list is not changed as a result of this call.
74
+	 * <br>pre: <tt>0 <= start < size(), start <= stop <= size()</tt>
75
+	 * <br>post: return a list whose size is stop - start and contains the elements at positions start through stop - 1 in this list.
76
+	 * @param start index of the first element of the sublist.
77
+	 * @param stop stop - 1 is the index of the last element of the sublist.
78
+	 * @return a list with <tt>stop - start</tt> elements, The elements are from positions <tt>start</tt> inclusive to
79
+	 * <tt>stop</tt> exclusive in this list.
80
+	 */
81
+	IList<E> getSubList(int start, int stop);
82
+
83
+	/**
84
+	 * Return the size of this list. In other words the number of elements in this list.
85
+	 * <br>pre: none
86
+	 * <br>post: return the number of items in this list
87
+	 * @return the number of items in this list
88
+	 */
89
+	int size();
90
+
91
+	/**
92
+	 * Find the position of an element in the list.
93
+	 * <br>pre: none
94
+	 * <br>post: return the index of the first element equal to item
95
+	 * or -1 if item is not present
96
+	 * @param item the element to search for in the list
97
+	 * @return return the index of the first element equal to item or a -1 if item is not present
98
+	 */
99
+	int indexOf(E item);
100
+
101
+	/**
102
+	 * find the position of an element in the list starting at a specified position.
103
+	 * <br>pre: 0 <= pos < size()
104
+	 * <br>post: return the index of the first element equal to item starting at pos
105
+	 * or -1 if item is not present from position pos onward
106
+	 * @param item the element to search for in the list
107
+	 * @param pos the position in the list to start searching from
108
+	 * @return starting from the specified position return the index of the first element equal to item or a -1 if item is not present between pos and the end of the list
109
+	 */
110
+	int indexOf(E item, int pos);
111
+
112
+	/**
113
+	 * return the list to an empty state.
114
+	 * <br>pre: none
115
+	 * <br>post: size() = 0
116
+	 */
117
+	void makeEmpty();
118
+
119
+	/**
120
+	* return an Iterator for this list.
121
+	* <br>pre: none
122
+	* <br>post: return an Iterator object for this List
123
+	*/
124
+    Iterator<E> iterator();
125
+
126
+    /**
127
+     * Remove all elements in this list from <tt>start</tt> inclusive to <tt>stop</tt> exclusive.
128
+     * <br>pre: <tt>0 <= start < size(), start <= stop <= size()</tt>
129
+     * <br>post: <tt>size() = old size() - (stop - start)</tt>
130
+     * @param start position at beginning of range of elements to be removed
131
+     * @param stop stop - 1 is the position at the end of the range of elements to be removed
132
+     */
133
+    void removeRange(int start, int stop);
134
+    
135
+    /**
136
+     * Return a String version of this list enclosed in
137
+     * square brackets, []. Elements are in
138
+     * are in order based on position in the 
139
+     * list with the first element
140
+     * first. Adjacent elements are seperated by comma's
141
+     * @return a String representation of this IList
142
+     */
143
+    public String toString();
144
+    
145
+    /**
146
+     * Determine if this IList is equal to other. Two
147
+     * ILists are equal if they contain the same elements
148
+     * in the same order.
149
+     * @return true if this IList is equal to other, false otherwise
150
+     */
151
+    public boolean equals(Object other);
152
+}

+ 121
- 0
CodeSamples/codeSamples/AirlineProblem.java Bestand weergeven

@@ -0,0 +1,121 @@
1
+import java.util.ArrayList;
2
+import java.util.Scanner;
3
+import java.io.File;
4
+import java.io.IOException;
5
+import java.util.Arrays;
6
+
7
+public class AirlineProblem {
8
+
9
+    public static void main(String[] args){
10
+        Scanner scannerToReadAirlines = null;
11
+        try{
12
+            scannerToReadAirlines = new Scanner(new File("airlines.txt"));
13
+        }
14
+        catch(IOException e){
15
+            System.out.println("Could not connect to file airlines.txt.");
16
+            System.exit(0);
17
+        }
18
+        if(scannerToReadAirlines != null){
19
+            ArrayList<Airline> airlinesPartnersNetwork = new ArrayList<Airline>();
20
+            Airline newAirline;
21
+            String lineFromFile;
22
+            String[] airlineNames;
23
+            
24
+            while( scannerToReadAirlines.hasNext() ){
25
+                lineFromFile = scannerToReadAirlines.nextLine();
26
+                airlineNames = lineFromFile.split(",");
27
+                newAirline = new Airline(airlineNames);
28
+                airlinesPartnersNetwork.add( newAirline );
29
+            }
30
+            System.out.println(airlinesPartnersNetwork);
31
+            Scanner keyboard = new Scanner(System.in);
32
+            System.out.print("Enter airline miles are on: ");
33
+            String start = keyboard.nextLine();
34
+            System.out.print("Enter goal airline: ");
35
+            String goal = keyboard.nextLine();
36
+            ArrayList<String> pathForMiles = new ArrayList<String>();
37
+            ArrayList<String> airlinesVisited = new ArrayList<String>();
38
+            if( canRedeem(start, goal, pathForMiles, airlinesVisited, airlinesPartnersNetwork))
39
+                System.out.println("Path to redeem miles: " + pathForMiles);
40
+            else
41
+                System.out.println("Cannot convert miles from " + start + " to " + goal + ".");
42
+        }
43
+    }
44
+    
45
+    private static boolean canRedeem(String current, String goal,
46
+            ArrayList<String> pathForMiles, ArrayList<String> airlinesVisited,
47
+            ArrayList<Airline> network){
48
+        if(current.equals(goal)){
49
+            //base case 1, I have found a path!
50
+            pathForMiles.add(current);
51
+            return true;
52
+        }
53
+        else if(airlinesVisited.contains(current))
54
+            // base case 2, I have already been here
55
+            // don't go into a cycle
56
+            return false;
57
+        else{
58
+            // I have not been here and it isn't
59
+            // the goal so check its partners
60
+            // now I have been here
61
+            airlinesVisited.add(current);
62
+            
63
+            // add this to the path
64
+            pathForMiles.add(current);
65
+            
66
+            // find this airline in the network
67
+            int pos = -1;
68
+            int index = 0;
69
+            while(pos == -1 && index < network.size()){
70
+                if(network.get(index).getName().equals(current))
71
+                    pos = index;
72
+                index++;
73
+            }
74
+            //if not in the network, no partners
75
+            if( pos == - 1)
76
+                return false;
77
+            
78
+            // loop through partners
79
+            index = 0;
80
+            String[] partners = network.get(pos).getPartners();
81
+            boolean foundPath = false;
82
+            while( !foundPath && index < partners.length){
83
+                foundPath = canRedeem(partners[index], goal, pathForMiles, airlinesVisited, network);
84
+                index++;
85
+            }
86
+            if( !foundPath )
87
+                pathForMiles.remove( pathForMiles.size() - 1);
88
+            return foundPath;
89
+        }
90
+    }
91
+
92
+    private static class Airline{
93
+        private String name;
94
+        private ArrayList<String> partners;
95
+        
96
+        //pre: data != null, data.length > 0
97
+        public Airline(String[] data){
98
+            assert data != null && data.length > 0 : "Failed precondition";
99
+            name = data[0];
100
+            partners = new ArrayList<String>();
101
+            for(int i = 1; i < data.length; i++)
102
+                partners.add( data[i] );
103
+        }
104
+        
105
+        public String[] getPartners(){
106
+            return partners.toArray(new String[partners.size()]);
107
+        }
108
+        
109
+        public boolean isPartner(String name){
110
+            return partners.contains(name);
111
+        }
112
+        
113
+        public String getName(){
114
+            return name;
115
+        }
116
+        
117
+        public String toString(){
118
+            return name + ", partners: " + partners;
119
+        }
120
+    }
121
+}

+ 149
- 0
CodeSamples/codeSamples/ArrayExamples.java Bestand weergeven

@@ -0,0 +1,149 @@
1
+//Mike Scott
2
+//examples of array manipulations
3
+
4
+public class ArrayExamples
5
+{	public static void main(String[] args)
6
+	{	int[] list = {1, 2, 3, 4, 1, 2, 3};
7
+		findAndPrintPairs(list, 5);
8
+		bubblesort(list);
9
+		showList(list);
10
+
11
+		list = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
12
+		bubblesort(list);
13
+		showList(list);
14
+
15
+		list = new int[]{11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2};
16
+		bubblesort(list);
17
+		showList(list);
18
+
19
+		list = new int[]{1};
20
+		bubblesort(list);
21
+		showList(list);
22
+	}
23
+
24
+
25
+	// pre: list != null, list.length > 0
26
+	// post: return index of minimum element of array
27
+	public static int findMin(int[] list)
28
+	{	assert list != null && list.length > 0 : "failed precondition";
29
+
30
+		int indexOfMin = 0;
31
+		for(int i = 1; i < list.length; i++)
32
+		{	if(list[i] < list[indexOfMin])
33
+			{	indexOfMin = i;
34
+			}
35
+		}
36
+
37
+		return indexOfMin;
38
+	}
39
+
40
+
41
+	/*
42
+	 *pre: list != null, newSize >= 0
43
+	 *post: nothing. the method does not succeed it resizing the
44
+	 * argument
45
+	 */
46
+	public static void badResize(int[] list, int newSize)
47
+	{	assert list != null && newSize >= 0 : "failed precondition";
48
+
49
+		int[] temp = new int[newSize];
50
+		int limit = Math.min(list.length, newSize);
51
+
52
+		for(int i = 0; i < limit; i++)
53
+		{	temp[i] = list[i];
54
+		}
55
+
56
+		// uh oh!! Changing pointer, not pointee. This breaks the
57
+		// relationship between the parameter and argument
58
+		list = temp;
59
+	}
60
+
61
+
62
+	/*
63
+	 *pre: list != null, newSize >= 0
64
+	 *post: returns an array of size newSize. Elements from 0 to newSize - 1
65
+	 *	will be copied into the new array
66
+	 */
67
+	public static int[] goodResize(int[] list, int newSize)
68
+	{	assert list != null && newSize >= 0 : "failed precondition";
69
+
70
+		int[] result = new int[newSize];
71
+		int limit = Math.min(list.length, newSize);
72
+
73
+		for(int i = 0; i < limit; i++)
74
+		{	result[i] = list[i];
75
+		}
76
+
77
+		return result;
78
+	}
79
+
80
+
81
+	/*
82
+	 *pre: list != null
83
+	 *post: prints out the indices and values of all pairs of numbers
84
+	 *in list such that list[a] + list[b] = target
85
+	 */
86
+	public static void findAndPrintPairs(int[] list, int target)
87
+	{	assert list != null : "failed precondition";
88
+
89
+		for(int i = 0; i < list.length; i++)
90
+		{	for(int j = i + 1; j < list.length; j++)
91
+			{	if(list[i] + list[j] == target)
92
+				{	System.out.println("The two elements at indices " + i + " and " + j
93
+						+ " are " + list[i] + " and " + list[j] + " add up to " + target);
94
+				}
95
+			}
96
+		}
97
+	}
98
+
99
+
100
+	/*
101
+	 *pre: list != null;
102
+	 *post: sort the elements of list so that they are in ascending order
103
+	 */
104
+	public static void bubblesort(int[] list)
105
+	{
106
+		assert list != null : "failed precondition";
107
+
108
+		int temp;
109
+		boolean changed = true;
110
+		for(int i = 0; i < list.length && changed; i++)
111
+		{	changed = false;
112
+			for(int j = 0; j < list.length - i - 1; j++)
113
+			{	assert (j > 0) && (j + 1 < list.length) : "loop counter j " + j +
114
+					"is out of bounds.";
115
+				if(list[j] > list[j+1])
116
+				{	changed = true;
117
+					temp = list[j + 1];
118
+					list[j + 1] = list[j];
119
+					list[j] = temp;
120
+				}
121
+			}
122
+		}
123
+
124
+		assert isAscending( list );
125
+	}
126
+
127
+
128
+	public static void showList(int[] list)
129
+	{	for(int i = 0; i < list.length; i++)
130
+			System.out.print( list[i] + " " );
131
+		System.out.println();
132
+	}
133
+
134
+	/* 	pre: list != null
135
+		post: return true if list is sorted in ascedning order, false otherwise
136
+	*/
137
+	public static boolean isAscending( int[] list )
138
+	{	boolean ascending = true;
139
+		int index = 1;
140
+		while( ascending && index < list.length )
141
+		{	assert index >= 0 && index < list.length;
142
+
143
+			ascending = (list[index - 1] <= list[index]);
144
+			index++;
145
+		}
146
+
147
+		return ascending;
148
+	}
149
+}

+ 53
- 0
CodeSamples/codeSamples/BinaryConverter.java Bestand weergeven

@@ -0,0 +1,53 @@
1
+
2
+public class BinaryConverter {
3
+    
4
+    public static void main(String[] args){
5
+        for(int i = -5; i < 33; i++){
6
+            System.out.println(i + ": " + toBinary(i));
7
+            System.out.println(i);
8
+            //always another way
9
+            System.out.println(i + ": " + Integer.toBinaryString(i));
10
+        }
11
+    }
12
+    
13
+    /*
14
+     * pre: none
15
+     * post: returns a String with base10Num in base 2
16
+     */
17
+    public static String toBinary(int base10Num){
18
+        boolean isNeg = base10Num < 0;
19
+        base10Num = Math.abs(base10Num);        
20
+        String result = "";
21
+        
22
+        while(base10Num > 1){
23
+            result = (base10Num % 2) + result;
24
+            base10Num /= 2;
25
+        }
26
+        assert base10Num == 0 || base10Num == 1 : "value is not <= 1: " + base10Num;
27
+        
28
+        result = base10Num + result;
29
+        assert all0sAnd1s(result);
30
+        
31
+        if( isNeg )
32
+            result = "-" + result;
33
+        return result;
34
+    }
35
+    
36
+    /*
37
+     * pre: cal != null
38
+     * post: return true if val consists only of characters 1 and 0, false otherwise
39
+     */
40
+    public static boolean all0sAnd1s(String val){
41
+        assert val != null : "Failed precondition all0sAnd1s. parameter cannot be null";
42
+        boolean all = true;
43
+        int i = 0;
44
+        char c;
45
+        
46
+        while(all && i < val.length()){
47
+            c = val.charAt(i);
48
+            all = c == '0' || c == '1';
49
+            i++;
50
+        }
51
+        return all;
52
+    }
53
+}

+ 23
- 0
CodeSamples/codeSamples/CallingMethodsInSameClass.java Bestand weergeven

@@ -0,0 +1,23 @@
1
+/* CallingMethodsInSameClass.java
2
+ *
3
+ * illustrates how to call static methods a class
4
+ * from a method in the same class
5
+ */
6
+
7
+public class CallingMethodsInSameClass
8
+{
9
+	public static void main(String[] args) {
10
+		printOne();
11
+		printOne();
12
+		printTwo();
13
+	}
14
+
15
+	public static void printOne() {
16
+		System.out.println("Hello World");
17
+	}
18
+
19
+	public static void printTwo() {
20
+		printOne();
21
+		printOne();
22
+	}
23
+}

+ 74
- 0
CodeSamples/codeSamples/CreateASet.java Bestand weergeven

@@ -0,0 +1,74 @@
1
+import java.util.Arrays;
2
+import java.awt.Rectangle;
3
+
4
+/**
5
+ * A sample of a ploymorphic method.
6
+ * @author scottm
7
+ *
8
+ */
9
+public class CreateASet {
10
+    
11
+    public static void main(String[] args){
12
+        String[] words = {"A", "B", "B", "D", "C", "A"};
13
+        System.out.println( "original: " + Arrays.toString(words));
14
+        System.out.println( "as a set: " + Arrays.toString(makeSet(words)));
15
+        
16
+        Rectangle[] rectList = {new Rectangle(), new Rectangle(), 
17
+                    new Rectangle(0, 1, 2, 3), new Rectangle(0, 1, 2, 3)};
18
+        System.out.println( "original: " + Arrays.toString(rectList));
19
+        System.out.println( "as a set: " + Arrays.toString(makeSet(rectList)));     
20
+        
21
+        
22
+        Object[] mixed = {"A", "C", "A", "B", new Rectangle(),
23
+                new Rectangle(), "A", new Rectangle(0, 1, 2, 3), "D"};
24
+        System.out.println( "original: " + Arrays.toString(mixed));
25
+        System.out.println( "as a set: " + Arrays.toString(makeSet(mixed))); 
26
+    }
27
+    
28
+    /**
29
+     * An example of polymorphism in action. The method relies
30
+     * on Java's inheritance requirement and polymorhphism to call
31
+     * the correct equals method.
32
+     * @param data != null, no elements of data are null
33
+     * @return a Set (no duplicates) of the elements in data.
34
+     */
35
+    public static Object[] makeSet(Object[] data){
36
+        assert data != null : "Failed precondition makeSet. parameter cannot be null";
37
+        assert noNulls(data) : "Failed precondition makeSet. no elements of parameter can be null";
38
+        Object[] result = new Object[data.length];
39
+        int numUnique = 0;
40
+        boolean found;
41
+        int indexInResult;
42
+        for(int i = 0; i < data.length; i++){
43
+            // maybe should break this out into another method
44
+            indexInResult = 0;
45
+            found = false;
46
+            while(!found && indexInResult < numUnique){
47
+                found = data[i].equals(result[indexInResult]);
48
+                indexInResult++;
49
+            }
50
+            if( ! found ){
51
+                result[numUnique] = data[i];
52
+                numUnique++;
53
+            }
54
+        }
55
+        Object[] result2 = new Object[numUnique];
56
+        System.arraycopy(result, 0, result2, 0, numUnique);
57
+        return result2;
58
+    }
59
+    
60
+    // pre: data != null
61
+    // return true if all elements of data are non null,
62
+    // false otherwise
63
+    private static boolean noNulls(Object[] data){
64
+        assert data != null : "Failed precondition makeSet. parameter cannot be null";
65
+        boolean good = true;
66
+        int i = 0;
67
+        while( good && i < data.length ){
68
+            good = data[i] != null;
69
+            i++;
70
+        }
71
+        return good;        
72
+    }
73
+    
74
+}

+ 103
- 0
CodeSamples/codeSamples/DemoClass.java Bestand weergeven

@@ -0,0 +1,103 @@
1
+/******************************************************************/
2
+/* Author: CS307 Course Staff                                     */
3
+/* Date: February 14, 2005                                        */
4
+/* Description: Demos constructors, static vs instance methods,   */
5
+/*              and method overloading.                           */
6
+/******************************************************************/
7
+public class DemoClass
8
+{
9
+    private int x;
10
+
11
+    public DemoClass()
12
+    {
13
+        // assign default value
14
+        x = 0;
15
+    }
16
+
17
+    public DemoClass(int x)
18
+    {
19
+        // use this.x to refer to the instance variable x
20
+        // use x to refer to a local variable x (more specifically,
21
+        // method parameter x)
22
+        this.x = x;
23
+    }
24
+
25
+    public DemoClass(DemoClass otherDemo)
26
+    {
27
+        // copy the value from the otherDemo
28
+        this.x = otherDemo.x;
29
+    }
30
+
31
+    // static method (aka class method)
32
+    public static void s1() {
33
+        return;
34
+    }
35
+    // instance method
36
+    public void i1() {
37
+        return;
38
+    }
39
+
40
+    // static calling static OK
41
+    // static calling instance is a compile-time error
42
+    public static void s2() {
43
+//        i1();     // compile-time error
44
+        s1();       // DemoClass.s1
45
+        return;
46
+    }
47
+
48
+    // instance calling static OK
49
+    // instance calling instance OK
50
+    public void i2() {
51
+        s1();       // DemoClass.s1();
52
+        i1();       // this.i1();
53
+        return;
54
+    }
55
+
56
+    // call various versions of overload() based on their 
57
+    // list of parameters (aka function signatures)
58
+    public void overloadTester() {
59
+        System.out.println("overloadTester:\n");
60
+
61
+        overload((byte)1);
62
+        overload((short)1);
63
+        overload(1);
64
+        overload(1L);
65
+        overload(1.0f);
66
+        overload(1.0);
67
+        overload('1');
68
+        overload(true);
69
+    }
70
+    
71
+    public void overload(byte b) {
72
+        System.out.println("byte");
73
+    }    
74
+    public void overload(short s) {
75
+        System.out.println("short");
76
+    }    
77
+    public void overload(int i) {
78
+        System.out.println("int");
79
+    }
80
+    public void overload(long l) {
81
+        System.out.println("long");
82
+    }
83
+    public void overload(float f) {
84
+        System.out.println("float");
85
+    }
86
+    public void overload(double d) {
87
+        System.out.println("double");
88
+    }    
89
+    public void overload(char c) {
90
+        System.out.println("char");
91
+    }    
92
+    public void overload(boolean b) {
93
+        System.out.println("boolean");
94
+    }    
95
+
96
+    public static void main(String[] args) {
97
+        DemoClass dc = new DemoClass();
98
+        dc.overloadTester();
99
+    }
100
+}
101
+
102
+// end of DemoClass.java
103
+

+ 126
- 0
CodeSamples/codeSamples/Die.java Bestand weergeven

@@ -0,0 +1,126 @@
1
+import java.util.Random;
2
+
3
+/**
4
+ * Models a playing die with sides numbered 1 to N.
5
+ * All sides have uniform probablity of being rolled.
6
+ *
7
+ * @author Summer CS 307 class
8
+ */
9
+public class Die
10
+{   public static final int DEFAULT_SIDES = 6;
11
+
12
+    private static Random ourRandNumGen = new Random();
13
+
14
+    private final int iMyNumSides;
15
+    private int iMyResult;
16
+
17
+
18
+    /**
19
+     * Default constructor.<p>
20
+     * pre: none<br>
21
+     * post: getNumSides() = DEFAULT_SIDES, getResult() = 1
22
+     */
23
+    public Die()
24
+    {   this(DEFAULT_SIDES);
25
+    }
26
+
27
+
28
+    /**
29
+     * Create a Die with numSides sides<p>
30
+     * pre: numSides > 1<br>
31
+     * post: getNumSides() = numSides, getResult() = 1<br>
32
+     * An exception will be generated if the preconditions are not met
33
+     */
34
+    public Die(int numSides)
35
+    {   assert numSides > 1 : "Violation of precondition: numSides = " + numSides + "numSides must be greater than 1";
36
+
37
+        iMyNumSides = numSides;
38
+        iMyResult = 1;
39
+        assert getResult() == 1 && getNumSides() == numSides;
40
+    }
41
+
42
+
43
+    /**
44
+     * Create a Die with numSides and top side and result set to result<p>
45
+     * pre: numSides > 1, 1 <= result <= numSides<br>
46
+     * post: getNumSides() = numSides, getResult() = 1<br>
47
+     * An exception will be generated if the preconditions are not met
48
+     */
49
+    public Die(int numSides, int result)
50
+    {   assert numSides > 1 && 1 <= result && result <= numSides : "Violation of precondition";
51
+
52
+        iMyNumSides = numSides;
53
+        iMyResult = result;
54
+    }
55
+
56
+
57
+    /**
58
+     * roll this Die. Every side has an equal chance of being the new result<p>
59
+     * pre: none<br>
60
+     * post: 1 <= getResult() <= getNumSides()
61
+     * @return the result of the Die after the roll
62
+     */
63
+    public int roll()
64
+    {   iMyResult = ourRandNumGen.nextInt(iMyNumSides) + 1;
65
+
66
+        assert ( 1 <= getResult() ) && ( getResult() <= getNumSides() );
67
+
68
+        return iMyResult;
69
+    }
70
+
71
+
72
+    /**
73
+     * return how many sides this Die has<p>
74
+     * pre: none<br>
75
+     * post: return how many sides this Die has
76
+     * @return the number of sides on this Die
77
+     */
78
+    public int getNumSides()
79
+    {   return iMyNumSides; }
80
+
81
+
82
+    /**
83
+     * get the current result or top number of this Die<p>
84
+     * pre: none<br>
85
+     * post: return the number on top of this Die
86
+     * @return the current result of this Die
87
+     */
88
+    public int getResult()
89
+    {   return iMyResult;   }
90
+
91
+
92
+    /**
93
+     * returns true if this Die and the parameter otherObj are equal<p>
94
+     * pre: none<br>
95
+     * post: return true if the parameter is a Die object with the same number of sides as this Die and currently has the same result.
96
+     * @return true if the the two Dice are equal, false otherwise
97
+     */
98
+    public boolean equals(Object otherObj)
99
+    {   boolean result = true;
100
+        if(otherObj == null)
101
+            result = false;
102
+        else if(this == otherObj)
103
+            result = true;
104
+        else if(this.getClass() != otherObj.getClass())
105
+            result = false;
106
+        else
107
+        {   Die otherDie = (Die)otherObj;
108
+            result = this.iMyResult == otherDie.iMyResult
109
+                && this.iMyNumSides == otherDie.iMyNumSides;
110
+        }
111
+        return result;
112
+    }
113
+
114
+
115
+    /**
116
+     * returns a String containing information about this Die<p>
117
+     * pre: none<br>
118
+     * post: return a String with information about the current state of this Die
119
+     * @return: A String with the number of sides and current result of this Die
120
+     */
121
+    public String toString()
122
+    {   return "Num sides " + getNumSides() + " result " + getResult();
123
+    }
124
+
125
+
126
+}// end of Die class

+ 183
- 0
CodeSamples/codeSamples/EightQueens.java Bestand weergeven

@@ -0,0 +1,183 @@
1
+import java.util.Arrays;
2
+import java.util.ArrayList;
3
+
4
+public class EightQueens {
5
+
6
+
7
+	public static void main(String[] args) {
8
+			solveNQueens(8);
9
+			ArrayList<char[][]> solutions = getAllNQueens(8);
10
+			System.out.println( solutions.size() );
11
+			for( int i = 0; i < solutions.size(); i++){
12
+				System.out.println("\n\nSolution " + (i+1));
13
+				if( queensAreSafe(solutions.get(i)) )
14
+					printBoard(solutions.get(i));
15
+				else
16
+					System.out.println("UH OH!!!!! BETTER FIX IT!!!!!");
17
+
18
+	}
19
+
20
+	/**
21
+	 * determine if the chess board represented by board is a safe set up
22
+	 * <p>pre: board != null, board.length > 0, board is a square matrix.
23
+	 * (In other words all rows in board have board.length columns.),
24
+	 * all elements of board == 'q' or '.'. 'q's represent queens, '.'s
25
+	 * represent open spaces.<br>
26
+	 * <p>post: return true if the configuration of board is safe,
27
+	 * that is no queen can attack any other queen on the board.
28
+	 * false otherwise.
29
+	 * @param board the chessboard
30
+	 * @return true if the configuration of board is safe,
31
+	 * that is no queen can attack any other queen on the board.
32
+	 * false otherwise.
33
+	*/
34
+	public static boolean queensAreSafe(char[][] board)
35
+	{	char[] validChars = {'q', '.'};
36
+		assert (board != null) && (board.length > 0)
37
+				&& isSquare(board) && onlyContains(board, validChars)
38
+				: "Violation of precondition: queensAreSafe";
39
+
40
+
41
+		return true;
42
+	}
43
+
44
+	public static ArrayList<char[][]> getAllNQueens(int size){
45
+		ArrayList<char[][]> solutions = new ArrayList<char[][]>();
46
+		char[][] board = blankBoard(size);
47
+		solveAllNQueens(board, 0, solutions);
48
+		return solutions;
49
+	}
50
+
51
+	public static void solveAllNQueens(char[][] board, int col, ArrayList<char[][]> solutions){
52
+		// am I done? if so, add this solution to the ArrayList of solutions
53
+		if( col == board.length){
54
+			solutions.add( makeCopy(board));
55
+			// all done
56
+		} else {
57
+			for(int row = 0; row < board.length; row++){
58
+				// place queen
59
+				board[row][col] = 'q';
60
+				if( queensAreSafe(board) )
61
+					// if safe go on to next column
62
+					solveAllNQueens(board, col + 1, solutions);
63
+				board[row][col] = '.';
64
+			}
65
+		}
66
+	}
67
+
68
+	// pre: mat != null, mat is rectangular
69
+	public static char[][] makeCopy(char[][] mat){
70
+		assert mat != null;
71
+		char[][] copy = new char[mat.length][mat[0].length];
72
+		for(int r = 0; r < mat.length; r++)
73
+			for(int c = 0; c < mat[0].length; c++)
74
+				copy[r][c] = mat[r][c];
75
+		return copy;
76
+	}
77
+
78
+	public static void printBoard(char[][] board){
79
+		for(int r = 0; r < board.length; r++){
80
+			for(int c = 0; c < board[r].length; c++)
81
+				System.out.print(board[r][c]);
82
+			System.out.println();
83
+		}
84
+	}
85
+
86
+	public static void solveNQueens(int n){
87
+		char[][] board = blankBoard(n);
88
+		//start in column 0
89
+		boolean solved = canSolve(board, 0);
90
+		if( solved ){
91
+			System.out.println("Solved the " + n + " queen problem.");
92
+			printBoard(board);
93
+		}
94
+		else
95
+			System.out.println("Can't solve the " + n + " queen problem.");
96
+	}
97
+
98
+	public static boolean
99
+		canSolve(char[][] board, int col){
100
+
101
+
102
+		//know when you are done!
103
+		if( col == board.length)
104
+			return true; // solved!!!!!
105
+
106
+		// not done, try all the rows
107
+		boolean solved = false;
108
+		for(int row = 0; row < board.length && !solved; row++){
109
+			//System.out.println(row + " " + col);
110
+			// place queen
111
+			board[row][col] = 'q';
112
+			if( queensAreSafe(board) )
113
+				solved = canSolve(board, col + 1);
114
+			if( !solved )
115
+				board[row][col] = '.';
116
+		}
117
+		return solved; //could be true(solved) or false(not solved)!!
118
+	}
119
+
120
+
121
+	private static char[][] blankBoard(int size){
122
+		char[][] result = new char[size][size];
123
+		for(int r = 0; r < size; r++)
124
+			Arrays.fill(result[r], '.');
125
+		return result;
126
+	}
127
+
128
+	private static boolean inbounds(int row, int col, char[][] mat){
129
+		return row >= 0 && row < mat.length && col >= 0 && col < mat[0].length;
130
+	}
131
+
132
+	/* pre: mat != null
133
+	   post: return true if mat is a square matrix, false otherwise
134
+	*/
135
+	private static boolean isSquare(char[][] mat)
136
+	{	assert mat != null : "Violation of precondition: isSquare";
137
+
138
+		final int numRows = mat.length;
139
+		int row = 0;
140
+		boolean square = true;
141
+		while( square && row < numRows )
142
+		{	square = ( mat[row] != null) && (mat[row].length == numRows);
143
+			row++;
144
+		}
145
+		return square;
146
+	}
147
+
148
+	/* pre: mat != null, valid != null
149
+	   post: return true if all elements in mat are one of the characters in valid
150
+	*/
151
+	private static boolean onlyContains(char[][] mat, char[] valid)
152
+	{	assert mat != null && valid != null : "Violation of precondition: onlyContains";
153
+
154
+		int row = 0;
155
+		int col;
156
+		boolean correct = true;
157
+		while( correct && row < mat.length)
158
+		{	col = 0;
159
+			while(correct && col < mat[row].length)
160
+			{	correct = contains(valid, mat[row][col]);
161
+				col++;
162
+			}
163
+			row++;
164
+		}
165
+		return correct;
166
+	}
167
+
168
+	/* pre: list != null
169
+	   post: return true if c is in list
170
+	*/
171
+	private static boolean contains(char[] list, char c)
172
+	{	assert ( list != null ) : "Violation of precondition: contains";
173
+
174
+		boolean found = false;
175
+		int index = 0;
176
+		while( !found && index < list.length)
177
+		{	found = list[index] == c;
178
+			index++;
179
+		}
180
+		return found;
181
+	}
182
+
183
+}

+ 69
- 0
CodeSamples/codeSamples/EnhancedFor.java Bestand weergeven

@@ -0,0 +1,69 @@
1
+public class EnhancedFor
2
+{
3
+	public static void main(String[] args)
4
+	{	int[] list ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
5
+		int sum = sumListEnhanced(list);
6
+		System.out.println("Sum of elements in list: " + sum);
7
+
8
+		System.out.println("Original List");
9
+		printList(list);
10
+		System.out.println("Calling addOne");
11
+		addOne(list);
12
+		System.out.println("List after call to addOne");
13
+		printList(list);
14
+		System.out.println("Calling addOneError");
15
+		addOneError(list);
16
+		System.out.println("List after call to addOneError. Note elements of list did not change.");
17
+		printList(list);
18
+	}
19
+
20
+	// pre: list != null
21
+	// post: return sum of elements
22
+	// uses enhanced for loop
23
+	public static int sumListEnhanced(int[] list)
24
+	{	int total = 0;
25
+		for(int val : list)
26
+		{	total += val;
27
+		}
28
+		return total;
29
+	}
30
+
31
+	// pre: list != null
32
+	// post: return sum of elements
33
+	// use traditional for loop
34
+	public static int sumListOld(int[] list)
35
+	{	int total = 0;
36
+		for(int i = 0; i < list.length; i++)
37
+		{	total += list[i];
38
+			System.out.println( list[i] );
39
+		}
40
+		return total;
41
+	}
42
+
43
+	// pre: list != null
44
+	// post: none.
45
+	// The code appears to add one to every element in the list, but does not
46
+	public static void addOneError(int[] list)
47
+	{	for(int val : list)
48
+		{	val = val + 1;
49
+		}
50
+	}
51
+
52
+	// pre: list != null
53
+	// post: adds one to every element of list
54
+	public static void addOne(int[] list)
55
+	{	for(int i = 0; i < list.length; i++)
56
+		{	list[i]++;
57
+		}
58
+	}
59
+
60
+	public static void printList(int[] list)
61
+	{	System.out.println("index, value");
62
+		for(int i = 0; i < list.length; i++)
63
+		{	System.out.println(i + ", " + list[i]);
64
+		}
65
+	}
66
+
67
+
68
+
69
+}

+ 15
- 0
CodeSamples/codeSamples/Factorial.java Bestand weergeven

@@ -0,0 +1,15 @@
1
+public class Factorial
2
+{
3
+	public static void main(String[] args)
4
+	{	final int NUM_FACTS = 100;
5
+		for(int i = 0; i < NUM_FACTS; i++)
6
+			System.out.println( i + "! is " + factorial(i));
7
+	}
8
+	
9
+	public static int factorial(int n)
10
+	{	int result = 1;
11
+		for(int i = 2; i <= n; i++)
12
+			result *= i;
13
+		return result;
14
+	}
15
+}

+ 75
- 0
CodeSamples/codeSamples/FilterExample.java Bestand weergeven

@@ -0,0 +1,75 @@
1
+// Mike Scott
2
+// 2d array manipulation examples
3
+
4
+//import
5
+import java.awt.Color;
6
+
7
+
8
+public class FilterExample
9
+{
10
+	/*
11
+	 *pre: image != null, image.length > 1, image[0].length > 1
12
+	 *	image is a rectangular matrix, neighberhoodSize > 0
13
+	 *post: return a smoothed version of image
14
+	 */
15
+	public Color[][] smooth(Color[][] image, int neighberhoodSize)
16
+	{	//check precondition
17
+		assert image != null && image.length > 1 && image[0].length > 1
18
+				&& ( neighberhoodSize > 0 ) && rectangularMatrix( image )
19
+				: "Violation of precondition: smooth";
20
+
21
+		Color[][] result = new Color[image.length][image[0].length];
22
+
23
+		for(int row = 0; row < image.length; row++)
24
+		{	for(int col = 0; col < image[0].length; col++)
25
+			{	result[row][col] = aveOfNeighbors(image, row, col, neighberhoodSize);
26
+			}
27
+		}
28
+
29
+		return result;
30
+	}
31
+
32
+
33
+	// helper method that determines the average color of a neighberhood
34
+	// around a particular cell.
35
+	private Color aveOfNeighbors(Color[][] image, int row, int col, int neighberhoodSize)
36
+	{	int numNeighbors = 0;
37
+		int red = 0;
38
+		int green = 0;
39
+		int blue = 0;
40
+
41
+		for(int r = row - neighberhoodSize; r <= row + neighberhoodSize; r++)
42
+		{	for(int c = col - neighberhoodSize; c <= col + neighberhoodSize; c++)
43
+			{	if( inBounds( image, r, c ) )
44
+				{	numNeighbors++;
45
+					red += image[r][c].getRed();
46
+					green += image[r][c].getGreen();
47
+					blue += image[r][c].getBlue();
48
+				}
49
+			}
50
+		}
51
+
52
+		assert numNeighbors > 0;
53
+		return new Color( red / numNeighbors, green / numNeighbors, blue / numNeighbors );
54
+	}
55
+
56
+	//helper method to determine if given coordinates are in bounds
57
+	private boolean inBounds(Color[][] image, int row, int col)
58
+	{	return (row >= 0) && (row <= image.length) && (col >= 0)
59
+				&& (col < image[0].length);
60
+	}
61
+
62
+	//private method to ensure mat is rectangular
63
+	private boolean rectangularMatrix( Color[][] mat )
64
+	{	boolean isRectangular = true;
65
+		int row = 1;
66
+		final int COLUMNS = mat[0].length;
67
+
68
+		while( isRectangular && row < mat.length )
69
+		{	isRectangular = ( mat[row].length == COLUMNS );
70
+			row++;
71
+		}
72
+
73
+		return isRectangular;
74
+	}
75
+}

+ 134
- 0
CodeSamples/codeSamples/FreqTableExampleOriginal.java Bestand weergeven

@@ -0,0 +1,134 @@
1
+import java.io.File;
2
+import java.io.FileNotFoundException;
3
+import java.io.FileReader;
4
+import java.io.IOException;
5
+import java.io.InputStreamReader;
6
+import java.net.MalformedURLException;
7
+import java.net.URL;
8
+
9
+
10
+public class FreqTableExampleOriginal {
11
+
12
+    public static final int NUM_ASCII_CHAR = 128;
13
+
14
+    // program to create a frequency table.
15
+    // Example of simple try catch blocks to deal with checked exceptions
16
+    public static void main(String[] args)
17
+        {
18
+
19
+        int[] freqs = createFreqTableURL("http://www.utexas.edu/");
20
+
21
+        if( freqs.length == 0)
22
+            System.out.println("No frequency table created due to problems when reading from file");
23
+        else{
24
+            for(int i = 0; i < NUM_ASCII_CHAR; i++){
25
+                System.out.println("charcater code: " + i + " ,character: " + (char)i + " ,frequency: " + freqs[i]);
26
+            }
27
+            System.out.println("Total characters in file: " + sum(freqs));
28
+        }
29
+
30
+
31
+        freqs = new int[]{};
32
+        try{
33
+            freqs = createTable("ciaFactBook2008.txt");
34
+        }
35
+        catch(FileNotFoundException e){
36
+            System.out.println("File not found. Unable to create freq table" + e);
37
+        }
38
+        catch(IOException e){
39
+            System.out.println("Problem while reading from file. Unable to create freq table" + e);
40
+        }
41
+        if( freqs.length == 0)
42
+            System.out.println("No frequency table created due to problems when reading from file");
43
+        else{
44
+            for(int i = 0; i < freqs.length; i++){
45
+                System.out.println("charcater code: " + i + " ,character: " + (char)i + " ,frequency: " + freqs[i]);
46
+            }
47
+            System.out.println("Total characters in file: " + sum(freqs));
48
+        }
49
+
50
+    }
51
+
52
+
53
+    // return sum of ints in list
54
+    // list may not be null
55
+    private static int sum(int[] list) {
56
+        assert list != null : "Failed precondition, sum: parameter list" +
57
+            " may not be null.";
58
+        int total = 0;
59
+        for(int x : list){
60
+            total += x;
61
+        }
62
+        return total;
63
+    }
64
+
65
+
66
+    // pre: url != null
67
+    // Connect to the URL specified by the String url.
68
+    // Map characters to index in array.
69
+    // All non ASCII character dumped into one element of array
70
+    // If IOException occurs message printed and array of
71
+    // length 0 returned.
72
+    public static int[] createFreqTableURL (String url){
73
+        if(url == null)
74
+            throw new IllegalArgumentException("Violation of precondition. parameter url must not be null.");
75
+
76
+        int[] freqs = new int[NUM_ASCII_CHAR];
77
+        try {
78
+        URL inputURL = new URL(url);
79
+        InputStreamReader in
80
+            = new InputStreamReader(inputURL.openStream());
81
+
82
+        while(in.ready()){
83
+            int c = in.read();
84
+            if(0 <= c && c < freqs.length)
85
+                freqs[c]++;
86
+            else
87
+                System.out.println("Non ASCII char: " + c + " " + (char) c);
88
+        }
89
+        in.close();
90
+        }
91
+        catch(MalformedURLException e){
92
+            System.out.println("Bad URL.");
93
+            freqs = new int[0];
94
+        }
95
+        catch(IOException e){
96
+            System.out.println("Unable to read from resource." + e);
97
+            freqs = new int[0];
98
+        }
99
+        return freqs;
100
+    }
101
+
102
+
103
+
104
+    // Connect to the file specified by the String fileName.
105
+    // Assumes it is in same directory as compiled code.
106
+    // Map characters to index in array.
107
+    public static int[] createTable(String fileName) throws FileNotFoundException, IOException{
108
+        int[] freqs = new int[NUM_ASCII_CHAR];
109
+        File f = new File(fileName);
110
+        FileReader r = new FileReader(f);
111
+        while( r.ready() ){
112
+            int ch = r.read();
113
+//            if( 0 <= ch && ch <= NUM_ASCII_CHAR)
114
+//                freqs[ch]++;
115
+//            else
116
+//                freqs[INDEX_NON_ASCII]++;
117
+            if(0 <= ch && ch < freqs.length)
118
+                freqs[ch]++;
119
+            else
120
+                System.out.println((char) ch);
121
+                
122
+        }
123
+        r.close();
124
+        return freqs;
125
+    }
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+}

+ 163
- 0
CodeSamples/codeSamples/GenericList.java Bestand weergeven

@@ -0,0 +1,163 @@
1
+/**
2
+ * A class to provide a simple list.
3
+ * List resizes automatically. Used to illustrate 
4
+ * various design and implementation details of 
5
+ * a class in Java.
6
+ * 
7
+ * @author scottm
8
+ *
9
+ */
10
+public class GenericList{
11
+    // class constant for default size
12
+    private static final int DEFAULT_CAP = 10;
13
+    
14
+    //instance variables
15
+    // iValues store the elements of the list and 
16
+    // may have extra capacity
17
+    private Object[] iValues;
18
+    private int iSize;
19
+    
20
+    /**
21
+     * Default add method. Add x to the end of this IntList.
22
+     * Size of the list goes up by 1.
23
+     * @param x The value to add to the end of this list.
24
+     */
25
+    public void add(Object x){
26
+        insert(iSize, x);
27
+    }
28
+    
29
+    public Object get(int pos){
30
+        return iValues[pos];
31
+    }
32
+    
33
+    /**
34
+     * Insert obj at position pos.
35
+     * post: get(pos) = x, size() = old size() + 1
36
+     * @param pos 0 <= pos <= size()
37
+     * @param obj The element to add.
38
+     */
39
+    public void insert(int pos, Object obj){
40
+        ensureCapcity();
41
+        for(int i = iSize; i > pos; i--){
42
+            iValues[i] = iValues[i - 1];
43
+        }
44
+        iValues[pos] = obj;
45
+        iSize++;
46
+    }
47
+    
48
+    public Object remove(int pos){
49
+        Object removedValue = iValues[pos];
50
+        for(int i = pos; i < iSize - 1; i++)
51
+            iValues[i] = iValues[i + 1];
52
+        iValues[iSize - 1] = null;
53
+        iSize--;
54
+        return removedValue;
55
+    }
56
+    
57
+    private void ensureCapcity(){
58
+        // is there extra capacity available?
59
+        // if not, resize
60
+        if(iSize == iValues.length)
61
+            resize();
62
+    }
63
+    
64
+    public int size(){
65
+        return iSize;
66
+    }
67
+    
68
+    // resize internal storage container by a factor of 2
69
+    private void resize() {
70
+        Object[] temp = new Object[iValues.length * 2];
71
+        System.arraycopy(iValues, 0, temp, 0, iValues.length);
72
+        iValues = temp;
73
+    }
74
+    
75
+    /**
76
+     * Return a String version of this list. Size and 
77
+     * elements included.
78
+     */
79
+    public String toString(){
80
+        // we could make this more effecient by using a StringBuffer.
81
+        // See alternative version
82
+        String result = "size: " + iSize + ", elements: [";
83
+        for(int i = 0; i < iSize - 1; i++)
84
+            result += iValues[i].toString() + ", ";
85
+        if(iSize > 0 )
86
+            result += iValues[iSize - 1];
87
+        result += "]";
88
+        return result;
89
+    }
90
+    
91
+    // Would not really have this and toString available
92
+    // both included just for testing
93
+    public String toStringUsingStringBuffer(){
94
+        StringBuffer result = new StringBuffer();
95
+        result.append( "size: " );
96
+        result.append( iSize );
97
+        result.append(", elements: [");
98
+        for(int i = 0; i < iSize - 1; i++){
99
+            result.append(iValues[i]);
100
+            result.append(", ");
101
+        }
102
+        if( iSize > 0 )
103
+            result.append(iValues[iSize - 1]);
104
+        result.append("]");
105
+        return result.toString();
106
+    }
107
+
108
+    /**
109
+     * Default constructor. Creates an empty list.
110
+     */
111
+    public GenericList(){
112
+        //redirect to single int constructor
113
+        this(DEFAULT_CAP);
114
+        //other statments could go here.
115
+    }
116
+
117
+    /**
118
+     * Constructor to allow user of class to specify 
119
+     * initial capacity in case they intend to add a lot
120
+     * of elements to new list. Creates an empty list.
121
+     * @param initialCap > 0
122
+     */    
123
+    public GenericList(int initialCap) {
124
+        assert initialCap > 0 : "Violation of precondition. IntListVer1(int initialCap):"
125
+            + "initialCap must be greater than 0. Value of initialCap: " + initialCap;
126
+        iValues = new Object[initialCap];
127
+        iSize = 0;
128
+    }
129
+    
130
+   /**
131
+    * Return true if this IntList is equal to other.<br>
132
+    * pre: none
133
+    * @param other The object to comapre to this
134
+    * @return true if other is a non null, IntList object
135
+    * that is the same size as this IntList and has the
136
+    * same elements in the same order, false otherwise.
137
+    */
138
+    public boolean equals(Object other){
139
+        boolean result;
140
+        if(other == null)
141
+            // we know this is not null so can't be equal
142
+            result = false;
143
+        else if(this == other)
144
+            // quick check if this and other refer to same IntList object
145
+            result = true;
146
+        else if( this.getClass() != other.getClass() )
147
+            // other is not an IntList they can't be equal
148
+            result = false;
149
+        else{
150
+            // other is not null and refers to an IntList
151
+            GenericList otherList = (GenericList)other;
152
+            result = this.size() == otherList.size();
153
+            int i = 0;
154
+            while(i < iSize && result){
155
+                result = this.iValues[i].equals( otherList.iValues[i] );
156
+                i++;
157
+            }
158
+        }
159
+        return result;     
160
+    }
161
+
162
+}
163
+

+ 208
- 0
CodeSamples/codeSamples/GenericListVersion2.java Bestand weergeven

@@ -0,0 +1,208 @@
1
+import java.util.Collection;
2
+import java.util.Iterator;
3
+
4
+/**
5
+ * A class to provide a simple list.
6
+ * List resizes automatically. Used to illustrate 
7
+ * various design and implementation details of 
8
+ * a class in Java.
9
+ * 
10
+ * @author scottm
11
+ *
12
+ */
13
+public class GenericListVersion2 implements Iterable{
14
+    // class constant for default size
15
+    private static final int DEFAULT_CAP = 10;
16
+    
17
+    //instance variables
18
+    // iValues store the elements of the list and 
19
+    // may have extra capacity
20
+    private Object[] iValues;
21
+    private int iSize;
22
+    
23
+    private class GenericListIterator implements Iterator{
24
+        private int position;
25
+        private boolean removeOK;
26
+        
27
+        private GenericListIterator(){
28
+            position = 0;
29
+            removeOK = false;
30
+        }
31
+        
32
+        public boolean hasNext(){
33
+            return position < iSize;
34
+        }
35
+        
36
+        public Object next(){
37
+            Object result = iValues[position];
38
+            position++;
39
+            removeOK = true;
40
+            return result;
41
+        }
42
+        
43
+        public void remove(){
44
+            if( !removeOK )
45
+                throw new IllegalStateException();
46
+            // which element should be removed??
47
+            removeOK = false;
48
+            GenericListVersion2.this.remove(position - 1);
49
+            position--;
50
+        }
51
+    }
52
+    
53
+    public Iterator iterator(){
54
+        return new GenericListIterator();
55
+    }
56
+    
57
+    public void addAll(Collection c){
58
+       // for each loop
59
+        for(Object obj : c){
60
+            this.add(obj);
61
+        }
62
+    }
63
+    
64
+    /**
65
+     * Default add method. Add x to the end of this IntList.
66
+     * Size of the list goes up by 1.
67
+     * @param x The value to add to the end of this list.
68
+     */
69
+    public void add(Object x){
70
+        insert(iSize, x);
71
+    }
72
+    
73
+    public Object get(int pos){
74
+        return iValues[pos];
75
+    }
76
+    
77
+    /**
78
+     * Insert obj at position pos.
79
+     * post: get(pos) = x, size() = old size() + 1
80
+     * @param pos 0 <= pos <= size()
81
+     * @param obj The element to add.
82
+     */
83
+    public void insert(int pos, Object obj){
84
+        ensureCapcity();
85
+        for(int i = iSize; i > pos; i--){
86
+            iValues[i] = iValues[i - 1];
87
+        }
88
+        iValues[pos] = obj;
89
+        iSize++;
90
+    }
91
+    
92
+    public Object remove(int pos){
93
+        Object removedValue = iValues[pos];
94
+        for(int i = pos; i < iSize - 1; i++)
95
+            iValues[i] = iValues[i + 1];
96
+        iValues[iSize - 1] = null;
97
+        iSize--;
98
+        return removedValue;
99
+    }
100
+    
101
+    private void ensureCapcity(){
102
+        // is there extra capacity available?
103
+        // if not, resize
104
+        if(iSize == iValues.length)
105
+            resize();
106
+    }
107
+    
108
+    public int size(){
109
+        return iSize;
110
+    }
111
+    
112
+    // resize internal storage container by a factor of 2
113
+    private void resize() {
114
+        Object[] temp = new Object[iValues.length * 2];
115
+        System.arraycopy(iValues, 0, temp, 0, iValues.length);
116
+        iValues = temp;
117
+    }
118
+    
119
+    /**
120
+     * Return a String version of this list. Size and 
121
+     * elements included.
122
+     */
123
+    public String toString(){
124
+        // we could make this more effecient by using a StringBuffer.
125
+        // See alternative version
126
+        String result = "size: " + iSize + ", elements: [";
127
+        for(int i = 0; i < iSize - 1; i++)
128
+            result += iValues[i].toString() + ", ";
129
+        if(iSize > 0 )
130
+            result += iValues[iSize - 1];
131
+        result += "]";
132
+        return result;
133
+    }
134
+    
135
+    // Would not really have this and toString available
136
+    // both included just for testing
137
+    public String toStringUsingStringBuffer(){
138
+        StringBuffer result = new StringBuffer();
139
+        result.append( "size: " );
140
+        result.append( iSize );
141
+        result.append(", elements: [");
142
+        for(int i = 0; i < iSize - 1; i++){
143
+            result.append(iValues[i]);
144
+            result.append(", ");
145
+        }
146
+        if( iSize > 0 )
147
+            result.append(iValues[iSize - 1]);
148
+        result.append("]");
149
+        return result.toString();
150
+    }
151
+
152
+    /**
153
+     * Default constructor. Creates an empty list.
154
+     */
155
+    public GenericListVersion2(){
156
+        //redirect to single int constructor
157
+        this(DEFAULT_CAP);
158
+        //other statments could go here.
159
+    }
160
+
161
+    /**
162
+     * Constructor to allow user of class to specify 
163
+     * initial capacity in case they intend to add a lot
164
+     * of elements to new list. Creates an empty list.
165
+     * @param initialCap > 0
166
+     */    
167
+    public GenericListVersion2(int initialCap) {
168
+        assert initialCap > 0 : "Violation of precondition. IntListVer1(int initialCap):"
169
+            + "initialCap must be greater than 0. Value of initialCap: " + initialCap;
170
+        iValues = new Object[initialCap];
171
+        iSize = 0;
172
+    }
173
+    
174
+   /**
175
+    * Return true if this IntList is equal to other.<br>
176
+    * pre: none
177
+    * @param other The object to comapre to this
178
+    * @return true if other is a non null, IntList object
179
+    * that is the same size as this IntList and has the
180
+    * same elements in the same order, false otherwise.
181
+    */
182
+    public boolean equals(Object other){
183
+        boolean result;
184
+        if(other == null)
185
+            // we know this is not null so can't be equal
186
+            result = false;
187
+        else if(this == other)
188
+            // quick check if this and other refer to same IntList object
189
+            result = true;
190
+        else if( this.getClass() != other.getClass() )
191
+            // other is not an IntList they can't be equal
192
+            result = false;
193
+        else{
194
+            // other is not null and refers to an IntList
195
+            GenericListVersion2 otherList = (GenericListVersion2)other;
196
+            result = this.size() == otherList.size();
197
+            int i = 0;
198
+            while(i < iSize && result){
199
+                result = this.iValues[i].equals( otherList.iValues[i] );
200
+                i++;
201
+            }
202
+        }
203
+        return result;     
204
+    }
205
+
206
+}
207
+
208
+

+ 9
- 0
CodeSamples/codeSamples/HelloWorld.java Bestand weergeven

@@ -0,0 +1,9 @@
1
+/* HelloWorld.java
2
+ */
3
+
4
+public class HelloWorld
5
+{
6
+	public static void main(String[] args) {
7
+		System.out.println("Hello World!");
8
+	}
9
+}

+ 12
- 0
CodeSamples/codeSamples/IntListTesterVer1.java Bestand weergeven

@@ -0,0 +1,12 @@
1
+
2
+public class IntListTesterVer1 {
3
+    public static void main(String[] args){
4
+        IntListVer1 list1 = new IntListVer1();
5
+        IntListVer1 list2 = new IntListVer1(100);
6
+        
7
+        //equal when empty?
8
+        System.out.println("list1.equals(list2): " + list1.equals(list2));
9
+        System.out.println("list1: " + list1);
10
+        System.out.println("list2: " + list2);
11
+    }
12
+}

+ 44
- 0
CodeSamples/codeSamples/IntListTesterVer2.java Bestand weergeven

@@ -0,0 +1,44 @@
1
+
2
+public class IntListTesterVer2 {
3
+    public static void main(String[] args){
4
+        IntListVer2 list1 = new IntListVer2();
5
+        IntListVer2 list2 = new IntListVer2(100);
6
+        
7
+        //equal when empty?
8
+        System.out.println("list1.equals(list2): " + list1.equals(list2));
9
+        System.out.println("list1: " + list1);
10
+        System.out.println("list2: " + list2);
11
+        
12
+        //add elements
13
+        for(int i = 0; i < 100; i += 5){
14
+            list1.add(i);
15
+            list2.add(i);
16
+        }
17
+        
18
+        System.out.println("list1.equals(list2): " + list1.equals(list2));
19
+        System.out.println("list1: " + list1);
20
+        System.out.println("list2: " + list2);
21
+        
22
+        list2.add(200);
23
+        System.out.println("Added 200 to list2.");
24
+        System.out.println("list1.equals(list2): " + list1.equals(list2));
25
+        System.out.println("list1: " + list1);
26
+        System.out.println("list2: " + list2);
27
+        
28
+        System.out.println("Testing efficieny of StringBuffer versus using String.");
29
+        System.out.println("Increasing list1 size to 10000.");
30
+        Stopwatch s = new Stopwatch();
31
+        list1 = new IntListVer2();
32
+        for(int i = 0; i < 10000; i++)
33
+            list1.add(i);
34
+        s.start();
35
+        list1.toString();
36
+        s.stop();
37
+        System.out.println("Time to build String using String class: " + s.toString() );
38
+        s.start();
39
+        list1.toStringUsingStringBuffer();
40
+        s.stop();
41
+        System.out.println("Time to build String using StringBuffer class: " + s.toString() );
42
+
43
+    }
44
+}

+ 41
- 0
CodeSamples/codeSamples/IntListVer1.java Bestand weergeven

@@ -0,0 +1,41 @@
1
+/**
2
+ * A class to provide a simple list of integers.
3
+ * List resizes automatically. Used to illustrate 
4
+ * various design and implementation details of 
5
+ * a class in Java.
6
+ * 
7
+ * Version 1 only contains the instance variables and
8
+ * the constructors
9
+ * @author scottm
10
+ *
11
+ */
12
+public class IntListVer1 {
13
+    // class constant for default size
14
+    private static final int DEFAULT_CAP = 10;
15
+    
16
+    //instance variables
17
+    private int[] iValues;
18
+    private int iSize;
19
+    
20
+    /**
21
+     * Default constructor. Creates an empty list.
22
+     */
23
+    public IntListVer1(){
24
+        //redirect to single int constructor
25
+        this(DEFAULT_CAP);
26
+        //other statments could go here.
27
+    }
28
+
29
+    /**
30
+     * Constructor to allow user of class to specify 
31
+     * initial capacity in case they intend to add a lot
32
+     * of elements to new list. Creates an empty list.
33
+     * @param initialCap > 0
34
+     */    
35
+    public IntListVer1(int initialCap) {
36
+        assert initialCap > 0 : "Violation of precondition. IntListVer1(int initialCap):"
37
+            + "initialCap must be greater than 0. Value of initialCap: " + initialCap;
38
+        iValues = new int[initialCap];
39
+        iSize = 0;
40
+    }
41
+}

+ 131
- 0
CodeSamples/codeSamples/IntListVer2.java Bestand weergeven

@@ -0,0 +1,131 @@
1
+/**
2
+ * A class to provide a simple list of integers.
3
+ * List resizes automatically. Used to illustrate 
4
+ * various design and implementation details of 
5
+ * a class in Java.
6
+ * 
7
+ * Version 1 only contains the instance variables and
8
+ * the constructors
9
+ * @author scottm
10
+ *
11
+ */
12
+public class IntListVer2{
13
+    // class constant for default size
14
+    private static final int DEFAULT_CAP = 10;
15
+    
16
+    //instance variables
17
+    // iValues store the elements of the list and 
18
+    // may have extra capacity
19
+    private int[] iValues;
20
+    private int iSize;
21
+    
22
+    /**
23
+     * Default add method. Add x to the end of this IntList.
24
+     * Size of the list goes up by 1.
25
+     * @param x The value to add to the end of this list.
26
+     */
27
+    public void add(int x){
28
+        // is there extra capacity available?
29
+        // if not, resize
30
+        if(iSize == iValues.length)
31
+            resize();
32
+        assert 0 <= iSize && iSize < iValues.length;
33
+        iValues[iSize] = x;
34
+        iSize++;
35
+    }
36
+    
37
+    // resize internal storage container by a factor of 2
38
+    private void resize() {
39
+        int[] temp = new int[iValues.length * 2];
40
+        System.arraycopy(iValues, 0, temp, 0, iValues.length);
41
+        iValues = temp;
42
+    }
43
+    
44
+    /**
45
+     * Return a String version of this list. Size and 
46
+     * elements included.
47
+     */
48
+    public String toString(){
49
+        // we could make this more effecient by using a StringBuffer.
50
+        // See alternative version
51
+        String result = "size: " + iSize + ", elements: [";
52
+        for(int i = 0; i < iSize - 1; i++)
53
+            result += iValues[i] + ", ";
54
+        if(iSize > 0 )
55
+            result += iValues[iSize - 1];
56
+        result += "]";
57
+        return result;
58
+    }
59
+    
60
+    // Would not really have this and toString available
61
+    // both included just for testing
62
+    public String toStringUsingStringBuffer(){
63
+        StringBuffer result = new StringBuffer();
64
+        result.append( "size: " );
65
+        result.append( iSize );
66
+        result.append(", elements: [");
67
+        for(int i = 0; i < iSize - 1; i++){
68
+            result.append(iValues[i]);
69
+            result.append(", ");
70
+        }
71
+        if( iSize > 0 )
72
+            result.append(iValues[iSize - 1]);
73
+        result.append("]");
74
+        return result.toString();
75
+    }
76
+
77
+    /**
78
+     * Default constructor. Creates an empty list.
79
+     */
80
+    public IntListVer2(){
81
+        //redirect to single int constructor
82
+        this(DEFAULT_CAP);
83
+        //other statments could go here.
84
+    }
85
+
86
+    /**
87
+     * Constructor to allow user of class to specify 
88
+     * initial capacity in case they intend to add a lot
89
+     * of elements to new list. Creates an empty list.
90
+     * @param initialCap > 0
91
+     */    
92
+    public IntListVer2(int initialCap) {
93
+        assert initialCap > 0 : "Violation of precondition. IntListVer1(int initialCap):"
94
+            + "initialCap must be greater than 0. Value of initialCap: " + initialCap;
95
+        iValues = new int[initialCap];
96
+        iSize = 0;
97
+    }
98
+    
99
+   /**
100
+    * Return true if this IntList is equal to other.<br>
101
+    * pre: none
102
+    * @param other The object to comapre to this
103
+    * @return true if other is a non null, IntList object
104
+    * that is the same size as this IntList and has the
105
+    * same elements in the same order, false otherwise.
106
+    */
107
+    public boolean equals(Object other){
108
+        boolean result;
109
+        if(other == null)
110
+            // we know this is not null so can't be equal
111
+            result = false;
112
+        else if(this == other)
113
+            // quick check if this and other refer to same IntList object
114
+            result = true;
115
+        else if( this.getClass() != other.getClass() )
116
+            // other is not an IntList they can't be equal
117
+            result = false;
118
+        else{
119
+            // other ris not null and refers to an IntList
120
+            IntListVer2 otherIntList = (IntListVer2)other;
121
+            result = this.iSize == otherIntList.iSize;
122
+            int i = 0;
123
+            while(i < iSize && result){
124
+                result = this.iValues[i] == otherIntList.iValues[i];
125
+                i++;
126
+            }
127
+        }
128
+        return result;     
129
+    }
130
+
131
+}

+ 190
- 0
CodeSamples/codeSamples/IntListVer3.java Bestand weergeven

@@ -0,0 +1,190 @@
1
+/**
2
+ * A class to provide a simple list of integers.
3
+ * List resizes automatically. Used to illustrate 
4
+ * various design and implementation details of 
5
+ * a class in Java.
6
+ * 
7
+ * Version 3 added the insert and remove methods. Changed the
8
+ * add method to rely on insert.
9
+ * @author scottm
10
+ *
11
+ */
12
+public class IntListVer3{
13
+    // class constant for default size
14
+    private static final int DEFAULT_CAP = 10;
15
+    
16
+    //instance variables
17
+    // iValues store the elements of the list and 
18
+    // may have extra capacity
19
+    private int[] iValues;
20
+    private int iSize;
21
+    
22
+    /**
23
+     * Default constructor. Creates an empty list.
24
+     */
25
+    public IntListVer3(){
26
+        //redirect to single int constructor
27
+        this(DEFAULT_CAP);
28
+        //other statments could go here.
29
+    }
30
+
31
+    /**
32
+     * Constructor to allow user of class to specify 
33
+     * initial capacity in case they intend to add a lot
34
+     * of elements to new list. Creates an empty list.
35
+     * @param initialCap > 0
36
+     */    
37
+    public IntListVer3(int initialCap) {
38
+        assert initialCap > 0 : "Violation of precondition. IntListVer1(int initialCap):"
39
+            + "initialCap must be greater than 0. Value of initialCap: " + initialCap;
40
+        iValues = new int[initialCap];
41
+        iSize = 0;
42
+    }
43
+    
44
+    /**
45
+     * Default add method. Add x to the end of this IntList.
46
+     * Size of the list goes up by 1.
47
+     * @param x The value to add to the end of this list.
48
+     */
49
+    public void add(int x){
50
+        //example of loose coupling
51
+        insert(iSize, x);
52
+    }
53
+    
54
+    /**
55
+     * Retrieve an element from the list based on position.
56
+     * @param pos 0 <= pos < size()
57
+     * @return The element at the given position.
58
+     */
59
+    public int get(int pos){
60
+        assert 0 <= pos && pos < size() : "Failed precondition get. " +
61
+        		"pos it out of bounds. Value of pos: " + pos;
62
+        return iValues[pos];
63
+    }
64
+    
65
+    /**
66
+     * Insert x at position pos. Elements with a position equal
67
+     * to pos or more are shifted to the right. (One added to their
68
+     * position.)
69
+     * post: get(pos) = x, size() = old size() + 1
70
+     * @param pos 0 <= pos <= size()
71
+     * @param x
72
+     */
73
+    public void insert(int pos, int x){
74
+        assert 0 <= pos && pos <= size() : "Failed precondition insert. " +
75
+        "pos is invalid. Value of pos: " + pos;
76
+        ensureCapcity();
77
+        for(int i = iSize; i > pos; i--){
78
+            iValues[i] = iValues[i - 1];
79
+        }
80
+        iValues[pos] = x;
81
+        iSize++;
82
+    }
83
+    
84
+    /**
85
+     * Remove an element from the list based on position.
86
+     * Elements with a position greater than pos
87
+     * are shifted to the left. (One subtracted from their
88
+     * position.)
89
+     * @param pos 0 <= pos < size()
90
+     * @return The element that is removed.
91
+     */
92
+    public int remove(int pos){
93
+        assert 0 <= pos && pos < size() : "Failed precondition remove. " +
94
+        "pos it out of bounds. Value of pos: " + pos;
95
+        int removedValue = iValues[pos];
96
+        for(int i = pos; i < iSize - 1; i++)
97
+            iValues[i] = iValues[i + 1];
98
+        iSize--;
99
+        return removedValue;
100
+    }
101
+    
102
+    private void ensureCapcity(){
103
+        // is there extra capacity available?
104
+        // if not, resize
105
+        if(iSize == iValues.length)
106
+            resize();
107
+    }
108
+    
109
+    /**
110
+     * Returns the size of the list.
111
+     * @return The size of the list.
112
+     */
113
+    public int size(){
114
+        return iSize;
115
+    }
116
+    
117
+    // resize internal storage container by a factor of 2
118
+    private void resize() {
119
+        int[] temp = new int[iValues.length * 2];
120
+        System.arraycopy(iValues, 0, temp, 0, iValues.length);
121
+        iValues = temp;
122
+    }
123
+    
124
+    /**
125
+     * Return a String version of this list. Size and 
126
+     * elements included.
127
+     */
128
+    public String toString(){
129
+        // we could make this more effecient by using a StringBuffer.
130
+        // See alternative version
131
+        String result = "size: " + iSize + ", elements: [";
132
+        for(int i = 0; i < iSize - 1; i++)
133
+            result += iValues[i] + ", ";
134
+        if(iSize > 0 )
135
+            result += iValues[iSize - 1];
136
+        result += "]";
137
+        return result;
138
+    }
139
+    
140
+    // Would not really have this and toString available
141
+    // both included just for testing
142
+    public String toStringUsingStringBuffer(){
143
+        StringBuffer result = new StringBuffer();
144
+        result.append( "size: " );
145
+        result.append( iSize );
146
+        result.append(", elements: [");
147
+        for(int i = 0; i < iSize - 1; i++){
148
+            result.append(iValues[i]);
149
+            result.append(", ");
150
+        }
151
+        if( iSize > 0 )
152
+            result.append(iValues[iSize - 1]);
153
+        result.append("]");
154
+        return result.toString();
155
+    }
156
+    
157
+   /**
158
+    * Return true if this IntList is equal to other.<br>
159
+    * pre: none
160
+    * @param other The object to comapre to this
161
+    * @return true if other is a non null, IntList object
162
+    * that is the same size as this IntList and has the
163
+    * same elements in the same order, false otherwise.
164
+    */
165
+    public boolean equals(Object other){
166
+        boolean result;
167
+        if(other == null)
168
+            // we know this is not null so can't be equal
169
+            result = false;
170
+        else if(this == other)
171
+            // quick check if this and other refer to same IntList object
172
+            result = true;
173
+        else if( this.getClass() != other.getClass() )
174
+            // other is not an IntList they can't be equal
175
+            result = false;
176
+        else{
177
+            // other is not null and refers to an IntList
178
+            IntListVer3 otherIntList = (IntListVer3)other;
179
+            result = this.size() == otherIntList.size();
180
+            int i = 0;
181
+            while(i < iSize && result){
182
+                result = this.iValues[i] == otherIntList.iValues[i];
183
+                i++;
184
+            }
185
+        }
186
+        return result;     
187
+    }
188
+
189
+}
190
+

+ 81
- 0
CodeSamples/codeSamples/Life.java Bestand weergeven

@@ -0,0 +1,81 @@
1
+import java.util.Scanner;
2
+
3
+public class Life {
4
+    public static void show(boolean[][] grid){
5
+        String s = "";
6
+        for(boolean[] row : grid){
7
+            for(boolean val : row)
8
+                if(val)
9
+                    s += "*";
10
+                else
11
+                    s += ".";
12
+            s += "\n";
13
+        }
14
+        System.out.println(s);
15
+    }
16
+    
17
+    public static boolean[][] gen(){
18
+        boolean[][] grid = new boolean[10][10];
19
+        for(int r = 0; r < 10; r++)
20
+            for(int c = 0; c < 10; c++)
21
+                if( Math.random() > 0.7 )
22
+                    grid[r][c] = true;
23
+        return grid;
24
+    }
25
+    
26
+    public static void main(String[] args){
27
+        boolean[][] world = gen();
28
+        show(world);
29
+        System.out.println();
30
+        world = nextGen(world);
31
+        show(world);
32
+        Scanner s = new Scanner(System.in);
33
+        while(s.nextLine().length() == 0){
34
+            System.out.println();
35
+            world = nextGen(world);
36
+            show(world);
37
+            
38
+        }
39
+    }
40
+    
41
+    public static boolean[][] nextGen(boolean[][] world){
42
+        boolean[][] newWorld 
43
+            = new boolean[world.length][world[0].length];
44
+        int num;
45
+        for(int r = 0; r < world.length; r++){
46
+            for(int c = 0; c < world[0].length; c++){
47
+                num = numNeighbors(world, r, c);
48
+                if( occupiedNext(num, world[r][c]) )
49
+                    newWorld[r][c] = true;
50
+            }
51
+        }
52
+        return newWorld;
53
+    }
54
+    
55
+    public static boolean occupiedNext(int numNeighbors, boolean occupied){
56
+        if( occupied && (numNeighbors == 2 || numNeighbors == 3))
57
+            return true;
58
+        else if (!occupied && numNeighbors == 3)
59
+            return true;
60
+        else
61
+            return false;
62
+    }
63
+
64
+    private static int numNeighbors(boolean[][] world, int row, int col) {
65
+        int num = world[row][col] ? -1 : 0;
66
+        for(int r = row - 1; r <= row + 1; r++)
67
+            for(int c = col - 1; c <= col + 1; c++)
68
+                if( inbounds(world, r, c) && world[r][c] )
69
+                    num++;
70
+
71
+        return num;
72
+    }
73
+
74
+    private static boolean inbounds(boolean[][] world, int r, int c) {
75
+        return r >= 0 && r < world.length && c >= 0 &&
76
+        c < world[0].length;
77
+    }
78
+    
79
+    
80
+    
81
+}

+ 147
- 0
CodeSamples/codeSamples/LinkedList.java Bestand weergeven

@@ -0,0 +1,147 @@
1
+package Fall0811;
2
+
3
+import java.util.Iterator;
4
+
5
+import Summer08.Node;
6
+
7
+public class LinkedList implements Iterable {
8
+    private Node head;
9
+    private Node tail;
10
+    private int size;
11
+    
12
+    public Iterator iterator(){
13
+        return new LLIterator();
14
+    }
15
+    
16
+    private class LLIterator implements Iterator{
17
+        private Node nextNode;
18
+        private boolean removeOK;
19
+        private int posToRemove;
20
+        
21
+        private LLIterator(){
22
+            nextNode = head;
23
+            removeOK = false;
24
+            posToRemove = -1;
25
+        }
26
+        
27
+        public boolean hasNext(){
28
+            return nextNode != null;
29
+        }
30
+        
31
+        public Object next(){
32
+            assert hasNext();
33
+            
34
+            Object result = nextNode.getData();
35
+            nextNode = nextNode.getNext();
36
+            
37
+            removeOK = true;
38
+            posToRemove++;
39
+            
40
+            return result;
41
+        }
42
+        
43
+        public void remove(){
44
+            assert removeOK;
45
+            removeOK = false;
46
+            LinkedList.this.remove(posToRemove);
47
+            posToRemove--;
48
+        }
49
+    }
50
+    
51
+    public void makeEmpty(){
52
+        // let GC do its job!!!!!!!
53
+        head = tail = null;
54
+        size = 0;
55
+    }
56
+    
57
+    public Object remove(int pos){
58
+        assert pos >= 0 && pos < size;
59
+        Object result;
60
+        if( pos == 0 ){
61
+            result = head.getData();
62
+            head = head.getNext();
63
+            if( size == 1 )
64
+                tail = null;
65
+        }
66
+        else{    
67
+            Node temp = head;
68
+            for(int i = 1; i < pos; i++)
69
+                temp = temp.getNext();
70
+            result = temp.getNext().getData();
71
+            temp.setNext( temp.getNext().getNext() );
72
+            if( pos == size - 1)
73
+                tail = temp;
74
+        }
75
+        size--;
76
+        return result;
77
+    }
78
+    
79
+    public Object get(int pos){
80
+        assert pos >= 0 && pos < size;
81
+        // array based list
82
+        // return myCon[pos]
83
+        Object result;
84
+        if( pos == size - 1 )
85
+            result = tail.getData(); //O(1)
86
+        else{
87
+            Node temp = head;
88
+            for(int i = 0; i < pos; i++)
89
+                temp = temp.getNext();
90
+            result = temp.getData();
91
+            // average case O(N) :((((
92
+        }
93
+        return result;
94
+    }
95
+    
96
+    public void insert(int pos, Object obj){
97
+        assert pos >= 0 && pos <= size;
98
+        
99
+        // addFirst?
100
+        if(pos == 0)
101
+            addFirst(obj); // O(1)
102
+        // add last?
103
+        else if( pos == size )
104
+            add(obj); //at end O(1)
105
+        else{
106
+            // general case
107
+            Node temp = head;
108
+            for(int i = 1; i < pos; i++)
109
+                temp = temp.getNext();
110
+            // I know temp is pointing at the
111
+            // node at position pos - 1
112
+            Node newNode = new Node(obj, temp.getNext());
113
+            temp.setNext( newNode );
114
+            size++;
115
+        }
116
+    }
117
+    
118
+    public void add(Object obj){
119
+        Node newNode = new Node(obj, null);
120
+        if( size == 0 )
121
+            head = newNode;
122
+        else
123
+            tail.setNext(newNode);
124
+        tail = newNode;
125
+        size++;
126
+    }
127
+    
128
+    public void addFirst(Object obj){
129
+        if(size == 0)
130
+            add(obj);
131
+        else{
132
+            Node newNode = new Node(obj, head);
133
+            head = newNode;
134
+            size++;
135
+        }
136
+    }
137
+    
138
+    public String toString(){
139
+        String result = "";
140
+        Node temp = head;
141
+        for(int i = 0; i < size; i++){
142
+            result += temp.getData() + " ";
143
+            temp = temp.getNext();
144
+        }
145
+        return result;
146
+    }
147
+}

+ 75
- 0
CodeSamples/codeSamples/ListNode.java Bestand weergeven

@@ -0,0 +1,75 @@
1
+/**
2
+ * A class that represents a node to be used in a linked list.
3
+ * These nodes are singly linked.
4
+ *
5
+ * @author Mike Scott
6
+ * @version July 27, 2005
7
+ */
8
+
9
+ public class ListNode
10
+ {
11
+	 // instance variables
12
+
13
+	// the data to store in this node
14
+	private Object myData;
15
+
16
+	// the link to the next node (presumably in a list)
17
+	private ListNode myNext;
18
+
19
+	/**
20
+	 * default constructor
21
+	 * pre: none<br>
22
+	 * post: getData() = null, getNext() = null
23
+	 */
24
+	public ListNode()
25
+	{	this(null, null);
26
+	}
27
+
28
+	/**
29
+	 * create a ListNode that holds the specified data and refers to the specified next element
30
+	 * pre: none<br>
31
+	 * post: getData() = item, getNext() = next
32
+	 * @param item the  data this ListNode should hold
33
+	 * @param next the next node in the list
34
+	 */
35
+	public ListNode(Object data, ListNode next)
36
+	{	myData = data;
37
+		myNext = next;
38
+	}
39
+
40
+	
41
+	/**
42
+	 * return the data in this node
43
+	 * pre: none<br>
44
+	 * @return the data this ListNode holds
45
+	 */
46
+	public Object getData()
47
+	{	return myData;	}
48
+
49
+	
50
+	/**
51
+	 * return the ListNode this ListNode refers to
52
+	 * pre: none<br>
53
+	 * @return the ListNode this ListNode refers to (normally the next one in a list)
54
+	 */
55
+	public ListNode getNext()
56
+	{	return myNext;	}
57
+
58
+
59
+	/**
60
+	 * set the data in this node
61
+	 * The old data is over written.<br>
62
+	 * pre: none<br>
63
+	 * @param data the new data for this ListNode to hold
64
+	 */
65
+	public void setData(Object data)
66
+	{	myData = data;	}
67
+
68
+	/**
69
+	 * set the next node this ListNode refers to
70
+	 * pre: none<br>
71
+	 * @param next the next node this ListNode should refer to
72
+	 */
73
+	public void setNext(ListNode next)
74
+	{	myNext = next;	}
75
+ }

+ 20
- 0
CodeSamples/codeSamples/MineSweeper.java Bestand weergeven

@@ -0,0 +1,20 @@
1
+public class MineSweeper
2
+{	private int[][] myTruth;
3
+	private boolean[][] myShow;
4
+	
5
+	public void cellPicked(int row, int col)
6
+	{	if( inBounds(row, col) && !myShow[row][col] )
7
+		{	myShow[row][col] = true;
8
+		
9
+			if( myTruth[row][col] == 0)
10
+			{	for(int r = -1; r <= 1; r++)
11
+					for(int c = -1; c <= 1; c++)
12
+						cellPicked(row + r, col + c);
13
+			}	
14
+		}
15
+	}
16
+	
17
+	public boolean inBounds(int row, int col)
18
+	{	return 0 <= row && row < myTruth.length && 0 <= col && col < myTruth[0].length;
19
+	}
20
+}

+ 35
- 0
CodeSamples/codeSamples/ObjectVarsAsParameters.java Bestand weergeven

@@ -0,0 +1,35 @@
1
+import java.awt.Rectangle;
2
+
3
+public class ObjectVarsAsParameters
4
+{	public static void main(String[] args)
5
+	{	go();
6
+	}
7
+	
8
+	public static void go()
9
+	{	Rectangle r1 = new Rectangle(0,0,5,5);
10
+		System.out.println("In method go. r1 " + r1 + "\n");
11
+		// could have been 
12
+		//System.out.prinltn("r1" + r1.toString());
13
+		r1.setSize(10, 15);
14
+		System.out.println("In method go. r1 " + r1 + "\n");
15
+		alterPointee(r1);
16
+		System.out.println("In method go. r1 " + r1 + "\n");
17
+		
18
+		alterPointer(r1);
19
+		System.out.println("In method go. r1 " + r1 + "\n");
20
+	}
21
+	
22
+	public static void alterPointee(Rectangle r)
23
+	{	System.out.println("In method alterPointee. r " + r + "\n");
24
+		r.setSize(20, 30);
25
+		System.out.println("In method alterPointee. r " + r + "\n");
26
+	}
27
+	
28
+	public static void alterPointer(Rectangle r)
29
+	{	System.out.println("In method alterPointer. r " + r + "\n");
30
+		r = new Rectangle(5, 10, 30, 35);
31
+		System.out.println("In method alterPointer. r " + r + "\n");
32
+	}
33
+	
34
+	
35
+}

+ 102
- 0
CodeSamples/codeSamples/PrimeEx.java Bestand weergeven

@@ -0,0 +1,102 @@
1
+import java.math.BigInteger;
2
+import java.util.Random;
3
+
4
+public class PrimeEx {
5
+
6
+	/**
7
+	 * @param args
8
+	 */
9
+	public static void main(String[] args) {
10
+		printTest(10, 4);
11
+		printTest(2, 2);
12
+		printTest(54161329, 4);
13
+		printTest(1882341361, 2);
14
+		printTest(36, 9);
15
+
16
+		System.out.println(isPrime(54161329) + " expect false");
17
+		System.out.println(isPrime(1882341361) + " expect true");
18
+		System.out.println(isPrime(2) + " expect true");
19
+		int numPrimes = 0;
20
+		Stopwatch s = new Stopwatch();
21
+		s.start();
22
+		for(int i = 2; i < 10000000; i++) {
23
+			if(isPrime(i)) {
24
+				numPrimes++;
25
+			}
26
+		}
27
+		s.stop();
28
+		System.out.println(numPrimes + " " + s);
29
+		s.start();
30
+		boolean[] primes = getPrimes(10000000);
31
+		int np = 0;
32
+		for(boolean b : primes)
33
+			if(b)
34
+				np++;
35
+		s.stop();
36
+		System.out.println(np + " " + s);
37
+
38
+		System.out.println(new BigInteger(1024, 10, new Random()));
39
+	}
40
+
41
+	public static boolean[] getPrimes(int max) {
42
+		boolean[] result = new boolean[max + 1];
43
+		for(int i = 2; i < result.length; i++)
44
+			result[i] = true;
45
+		final double LIMIT = Math.sqrt(max);
46
+		for(int i = 2; i <= LIMIT; i++) {
47
+			if(result[i]) {
48
+				// cross out all multiples;
49
+				int index = 2 * i;
50
+				while(index < result.length){
51
+					result[index] = false;
52
+					 index += i;
53
+				}
54
+			}
55
+		}
56
+		return result;
57
+	}
58
+
59
+
60
+	public static void printTest(int num, int expectedFactors) {
61
+		Stopwatch st = new Stopwatch();
62
+		st.start();
63
+		int actualFactors = numFactors(num);
64
+		st.stop();
65
+		System.out.println("Testing " + num + " expect " + expectedFactors + ", " +
66
+				"actual " + actualFactors);
67
+		if(actualFactors == expectedFactors)
68
+			System.out.println("PASSED");
69
+		else
70
+			System.out.println("FAILED");
71
+		System.out.println(st.time());
72
+	}
73
+
74
+	// pre: num >= 2
75
+	public static boolean isPrime(int num) {
76
+		assert num >= 2 : "failed precondition. num must be >= 2. num: " + num;
77
+		final double LIMIT = Math.sqrt(num);
78
+		boolean isPrime = (num == 2) ? true : num % 2 != 0;
79
+		int div = 3;
80
+		while(div <= LIMIT && isPrime) {
81
+			isPrime = num % div != 0;
82
+			div += 2;
83
+		}
84
+		return isPrime;
85
+	}
86
+
87
+	// pre: num >= 2
88
+	public static int numFactors(int num) {
89
+		assert num >= 2 : "failed precondition. num must be >= 2. num: " + num;
90
+		int result = 0;
91
+		final double SQRT = Math.sqrt(num);
92
+		for(int i = 1; i < SQRT; i++) {
93
+			if(num % i == 0) {
94
+				result += 2;
95
+			}
96
+		}
97
+		if(num % SQRT == 0)
98
+			result++;
99
+		return result;
100
+	}
101
+
102
+}

+ 33
- 0
CodeSamples/codeSamples/PrimitiveParameters.java Bestand weergeven

@@ -0,0 +1,33 @@
1
+public class PrimitiveParameters
2
+{	
3
+	public static void main(String[] args)
4
+	{	go();
5
+	}
6
+	
7
+	public static void go()
8
+	{	int x = 3;
9
+		int y = 2;
10
+		System.out.println("In method go. x: " + x + " y: " + y);
11
+		falseSwap(x,y);
12
+		System.out.println("in method go. x: " + x + " y: " + y);
13
+		moreParameters(x,y);
14
+		System.out.println("in method go. x: " + x + " y: " + y);
15
+	}
16
+	
17
+	public static void falseSwap(int x, int y)
18
+	{	System.out.println("in method falseSwap. x: " + x + " y: " + y);
19
+		int temp = x;
20
+		x = y;
21
+		y = temp;
22
+		System.out.println("in method falseSwap. x: " + x + " y: " + y);
23
+	}
24
+	
25
+	public static void moreParameters(int a, int b)
26
+	{	System.out.println("in method moreParameters. a: " + a + " b: " + b);
27
+		a = a * b;
28
+		b = 12;
29
+		System.out.println("in method moreParameters. a: " + a + " b: " + b);
30
+		falseSwap(b,a);
31
+		System.out.println("in method moreParameters. a: " + a + " b: " + b);	
32
+	}
33
+}

+ 18
- 0
CodeSamples/codeSamples/ReadAndPrintScores.java Bestand weergeven

@@ -0,0 +1,18 @@
1
+import java.util.Scanner;
2
+import java.io.File;
3
+import java.io.IOException;
4
+
5
+public class ReadAndPrintScores
6
+{
7
+    public static void main(String[] args)
8
+    {	try
9
+	{   Scanner s = new Scanner( new File("scores.dat") );
10
+	    while( s.hasNextInt() )
11
+	    {	System.out.println( s.nextInt() );
12
+	    }
13
+	}
14
+	catch(IOException e)
15
+	{	System.out.println( e );
16
+	}
17
+    }
18
+}

+ 110
- 0
CodeSamples/codeSamples/RecursionExampleDirectory.java Bestand weergeven

@@ -0,0 +1,110 @@
1
+public class RecursionExampleDirectory
2
+{	
3
+	public int getSize(Directory dir)
4
+	{	int total = 0;
5
+	
6
+		//check files
7
+		File[] files = dir.getFiles();
8
+		for(int i = 0; i < files.length; i++)
9
+			total += files[i].getSize();
10
+			
11
+		//get sub directories and check them
12
+		Directory[] subs = dir.getSubs();
13
+		for(int i = 0; i < subs.length; i++)
14
+			total += getSize(subs[i]);
15
+			
16
+		return total;
17
+	}
18
+	
19
+	public static void main(String[] args)
20
+	{	RecursionExampleDirectory r = new RecursionExampleDirectory();
21
+		Directory d = new Directory();
22
+		System.out.println( r.getSize(d) );
23
+	}
24
+	
25
+	//pre: n >= 0
26
+	public static int fact(int n)
27
+	{	int result = 0;
28
+		if(n == 0)
29
+			result = 1;
30
+		else
31
+			result = n * fact(n-1);
32
+		return result;
33
+	}
34
+	
35
+	//pre: exp >= 0
36
+	public static int pow(int base, int exp)
37
+	{	int result = 0;
38
+		if(exp == 0)
39
+			result = 1;
40
+		else
41
+			result = base * pow(base, exp - 1);
42
+		return result;
43
+	}
44
+	
45
+	//slow fib
46
+	//pre: n >= 1
47
+	public static int fib(int n)
48
+	{	int result = 0;
49
+		if(n == 1 || n == 2)
50
+			result = 1;
51
+		else
52
+			result = fib(n-1) + fib(n-2);
53
+		return result;
54
+	}
55
+	
56
+	public static int minWasted(int[] items, int itemNum, int capLeft)
57
+	{	int result = 0;
58
+		if(itemNum >= items.length)
59
+			result = capLeft;
60
+		else if( capLeft == 0)
61
+			result = 0;
62
+		else
63
+		{	int minWithout = minWasted(items, itemNum + 1, capLeft);
64
+			if( capLeft <= items[itemNum])		
65
+			{	int minWith = minWasted(items, itemNum + 1, capLeft - items[itemNum]);
66
+				result = Math.min(minWith, minWithout);
67
+			}
68
+			else
69
+				result = minWithout;
70
+		}
71
+		return result;	
72
+	}
73
+}
74
+
75
+class Directory
76
+{	private Directory[] mySubs;
77
+	private File[] myFiles;
78
+	
79
+	public Directory()
80
+	{	int numSubs = (int)(Math.random() * 3);
81
+		mySubs = new Directory[numSubs];
82
+		int numFiles = (int)(Math.random() * 10);
83
+		myFiles = new File[numFiles];
84
+		
85
+		for(int i = 0; i < myFiles.length; i++)
86
+			myFiles[i] = new File( (int)(Math.random() * 1000 ) );
87
+		for(int i = 0; i < mySubs.length; i++)
88
+			mySubs[i] = new Directory();
89
+	}
90
+	
91
+	public Directory[] getSubs()
92
+	{	return mySubs;
93
+	}
94
+	
95
+	public File[] getFiles()
96
+	{	return myFiles;
97
+	}
98
+}
99
+
100
+class File
101
+{	private int iMySize;
102
+
103
+	public File(int size)
104
+	{	iMySize = size;
105
+	}
106
+	
107
+	public int getSize()
108
+	{	return iMySize;
109
+	}
110
+}

+ 12
- 0
CodeSamples/codeSamples/ScannerAndKeyboard.java Bestand weergeven

@@ -0,0 +1,12 @@
1
+import java.util.Scanner;
2
+
3
+public class ScannerAndKeyboard
4
+{
5
+
6
+	public static void main(String[] args)
7
+	{	Scanner s = new Scanner(System.in);
8
+		System.out.print( "Enter your name: "  );
9
+		String name = s.nextLine();
10
+		System.out.println( "Hello " + name + "!" );
11
+	}
12
+}

+ 34
- 0
CodeSamples/codeSamples/SimpleWordCounter.java Bestand weergeven

@@ -0,0 +1,34 @@
1
+
2
+import java.io.File;
3
+import java.io.IOException;
4
+import java.util.Map;
5
+import java.util.Scanner;
6
+import java.util.TreeMap;
7
+
8
+public class SimpleWordCounter {
9
+    
10
+    public static void main(String[] args) {
11
+        try {
12
+            File f = new File("ciaFactBook2008.txt");
13
+            Scanner sc;
14
+            sc = new Scanner(f);
15
+            // sc.useDelimiter("[^a-zA-Z']+");
16
+            Map<String, Integer> wordCount = new TreeMap<String, Integer>();
17
+            while(sc.hasNext()) {
18
+                String word = sc.next();
19
+                if(!wordCount.containsKey(word))
20
+                    wordCount.put(word, 1);
21
+                else
22
+                    wordCount.put(word, wordCount.get(word) + 1);
23
+            }
24
+            
25
+            // show results
26
+            for(String word : wordCount.keySet())
27
+                System.out.println(word + " " + wordCount.get(word));
28
+            System.out.println(wordCount.size());
29
+        }
30
+        catch(IOException e) {
31
+            System.out.println("Unable to read from file.");
32
+        }
33
+    }
34
+}

+ 22
- 0
CodeSamples/codeSamples/SortedIntList.java Bestand weergeven

@@ -0,0 +1,22 @@
1
+public class SortedIntList extends IntListVer3{
2
+    
3
+    public SortedIntList(int initialCap){
4
+        //call IntList constructor
5
+        super(initialCap);
6
+    }
7
+    
8
+    public SortedIntList(){
9
+        super();
10
+    }
11
+    
12
+    //override add
13
+    public void add(int value){
14
+        //search for location to insert value
15
+        int pos = 0;
16
+        while( pos < size() && value > get(pos) ){
17
+            pos++;
18
+        }
19
+        super.insert(pos, value);
20
+    }
21
+    
22
+}

+ 27
- 0
CodeSamples/codeSamples/StringExample.java Bestand weergeven

@@ -0,0 +1,27 @@
1
+public class StringExample
2
+{	public static void main(String[] args)
3
+	{	String s1 = "Computer Science";
4
+		int x = 307;
5
+		String s2 = s1 + " " + x;
6
+		String s3 = s2.substring(10,17);
7
+		String s4 = "is fun";
8
+		String s5 = s2 + s4;
9
+		
10
+		System.out.println("s1: " + s1);
11
+		System.out.println("s2: " + s2);
12
+		System.out.println("s3: " + s3);
13
+		System.out.println("s4: " + s4);
14
+		System.out.println("s5: " + s5);
15
+		
16
+		//showing effect of precedence
17
+		
18
+		x = 3;
19
+		int y = 5;
20
+		String s6 = x + y + "total";
21
+		String s7 = "total " + x + y;
22
+		String s8 = " " + x + y + "total";
23
+		System.out.println("s6: " + s6);
24
+		System.out.println("s7: " + s7);
25
+		System.out.println("s8: " + s8);
26
+	}
27
+}

+ 26
- 0
CodeSamples/codeSamples/URLExpSimple.java Bestand weergeven

@@ -0,0 +1,26 @@
1
+import java.io.InputStreamReader;
2
+import java.net.URL;
3
+import java.net.URLConnection;
4
+import java.util.Scanner;
5
+
6
+
7
+public class URLExpSimple {
8
+
9
+    
10
+    public static void main(String[] args) {
11
+        try {
12
+            URL mySite = new URL("http://www.cs.utexas.edu/~scottm");
13
+            URLConnection yc = mySite.openConnection();
14
+            Scanner in = new Scanner(new InputStreamReader(yc.getInputStream()));
15
+            int count = 0;
16
+            while (in.hasNext()) {
17
+                System.out.println(in.next());
18
+                count++;
19
+            }
20
+            System.out.println("Number of tokens: " + count);
21
+            in.close();
22
+        } catch (Exception e) {
23
+            e.printStackTrace();
24
+        }
25
+    }
26
+}

+ 46
- 0
CodeSamples/codeSamples/UnsortedHashSet.java Bestand weergeven

@@ -0,0 +1,46 @@
1
+
2
+
3
+import java.util.LinkedList;
4
+import java.lang.reflect.Array;
5
+
6
+public class UnsortedHashSet<E> {
7
+   
8
+    private static final double LOAD_FACTOR_LIMIT = 0.7;
9
+    
10
+    private int size;
11
+    private LinkedList<E>[] con;
12
+    
13
+    public UnsortedHashSet() {
14
+        con  = (LinkedList<E>[])(new LinkedList[10]);
15
+    }
16
+    
17
+    public boolean add(E obj) {
18
+        int oldSize = size;
19
+        int index = Math.abs(obj.hashCode()) % con.length;
20
+        if(con[index] == null)
21
+            con[index] = new LinkedList<E>();
22
+        if(!con[index].contains(obj)) {
23
+            con[index].add(obj);
24
+            size++;
25
+            
26
+        }
27
+        if(1.0 * size / con.length > LOAD_FACTOR_LIMIT)
28
+            resize();
29
+        return oldSize != size;
30
+    }
31
+
32
+    private void resize() {
33
+        UnsortedHashSet<E> temp = new UnsortedHashSet<E>();
34
+        temp.con = (LinkedList<E>[])(new LinkedList[con.length * 2 + 1]);
35
+        for(int i = 0; i < con.length; i++){
36
+            if(con[i] != null)
37
+                for(E e : con[i])
38
+                    temp.add(e);
39
+        }
40
+        con = temp.con;
41
+    }
42
+    
43
+    public int size() {
44
+        return size;
45
+    }
46
+}

+ 136
- 0
CodeSamples/codeSamples/UnsortedSetTest.java Bestand weergeven

@@ -0,0 +1,136 @@
1
+package Solution;
2
+
3
+
4
+import java.io.File;
5
+import java.lang.reflect.Method;
6
+import java.util.Arrays;
7
+import java.util.Collection;
8
+import java.util.HashSet;
9
+import java.util.Scanner;
10
+import java.util.TreeSet;
11
+
12
+public class UnsortedSetTest {
13
+
14
+    public static void main(String[] args) throws Exception {
15
+        String[] allFileNames = {"hounds.txt", "huckfinn.txt", "oz.txt", "war.txt", "ciaFactBook2008.txt"};
16
+        String[] noCIA = {"hounds.txt", "huckfinn.txt", "oz.txt", "war.txt"};
17
+        countWords(new BinarySearchTree<String>(), allFileNames[0]);
18
+        for(String s : allFileNames) {
19
+            System.out.println(s);
20
+            countWordsOurUnsortedSet(s);
21
+            countWordsOurBinarySearchTree(s);
22
+            countWordsOurHash(s);
23
+            countWordsCollection(new TreeSet<String>(), s);
24
+            int[] result = countWordsCollection(new HashSet<String>(), s);
25
+            System.out.println(result[0] + " total words.");
26
+            System.out.println(result[1] + " distinct words.");
27
+            System.out.println();
28
+            
29
+        }
30
+    }
31
+    
32
+    // return total num words, and num distinct words
33
+    public static int[] countWordsCollection(Collection<String> c, String fileName) throws Exception{
34
+        c.clear();
35
+        Scanner fileScanner = new Scanner(new File(fileName));  
36
+        Stopwatch st = new Stopwatch();
37
+        st.start();
38
+        int total = 0;
39
+        while(fileScanner.hasNext()){
40
+            c.add(fileScanner.next());
41
+            total++;
42
+        }
43
+        st.stop();
44
+        System.out.println("Time for " + c.getClass() + " : \n" + st);
45
+//        System.out.println(c.size() + " distinct words");
46
+//        System.out.println(total + " total words including duplicates: ");
47
+        assert total >= c.size();
48
+        System.out.println();
49
+        return new int[]{total, c.size()};
50
+    }
51
+    
52
+    
53
+    // GACKY GACKY GACKY repition. Look into removing repetition with reflection
54
+    // we assume there will be add and size methods
55
+    public static int[] countWordsOurHash(String fileName) throws Exception {
56
+        Scanner fileScanner = new Scanner(new File(fileName));  
57
+        Stopwatch st = new Stopwatch();
58
+        UnsortedHashSet<String> c = new UnsortedHashSet<String>();
59
+        st.start();
60
+        int total = 0;
61
+        while(fileScanner.hasNext()) {
62
+            c.add(fileScanner.next());
63
+            total++;
64
+        }
65
+        st.stop();
66
+        System.out.println("Time for our hashtable (closed address hashing): \n" + st);
67
+//        System.out.println(c.size() + " distinct words");
68
+//        System.out.println(total + " total words including duplicates: ");
69
+        assert total >= c.size();
70
+        System.out.println();
71
+        return new int[]{total, c.size()};
72
+    }
73
+    
74
+    public static int[] countWordsOurUnsortedSet(String fileName) throws Exception {
75
+        Scanner fileScanner = new Scanner(new File(fileName));  
76
+        Stopwatch st = new Stopwatch();
77
+        UnsortedSet<String> c = new UnsortedSet<String>();
78
+        st.start();
79
+        int total = 0;
80
+        while(fileScanner.hasNext()){
81
+            c.add(fileScanner.next());
82
+            total++;
83
+        }
84
+        st.stop();
85
+        System.out.println("Time for our unsorted set based on ArrayList: \n" + st);
86
+//        System.out.println(c.size() + " distinct words");
87
+//        System.out.println(total + " total words including duplicates: ");
88
+        assert total >= c.size();
89
+        System.out.println();
90
+        return new int[]{total, c.size()};
91
+    }
92
+    
93
+    public static int[] countWordsOurBinarySearchTree(String fileName) throws Exception {
94
+        Scanner fileScanner = new Scanner(new File(fileName));  
95
+        Stopwatch st = new Stopwatch();
96
+        BinarySearchTree<String> c = new BinarySearchTree<String>();
97
+        st.start();
98
+        int total = 0;
99
+        while(fileScanner.hasNext()){
100
+            c.add(fileScanner.next());
101
+            total++;
102
+        }
103
+        st.stop();
104
+        System.out.println("Time for our binary search tree: \n" + st);
105
+//        System.out.println(c.size() + " distinct words");
106
+//        System.out.println(total + " total words including duplicates: ");
107
+        assert total >= c.size();
108
+        System.out.println();
109
+        return new int[]{total, c.size()};
110
+    }
111
+    
112
+    
113
+    // a try at reflection. Not working on Binary Search tree from class. 
114
+    // Hunch. Due to add method taking in Comparable, not Object!
115
+    // Alterantives: search list of methods for name?
116
+    public static int[] countWords(Object c, String fileName) throws Exception {
117
+        Scanner fileScanner = new Scanner(new File(fileName));  
118
+        Stopwatch st = new Stopwatch();
119
+        System.out.println(Arrays.toString(c.getClass().getMethods()));
120
+        Method addMethod = c.getClass().getMethod("add", Object.class);
121
+        st.start();
122
+        int total = 0;
123
+        while(fileScanner.hasNext()){
124
+            addMethod.invoke(c, fileScanner.next());
125
+            total++;
126
+        }
127
+        st.stop();
128
+        System.out.println("Time for " + c.getClass() + ": "+ st);
129
+        Method sizeMethod = c.getClass().getMethod("size");
130
+        int distictWords = (Integer) sizeMethod.invoke(c);
131
+//        System.out.println(distictWords + " distinct words");
132
+//        System.out.println(total + " total words including duplicates: ");
133
+        System.out.println();
134
+        return new int[]{total, distictWords};
135
+    }
136
+}

+ 25
- 0
CodeSamples/codeSamples/WriteToFile.java Bestand weergeven

@@ -0,0 +1,25 @@
1
+//sample code to write 100 random ints to a file, 1 per line
2
+
3
+import java.io.PrintStream;
4
+import java.io.IOException;
5
+import java.io.File;
6
+
7
+import java.util.Random;
8
+
9
+public class WriteToFile
10
+{	public static void main(String[] args)
11
+	{	try
12
+		{	PrintStream writer = new PrintStream( new File("randInts.txt"));
13
+			Random r = new Random();
14
+			final int LIMIT = 100;
15
+
16
+			for(int i = 0; i < LIMIT; i++)
17
+			{	writer.println( r.nextInt() );
18
+			}
19
+			writer.close();
20
+		}
21
+		catch(IOException e)
22
+		{	System.out.println("An error occured while trying to write to the file");
23
+		}
24
+	}
25
+}

+ 19
- 0
CodeSamples/codeSamples/airlines.txt Bestand weergeven

@@ -0,0 +1,19 @@
1
+Delta,Air Canada,Aero Mexico,Ocean Air
2
+United,Aria,Lufthansa,Ocean Air,Quantas,British Airways
3
+Northwest,Air Alaska,BMI,Avolar,EVA Air
4
+Canjet,Girjet
5
+Air Canada,Areo Mexico,Delta,Air Alaska
6
+Aero Mexico,Delta,Air Canda,British Airways
7
+Ocean Air,Delta,United,Quantas,Avolar
8
+Aria,United,Lufthansa
9
+Lufthansa,United,Aria,EVA Air
10
+Quantas,United,Ocean Air,AlohaAir
11
+BMI,Northwest
12
+Maxair,Southwest,Girjet
13
+Girjet,Southwest,Canjet,Maxair
14
+British Airways,United,Aero Mexico
15
+Air Alaska,Northwest,Air Canada
16
+Avolar,Northwest,Ocean Air
17
+EVA Air,Northwest,Luftansa
18
+Southwest,Girjet,Maxair
19
+AlohaAir,Quantas

+ 363
- 0
CodeSamples/utilities/Stopwatch.html Bestand weergeven

@@ -0,0 +1,363 @@
1
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2
+<!--NewPage-->
3
+<HTML>
4
+<HEAD>
5
+<!-- Generated by javadoc (build 1.5.0_04) on Mon Jun 19 13:07:01 CDT 2006 -->
6
+<TITLE>
7
+Stopwatch
8
+</TITLE>
9
+
10
+<META NAME="keywords" CONTENT="Stopwatch class">
11
+
12
+<LINK REL ="stylesheet" TYPE="text/css" HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/stylesheet.css" TITLE="Style">
13
+
14
+<SCRIPT type="text/javascript">
15
+function windowTitle()
16
+{
17
+    parent.document.title="Stopwatch";
18
+}
19
+</SCRIPT>
20
+<NOSCRIPT>
21
+</NOSCRIPT>
22
+
23
+</HEAD>
24
+
25
+<BODY BGCOLOR="white" onload="windowTitle();">
26
+
27
+
28
+<!-- ========= START OF TOP NAVBAR ======= -->
29
+<A NAME="navbar_top"><!-- --></A>
30
+<A HREF="Stopwatch.html#skip-navbar_top" title="Skip navigation links"></A>
31
+<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
32
+<TR>
33
+<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
34
+<A NAME="navbar_top_firstrow"><!-- --></A>
35
+<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
36
+  <TR ALIGN="center" VALIGN="top">
37
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD>
38
+  <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD>
39
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/class-use/Stopwatch.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD>
40
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD>
41
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD>
42
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD>
43
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD>
44
+  </TR>
45
+</TABLE>
46
+</TD>
47
+<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
48
+</EM>
49
+</TD>
50
+</TR>
51
+
52
+<TR>
53
+<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
54
+&nbsp;PREV CLASS&nbsp;
55
+&nbsp;NEXT CLASS</FONT></TD>
56
+<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
57
+  <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/index.html?Stopwatch.html" target="_top"><B>FRAMES</B></A>  &nbsp;
58
+&nbsp;<A HREF="Stopwatch.html" target="_top"><B>NO FRAMES</B></A>  &nbsp;
59
+&nbsp;<SCRIPT type="text/javascript">
60
+  <!--
61
+  if(window==top) {
62
+    document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>');
63
+  }
64
+  //-->
65
+</SCRIPT>
66
+<NOSCRIPT>
67
+  <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/allclasses-noframe.html"><B>All Classes</B></A></NOSCRIPT>
68
+
69
+
70
+</FONT></TD>
71
+</TR>
72
+<TR>
73
+<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
74
+  SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="Stopwatch.html#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#method_summary">METHOD</A></FONT></TD>
75
+<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
76
+DETAIL:&nbsp;<A HREF="Stopwatch.html#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#method_detail">METHOD</A></FONT></TD>
77
+</TR>
78
+</TABLE>
79
+<A NAME="skip-navbar_top"></A>
80
+<!-- ========= END OF TOP NAVBAR ========= -->
81
+
82
+<HR>
83
+<!-- ======== START OF CLASS DATA ======== -->
84
+<H2>
85
+Class Stopwatch</H2>
86
+<PRE>java.lang.Object
87
+  <IMG SRC="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/resources/inherit.gif" ALT="extended by "><B>Stopwatch</B>
88
+</PRE>
89
+<HR>
90
+<DL>
91
+<DT><PRE>public class <B>Stopwatch</B><DT>extends java.lang.Object</DL>
92
+</PRE>
93
+
94
+<P>
95
+A class to measure time elapsed.
96
+<P>
97
+
98
+<P>
99
+<HR>
100
+
101
+<P>
102
+<!-- =========== FIELD SUMMARY =========== -->
103
+
104
+<A NAME="field_summary"><!-- --></A>
105
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
106
+<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
107
+<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
108
+<B>Field Summary</B></FONT></TH>
109
+</TR>
110
+<TR BGCOLOR="white" CLASS="TableRowColor">
111
+<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
112
+<CODE>static&nbsp;double</CODE></FONT></TD>
113
+<TD><CODE><B><A HREF="Stopwatch.html#NANOS_PER_SEC">NANOS_PER_SEC</A></B></CODE>
114
+
115
+<BR>
116
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD>
117
+</TR>
118
+</TABLE>
119
+&nbsp;
120
+<!-- ======== CONSTRUCTOR SUMMARY ======== -->
121
+
122
+<A NAME="constructor_summary"><!-- --></A>
123
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
124
+<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
125
+<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
126
+<B>Constructor Summary</B></FONT></TH>
127
+</TR>
128
+<TR BGCOLOR="white" CLASS="TableRowColor">
129
+<TD><CODE><B><A HREF="Stopwatch.html#Stopwatch()">Stopwatch</A></B>()</CODE>
130
+
131
+<BR>
132
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD>
133
+</TR>
134
+</TABLE>
135
+&nbsp;
136
+<!-- ========== METHOD SUMMARY =========== -->
137
+
138
+<A NAME="method_summary"><!-- --></A>
139
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
140
+<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
141
+<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
142
+<B>Method Summary</B></FONT></TH>
143
+</TR>
144
+<TR BGCOLOR="white" CLASS="TableRowColor">
145
+<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
146
+<CODE>&nbsp;void</CODE></FONT></TD>
147
+<TD><CODE><B><A HREF="Stopwatch.html#start()">start</A></B>()</CODE>
148
+
149
+<BR>
150
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;start the stop watch.</TD>
151
+</TR>
152
+<TR BGCOLOR="white" CLASS="TableRowColor">
153
+<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
154
+<CODE>&nbsp;void</CODE></FONT></TD>
155
+<TD><CODE><B><A HREF="Stopwatch.html#stop()">stop</A></B>()</CODE>
156
+
157
+<BR>
158
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stop the stop watch.</TD>
159
+</TR>
160
+<TR BGCOLOR="white" CLASS="TableRowColor">
161
+<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
162
+<CODE>&nbsp;double</CODE></FONT></TD>
163
+<TD><CODE><B><A HREF="Stopwatch.html#time()">time</A></B>()</CODE>
164
+
165
+<BR>
166
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elapsed time in secods.</TD>
167
+</TR>
168
+<TR BGCOLOR="white" CLASS="TableRowColor">
169
+<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
170
+<CODE>&nbsp;long</CODE></FONT></TD>
171
+<TD><CODE><B><A HREF="Stopwatch.html#timeInNanoseconds()">timeInNanoseconds</A></B>()</CODE>
172
+
173
+<BR>
174
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;elapsed time in nanoseconds.</TD>
175
+</TR>
176
+<TR BGCOLOR="white" CLASS="TableRowColor">
177
+<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
178
+<CODE>&nbsp;java.lang.String</CODE></FONT></TD>
179
+<TD><CODE><B><A HREF="Stopwatch.html#toString()">toString</A></B>()</CODE>
180
+
181
+<BR>
182
+&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD>
183
+</TR>
184
+</TABLE>
185
+&nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
186
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
187
+<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
188
+<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
189
+</TR>
190
+<TR BGCOLOR="white" CLASS="TableRowColor">
191
+<TD><CODE>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD>
192
+</TR>
193
+</TABLE>
194
+&nbsp;
195
+<P>
196
+
197
+<!-- ============ FIELD DETAIL =========== -->
198
+
199
+<A NAME="field_detail"><!-- --></A>
200
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
201
+<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
202
+<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
203
+<B>Field Detail</B></FONT></TH>
204
+</TR>
205
+</TABLE>
206
+
207
+<A NAME="NANOS_PER_SEC"><!-- --></A><H3>
208
+NANOS_PER_SEC</H3>
209
+<PRE>public static final double <B>NANOS_PER_SEC</B></PRE>
210
+<DL>
211
+<DL>
212
+<DT><B>See Also:</B><DD><A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/constant-values.html#Stopwatch.NANOS_PER_SEC">Constant Field Values</A></DL>
213
+</DL>
214
+
215
+<!-- ========= CONSTRUCTOR DETAIL ======== -->
216
+
217
+<A NAME="constructor_detail"><!-- --></A>
218
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
219
+<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
220
+<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
221
+<B>Constructor Detail</B></FONT></TH>
222
+</TR>
223
+</TABLE>
224
+
225
+<A NAME="Stopwatch()"><!-- --></A><H3>
226
+Stopwatch</H3>
227
+<PRE>public <B>Stopwatch</B>()</PRE>
228
+<DL>
229
+</DL>
230
+
231
+<!-- ============ METHOD DETAIL ========== -->
232
+
233
+<A NAME="method_detail"><!-- --></A>
234
+<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
235
+<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
236
+<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
237
+<B>Method Detail</B></FONT></TH>
238
+</TR>
239
+</TABLE>
240
+
241
+<A NAME="start()"><!-- --></A><H3>
242
+start</H3>
243
+<PRE>public void <B>start</B>()</PRE>
244
+<DL>
245
+<DD>start the stop watch.
246
+<P>
247
+<DD><DL>
248
+</DL>
249
+</DD>
250
+</DL>
251
+<HR>
252
+
253
+<A NAME="stop()"><!-- --></A><H3>
254
+stop</H3>
255
+<PRE>public void <B>stop</B>()</PRE>
256
+<DL>
257
+<DD>stop the stop watch.
258
+<P>
259
+<DD><DL>
260
+</DL>
261
+</DD>
262
+</DL>
263
+<HR>
264
+
265
+<A NAME="time()"><!-- --></A><H3>
266
+time</H3>
267
+<PRE>public double <B>time</B>()</PRE>
268
+<DL>
269
+<DD>elapsed time in secods.
270
+<P>
271
+<DD><DL>
272
+
273
+<DT><B>Returns:</B><DD>the time recorded on the stopwatch in seconds</DL>
274
+</DD>
275
+</DL>
276
+<HR>
277
+
278
+<A NAME="toString()"><!-- --></A><H3>
279
+toString</H3>
280
+<PRE>public java.lang.String <B>toString</B>()</PRE>
281
+<DL>
282
+<DD><DL>
283
+<DT><B>Overrides:</B><DD><CODE>toString</CODE> in class <CODE>java.lang.Object</CODE></DL>
284
+</DD>
285
+<DD><DL>
286
+</DL>
287
+</DD>
288
+</DL>
289
+<HR>
290
+
291
+<A NAME="timeInNanoseconds()"><!-- --></A><H3>
292
+timeInNanoseconds</H3>
293
+<PRE>public long <B>timeInNanoseconds</B>()</PRE>
294
+<DL>
295
+<DD>elapsed time in nanoseconds.
296
+<P>
297
+<DD><DL>
298
+
299
+<DT><B>Returns:</B><DD>the time recorded on the stopwatch in nanoseconds</DL>
300
+</DD>
301
+</DL>
302
+<!-- ========= END OF CLASS DATA ========= -->
303
+<HR>
304
+
305
+
306
+<!-- ======= START OF BOTTOM NAVBAR ====== -->
307
+<A NAME="navbar_bottom"><!-- --></A>
308
+<A HREF="Stopwatch.html#skip-navbar_bottom" title="Skip navigation links"></A>
309
+<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
310
+<TR>
311
+<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
312
+<A NAME="navbar_bottom_firstrow"><!-- --></A>
313
+<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
314
+  <TR ALIGN="center" VALIGN="top">
315
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD>
316
+  <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD>
317
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/class-use/Stopwatch.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD>
318
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD>
319
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD>
320
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD>
321
+  <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1">    <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD>
322
+  </TR>
323
+</TABLE>
324
+</TD>
325
+<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
326
+</EM>
327
+</TD>
328
+</TR>
329
+
330
+<TR>
331
+<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
332
+&nbsp;PREV CLASS&nbsp;
333
+&nbsp;NEXT CLASS</FONT></TD>
334
+<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
335
+  <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/index.html?Stopwatch.html" target="_top"><B>FRAMES</B></A>  &nbsp;
336
+&nbsp;<A HREF="Stopwatch.html" target="_top"><B>NO FRAMES</B></A>  &nbsp;
337
+&nbsp;<SCRIPT type="text/javascript">
338
+  <!--
339
+  if(window==top) {
340
+    document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>');
341
+  }
342
+  //-->
343
+</SCRIPT>
344
+<NOSCRIPT>
345
+  <A HREF="https://www.cs.utexas.edu/~scottm/cs307/javacode/utilities/allclasses-noframe.html"><B>All Classes</B></A></NOSCRIPT>
346
+
347
+
348
+</FONT></TD>
349
+</TR>
350
+<TR>
351
+<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
352
+  SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="Stopwatch.html#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#method_summary">METHOD</A></FONT></TD>
353
+<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
354
+DETAIL:&nbsp;<A HREF="Stopwatch.html#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="Stopwatch.html#method_detail">METHOD</A></FONT></TD>
355
+</TR>
356
+</TABLE>
357
+<A NAME="skip-navbar_bottom"></A>
358
+<!-- ======== END OF BOTTOM NAVBAR ======= -->
359
+
360
+<HR>
361
+
362
+</BODY>
363
+</HTML>

+ 43
- 0
CodeSamples/utilities/Stopwatch.java Bestand weergeven

@@ -0,0 +1,43 @@
1
+/**
2
+ A class to measure time elapsed.
3
+*/
4
+
5
+public class Stopwatch
6
+{
7
+    private long startTime;
8
+    private long stopTime;
9
+
10
+    public static final double NANOS_PER_SEC = 1000000000.0;
11
+
12
+	/**
13
+	 start the stop watch.
14
+	*/
15
+	public void start(){
16
+		startTime = System.nanoTime();
17
+	}
18
+
19
+	/**
20
+	 stop the stop watch.
21
+	*/
22
+	public void stop()
23
+	{	stopTime = System.nanoTime();	}
24
+
25
+	/**
26
+	elapsed time in seconds.
27
+	@return the time recorded on the stopwatch in seconds
28
+	*/
29
+	public double time()
30
+	{	return (stopTime - startTime) / NANOS_PER_SEC;	}
31
+
32
+	public String toString(){
33
+	    return "elapsed time: " + time() + " seconds.";
34
+	}
35
+
36
+	/**
37
+	elapsed time in nanoseconds.
38
+	@return the time recorded on the stopwatch in nanoseconds
39
+	*/
40
+	public long timeInNanoseconds()
41
+	{	return (stopTime - startTime);	}
42
+}
43
+

+ 1
- 0
README.md Bestand weergeven

@@ -0,0 +1 @@
1
+# More YeOldeCode