- Lab 16: Iterator
- Lab 17: Exceptions
- Lab 18: Pride and Prejudice
- Lab 19: Sierpinsky
- Lab 20: Stock Plot
- Lab 21: Disjoint Sets
- Lab 22: Thumbs Up
- Lab 23: Linked List
and homeworks:
CSCE 145: Algorithmic Design I
minCycle that takes a String s as an argument and returns the shortest string which when repeated generates s. For example:minCycle("aaaaaaaa") returns "a"
minCycle("ababababab") returns "ab"
minCycle("ababa") returns "ababa"
minCycle("12345") returns "12345"
minCycle("123123123") returns "123"
blackJackWinner(int[] points) which takes as an argument the points each player on the table ended up with and return the index of the winner, or -1 if there is a tie. Any player with more than 21 points loses. Of the remaining players, the one with the most points wins. If there is a tie, or if there are no winners, return -1. For example:blackJackWinner({1,2}) returns 1
blackJackWinner({1,2,3,3,2}) returns -1
blackJackWinner({21,22,19}) returns 0
blackJackWinner({1,20,15,22}) returns 1
blackJackWinner({22,23,25}) returns -1 //no winners
int[] findTeam(boolean[][] canWork) which takes as input a 2-dimensional array of booleans that tells us wether a particular employee (row) can work with another (col) and returns an array containing the indexes of 3 employees that can work together in a team, or null if there is none. That is canWork[2][3] is true if employee 2 can work with 3. For example:findTeam({true,true,true},
{true,true,true},
{true,true,true}) returns {0,1,2}
findTeam({true,true,true},
{false,true,true},
{true,true,true}) returns null
findTeam({true,false,true,true},
{true,true,true,true},
{true,true,true,true},
{true,true,true,true}) returns {1,2,3}
findTeam({true,false,true,true},
{true,true,false,true},
{true,true,true,true},
{true,true,true,true}) returns null
String decrypt(String spell) which decrypts the 'spell' by reversing the order in which the 'A' and 'Z' characters appear in it, but leaves all other characters in the same position. For example:decrypt("AZ") returns "ZA"
decrypt("ABZ") returns "ZBA"
decrypt("ABACDA") returns "ABACDA"
decrypt("ZBACDA") returns "ABACDZ"
decrypt("AAATZZ") returns "ZZATAA"
![]() |
| Word Cloud for Pride and Prejudice |
There are 6898 unique words. mr 783 elizabeth 594 such 393 darcy 371 mrs 343 much 328 more 326 bennet 293 miss 283 one 266 jane 263 bingley 257 know 239 before 229 herself 224 though 221 never 220 soon 216 well 212 think 211
There are 7531 unique words. elinor 616 mrs 525 marianne 488 more 403 such 359 one 317 much 287 herself 249 time 237 now 230 know 228 dashwood 224 though 213 sister 213 edward 210 miss 209 well 209 think 205 mother 200 before 198
private static final String[] stopWordsList = {
"a","able","about","after","all","almost","also","am","among","an",
"and","any","are","as","at","be","because","been","but","by","can",
"cannot","could","dear","did","do","does","either","else","ever",
"every","for","from","get","got","had","has","have","he","her","hers",
"him","his","how","however","i","if","in","into","is","it","its","just",
"least","let","like","likely","may","me","might","most","must","my",
"neither","no","nor","not","of","off","often","on","only","or","other",
"our","own","rather","said","say","says","she","should","since","so",
"some","than","that","the","their","them","then","there","these","they",
"this","tis","to","too","twas","us","very","wants","was","we","were","what",
"when","where","which","while","who","whom","why","will","with",
"would","yet","you","your"};
HashMap to keep track of the counts. You might also want to use the a HashSet.one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifthteen sixteen seventeen eightteen nineteen twenty twentyone twentytwo twentythree twentyfour twentyfive twentysix ...and so on... one hundred and ninetyseven one hundred and ninetyeight one hundred and ninetynine two hundred two hundred and one two hundred and two two hundred and three two hundred and four two hundred and five two hundred and six two hundred and seven ...and so on... nine hundred and ninetynine thousand nine hundred and ninetyfive nine hundred and ninetynine thousand nine hundred and ninetysix nine hundred and ninetynine thousand nine hundred and ninetyseven nine hundred and ninetynine thousand nine hundred and ninetyeight nine hundred and ninetynine thousand nine hundred and ninetynine one million
oe.occupation file. Each line in this file lists a different occupation by first listing the occupation code, a space, then the English description, a space, then a number (1). Your program will need to first read all these occupations codes and descriptions into an array so it can then ask the user for which occupation he wants to know the total number of people employed.oe.data.0.Current file contains all the data. It is a large file (266MB) and the .gov site is slow so, here is my copy. The oe.txt file describes the format of the data in this file in detail, but I will explain below what you need to do for this HW. The oe.data.0.Current file looks likeseries_id year period value footnote_codes OEUM001018000000000000001 2010 S01 61790 OEUM001018000000000000002 2010 S01 2.2 OEUM001018000000000000003 2010 S01 16.72 OEUM001018000000000000004 2010 S01 34780
series_id (OEUM000040000000000000001) can be broken out into:Code Value(Example) survey abbreviation = OE seasonal(code) = U area_code = 0000400 industry_code = 000000 occupation_code = 000000 datatype_code = 01
series_id that starts with OEUS and have a datatype_code (end with) of 01, which corresponds to "number of jobs". The occupation_code corresponds to the code from the oe.occupation file.oe.occupation file. It will then show the user the list of all occupation codes, numbered, and ask him to pick one. It will then open up the oe.data.0.Current file and add up the values (fourth column) of all the rows that with a series_id that starts with OEUS, ends with 01, and matches the user's chosen occupation code. Finally, it will print out this number. Here is a sample run:0 - All Occupations
1 - Management Occupations
2 - Chief Executives
3 - General and Operations Managers
....and so on.....
817 - Mine Shuttle Car Operators
818 - Tank Car, Truck, and Ship Loaders
819 - Material Moving Workers, All Other
Which of the occupations above do you need data for?
Enter number:77
Working......
17750 persons work as Actuaries in the US.
Enter number:66 Working...... 3294290 persons work as Computer and Mathematical Occupations in the US. Enter number:69 Working...... 335330 persons work as Computer Programmers in the US. Enter number:70 Working...... 499880 persons work as Software Developers, Applications in the US. Enter number:94 Working...... 144870 persons work as Electrical Engineers in the US. Enter number:101 Working...... 223470 persons work as Mechanical Engineers in the US. Enter number:119 Working...... 1072400 persons work as Life, Physical, and Social Science Occupations in the US. Enter number:146 Working...... 3360 persons work as Sociologists in the US. Enter number:1 Working...... 6066780 persons work as Management Occupations in the US. Enter number:295 Working...... 7394880 persons work as Healthcare Practitioners and Technical Occupations in the US.
oe.occupation file, along with an Occupation class which holds just one occupation: its name and its code.![]() |
| The Thing class hierarchy. |
Animated class has a protected enum Direction {N,S,E,W}; which shows up as Animated.Direction in the javadocs.main in the Game class which looks like this:public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Game g = new Game();
g.add(new Sword(3,3));
User user = new User(1,4);
g.add(user);
g.add(new Knight(5,5));
g.add(new Peasant(9,5));
g.add(new Peasant(6,7));
g.add(new Peasant(4,8));
g.add(new Peasant(7,2));
g.add(new Peasant(3,5));
String command = "";
do {
System.out.println(g); //print out the game board
System.out.print("Your move:");
command = keyboard.next();
user.move(command); //move the user
g.moveAll(); //move everyone
g.resolveConflicts(); //resolve any conflicts between those in the same row,col
} while (user.isAlive());
}A sample run of the program looks like:__________ ____Y_____ __________ ___S_P____ ________P_ _____K____ _______P__ __P_______ __________ _____P____ Your move:south Knight moves S Peasant moves E Peasant too weak to move. Peasant too weak to move. Peasant too weak to move. Peasant too weak to move. Peasant too weak to move. __________ __________ ____Y_____ ___S_P____ ________P_ __________ _____K_P__ __P_______ __________ ______P___ Your move:west Knight moves W Peasant moves S Peasant too weak to move. Peasant moves E Peasant too weak to move. Peasant moves N Peasant too weak to move. Peasant too weak to move. Peasant too weak to move. ______P___ __________ ___Y______ ___S_P__P_ __________ __________ ____K___P_ __P_______ __________ __________ Your move:south Knight moves W Peasant moves N Peasant too weak to move. Peasant moves S Peasant too weak to move. Peasant too weak to move. Peasant moves E Peasant too weak to move. Peasant moves E Peasant too weak to move. User picks up Sword __________ __________ __________ ___Y__P_P_ __________ __________ ___K______ ___P____P_ __________ ______P___ Your move:east Knight moves W Peasant too weak to move. Peasant too weak to move. Peasant moves E Peasant too weak to move. Peasant moves W Peasant too weak to move. Peasant too weak to move. __________ __________ __________ ____Y_P__P __________ __________ __K_______ __P_____P_ __________ ______P___ Your move:east Knight moves S Peasant too weak to move. Peasant moves S Peasant too weak to move. Peasant moves W Peasant too weak to move. Peasant too weak to move. Peasant moves S Peasant too weak to move. Bloodthristy Knight kills a P __________ __________ __________ _____Y__P_ ______P___ __________ __________ __K_______ ________P_ ______P___ Your move:south Knight moves W Peasant moves W Peasant too weak to move. Peasant moves W Peasant too weak to move. Peasant moves N Peasant too weak to move. Peasant moves S Peasant too weak to move. __________ __________ ________P_ __________ _____Y____ ______P___ __________ _K________ _______P__ _____P____ Your move:quit Knight moves W Peasant moves E Peasant too weak to move. Peasant moves S Peasant too weak to move. Peasant moves S Peasant too weak to move. Peasant too weak to move.
User how to move (N,S,E,W). The knights move randomly (one of N,S,E,W) on each turn. The peasants flip a coin, if heads they stay put otherwise they move randomly (one ofN,S,E,W). The world is 10 by 10 and wraps around.resolveconflicts method is described in the javadocs. It goes over every Thing. If there is another Thing in the same row,col position then, if the Thing is a Knight it kills (removes) any Thing else there. If it is the user then if it finds the sword there it picks it up (thus killing it) and it is it a peasant it kills it.Enter random sequence of 0 and 1s:
00000111
The distribution of length=3 substrings is:
000 3
001 1
010 0
011 1
100 0
101 0
110 0
111 1
Deviation = 0.9682458365518543
The computer's random sequence is:
01010100
The distribution of length=3 substring is:
000 0
001 0
010 3
011 0
100 1
101 2
110 0
111 0
Deviation = 1.0897247358851685
The user enters a random string of 0s and 1s (you can assume he does this correctly and does not enter other characters). The program then counts how many times each of the eight possible sequences of length 3 appears and prints these out. It then calculates the standard deviation for these counts. Enter random sequence of 0 and 1s:
0101010101010101000101001001001001001001010101011111010100101010010010010101010101010010
The distribution of length=3 substrings is:
000 1
001 12
010 34
011 1
100 12
101 22
110 1
111 3
Deviation = 11.266654339243749
The computer's random sequence is:
1000111001110111010010110110100110110111100001011000001111010100011100111100001010110000
The distribution of length=3 substrings is:
000 11
001 9
010 8
011 13
100 10
101 12
110 13
111 10
Deviation = 1.713913650100261
As you can see, I'm not very good at being random.Person class that has the following data members:public static void main(String[] args) {
//Part of the Weasley family tree, from http://www.hp-lexicon.org/wizards/weasley.html
Person molly = new Person("Molly Weasley", true, 1950);
//Person.toString() prints out a nice view of the person
System.out.println(molly); //print out molly
//Implement these constructors
Person arthur = new Person("Arthur Weasley", false, 1950);
Person fleur = new Person("Fleur Delacour", true, 1977);
Person bill = new Person("Bill Weasley", false, 1970);
//Implement these setters
bill.setFather(arthur);
bill.setMother(molly);
System.out.println(bill); //print out bill
//Implement these constructors
Person charlie = new Person("Charlie Weasley", false, 1972, molly, arthur);
Person percy = new Person("Percy Ignatius Weasley", false, 1976, molly, arthur);
Person fred = new Person("Fred Weasley", false, 1978, molly, arthur);
Person george = new Person("George Weasley", false, 1978, molly, arthur);
Person ron = new Person("Ronald \"Ron\" Bilius Weasley", false, 1980, molly, arthur);
Person ginny = new Person("Ginerva \"Ginney\" Molly Weasley", true, 1981, molly, arthur);
System.out.println(ron); //print out ron
//Implement Person.isSibling(Person p) which returns true if they are siblings
System.out.println("Are fred and george siblings? " + fred.isSiblingOf(george));
System.out.println("Are molly and george siblings? " + molly.isSiblingOf(george));
Person hermione = new Person("Hermione (Granger) Weasley", true, 1979);
Person rose = new Person("Rose Wealey", true, 2006,hermione,ron);
Person hugo = new Person("Hugo Wealey", true, 2008, hermione, ron);
System.out.println("Rose's paternal grandpa is:\n" + rose.getPaternalGrandfather());
System.out.println("Ron's paternal grandpa is:\n" + ron.getPaternalGrandfather());
Person harry = new Person("Harry Potter", false, 1980);
Person james = new Person("James Sirius", false, 2005, ginny, harry);
Person albus = new Person("Albus Severus", false, 2006, ginny, harry);
Person lily = new Person("Lily Luna", true, 2007, ginny, harry);
//Implement the Person.isCousin(Person p) which returns true if they are first cousins.
// X and Y are first cousins if one of their parents are siblings.
System.out.println("Are rose and albus cousins? " + rose.isCousinOf(albus));
System.out.println("Are albus and rose cousins? " + albus.isCousinOf(rose));
System.out.println("Are harry and ron cousins? " + harry.isCousinOf(ron));
System.out.println("Are lily and charlie cousins? " + lily.isCousinOf(charlie));
System.out.println("Are james and albus cousins? " + james.isCousinOf(albus));
System.out.println("Are james and fred cousins? " + james.isCousinOf(fred));
System.out.println("Are james and hugo cousins? " + james.isCousinOf(hugo));
System.out.println("Are james and rose cousins? " + james.isCousinOf(rose));
}
Molly Weasley (F) 1950
Mother=unknown
Father=unknown
Bill Weasley (M) 1970
Mother=Molly Weasley
Father=Arthur Weasley
Ronald "Ron" Bilius Weasley (M) 1980
Mother=Molly Weasley
Father=Arthur Weasley
Are fred and george siblings? true
Are molly and george siblings? false
Rose's paternal grandpa is:
Arthur Weasley (M) 1950
Mother=unknown
Father=unknown
Ron's paternal grandpa is:
null
Are rose and albus cousins? true
Are albus and rose cousins? true
Are harry and ron cousins? false
Are lily and charlie cousins? false
Are james and albus cousins? false
Are james and fred cousins? false
Are james and hugo cousins? true
Are james and rose cousins? true
g2.setStroke(new BasicStroke(5)).secretLength.
Think of a number between 1 and 255. I will guess the number you are thinking of. 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 153 155 157 159 161 163 165 167 169 171 173 175 177 179 181 183 185 187 189 191 193 195 197 199 201 203 205 207 209 211 213 215 217 219 221 223 225 227 229 231 233 235 237 239 241 243 245 247 249 251 253 255 Is it in the list above? (yes or no): yes 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 31 34 35 38 39 42 43 46 47 50 51 54 55 58 59 62 63 66 67 70 71 74 75 78 79 82 83 86 87 90 91 94 95 98 99 102 103 106 107 110 111 114 115 118 119 122 123 126 127 130 131 134 135 138 139 142 143 146 147 150 151 154 155 158 159 162 163 166 167 170 171 174 175 178 179 182 183 186 187 190 191 194 195 198 199 202 203 206 207 210 211 214 215 218 219 222 223 226 227 230 231 234 235 238 239 242 243 246 247 250 251 254 255 Is it in the list above? (yes or no): no 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 31 36 37 38 39 44 45 46 47 52 53 54 55 60 61 62 63 68 69 70 71 76 77 78 79 84 85 86 87 92 93 94 95 100 101 102 103 108 109 110 111 116 117 118 119 124 125 126 127 132 133 134 135 140 141 142 143 148 149 150 151 156 157 158 159 164 165 166 167 172 173 174 175 180 181 182 183 188 189 190 191 196 197 198 199 204 205 206 207 212 213 214 215 220 221 222 223 228 229 230 231 236 237 238 239 244 245 246 247 252 253 254 255 Is it in the list above? (yes or no): yes 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 31 40 41 42 43 44 45 46 47 56 57 58 59 60 61 62 63 72 73 74 75 76 77 78 79 88 89 90 91 92 93 94 95 104 105 106 107 108 109 110 111 120 121 122 123 124 125 126 127 136 137 138 139 140 141 142 143 152 153 154 155 156 157 158 159 168 169 170 171 172 173 174 175 184 185 186 187 188 189 190 191 200 201 202 203 204 205 206 207 216 217 218 219 220 221 222 223 232 233 234 235 236 237 238 239 248 249 250 251 252 253 254 255 Is it in the list above? (yes or no): yes 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 Is it in the list above? (yes or no): no 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 Is it in the list above? (yes or no): no 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 Is it in the list above? (yes or no): yes 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 Is it in the list above? (yes or no): no You are thinking of 77
for loops to print out the 8 sets of numbers (that is, you cannot just cut-n-paste these numbers into your program)..replace("e","3") more than once in your program then you were violating the DRY principle (Don't Repeat Yourself). Namely, every piece of knowledge should appear only once in your program. Math.random() to generate a random number). After the user makes a guess your program will tell him:Guess the 4-digit number I am thinking of. (the secret is 9712) Your guess:1245 1245 has 0 digits in the correct position. 1245 has 2 digits that are not found anywhere in the secret number. Your guess:9999 9999 has 1 digits in the correct position. 9999 has 0 digits that are not found anywhere in the secret number. Your guess:5555 5555 has 0 digits in the correct position. 5555 has 4 digits that are not found anywhere in the secret number. Your guess:9779 9779 has 2 digits in the correct position. 9779 has 0 digits that are not found anywhere in the secret number. Your guess:9721 9721 has 2 digits in the correct position. 9721 has 0 digits that are not found anywhere in the secret number. Your guess:1234 1234 has 0 digits in the correct position. 1234 has 2 digits that are not found anywhere in the secret number. Your guess:9712 9712 has 4 digits in the correct position. 9712 has 0 digits that are not found anywhere in the secret number. Congratulations! You guessed correctly.
| Replace this | with this |
|---|---|
| and | & |
| a | 4 |
| b | 8 |
| e | 3 |
| g | 6 |
| l | 1 |
| o | 0 |
| s | 5 |
| t | 7 |
| z | 2 |
I will translate your tweet to Leet. Enter your tweet:Hi there! Just a simple tweet to get started. No Hashtag found. Translation: hi 7h3r3! ju57 4 5imp13 7w337 70 637 574r73d. Message has 46 characters. I will translate your tweet to Leet. Enter your tweet:This one has a #hashtag Notice how it remains the same in the final message. Hashtag: #hashtag Translation: 7hi5 0n3 h45 4 #hashtag n07ic3 h0w i7 r3m4in5 7h3 54m3 in 7h3 fin41 m355463. Message has 77 characters. I will translate your tweet to Leet. Enter your tweet:The empty # is not a hashtag and should be left alone. No Hashtag found. Translation: 7h3 3mp7y # i5 n07 4 h45h746 & 5h0u1d 83 13f7 410n3. Message has 53 characters. I will translate your tweet to Leet. Enter your tweet:If you type a really long tweet then the program will still translate it but will give you an error because there is a 140 character limit #145rocks Hashtag: #145rocks Translation: if y0u 7yp3 4 r3411y 10n6 7w337 7h3n 7h3 pr06r4m wi11 57i11 7r4n51473 i7 8u7 wi11 6iv3 y0u 4n 3rr0r 83c4u53 7h3r3 i5 4 140 ch4r4c73r 1imi7 #145rocks Message has 149 characters. ERROR: Too big to tweet.
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Fractal extends JPanel {
private double length;
public int numLevels;
public void paintComponent(Graphics g) {
g.setColor(Color.black);
System.out.println("Drawing");
Point from = new Point(150,200);
Point to = new Point(450,200);
length = 0;
// drawFractalLineDragon(g,from,to,numLevels,Direction.Right);
drawFractalLine(g,from,to,numLevels);
// from = new Point(100,400);
// Point top = new Point(300,100);
// to = new Point(500,400);
// drawFractalLineSierpinsky(g,from,top,to,numLevels);
System.out.println("Length of curve is " + length);
}
/**
* Draw the Sierpinsky triangle http://en.wikipedia.org/wiki/Sierpinski_triangle
* @param g
* @param from bottom-left
* @param top
* @param to bottom-right
* @param level
*/
public void drawFractalLineSierpinsky(Graphics g, Point from, Point top, Point to, int level) {
if (level == 0) {
g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
length += from.getVectorTo(to).getMagnitude();
g.drawLine(from.getX(), from.getY(), top.getX(), top.getY());
length += from.getVectorTo(top).getMagnitude();
g.drawLine(top.getX(), top.getY(), to.getX(), to.getY());
length += top.getVectorTo(to).getMagnitude();
return;
}
Point midFromTop = from.getMidPoint(top);
Point midFromTo = from.getMidPoint(to);
Point midTopTo = top.getMidPoint(to);
drawFractalLineSierpinsky(g,from, midFromTop, midFromTo,level-1);
drawFractalLineSierpinsky(g,midFromTop, top, midTopTo, level-1);
drawFractalLineSierpinsky(g,midFromTo, midTopTo, to, level-1);
}
/**
* Draws the Levy C Curve http://en.wikipedia.org/wiki/Levy_C_curve
* @param g
* @param from start point
* @param to end point
* @param level number of recursive levels.
*/
public void drawFractalLine(Graphics g, Point from, Point to, int level) {
if (level == 0) {
g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
length += from.getVectorTo(to).getMagnitude();
// System.out.println(from + " " + to);
return;
}
Point mid = from.getMidPoint(to);
Vector delta = from.getVectorTo(to);
delta = delta.getPerpendicularRight();
delta = delta.multiplyBy(0.5); //half its magnitude
mid = mid.addVector(delta);
drawFractalLine(g,from,mid,level-1);
drawFractalLine(g,mid,to,level-1);
}
public enum Direction {Right,Left};
/**
* Draws the Dragon curve http://en.wikipedia.org/wiki/Dragon_curve
* @param g
* @param from
* @param to
* @param level
* @param d
*/
public void drawFractalLineDragon(Graphics g, Point from, Point to, int level, Direction d) {
if (level == 0) {
g.drawLine(from.getX(), from.getY(), to.getX(), to.getY());
length += from.getVectorTo(to).getMagnitude();
// System.out.println(from + " " + to);
return;
}
Point mid = from.getMidPoint(to);
Vector delta = from.getVectorTo(to);
if (d == Direction.Right) {
delta = delta.getPerpendicularRight();
} else {
delta = delta.getPerpendicularLeft();
}
delta = delta.multiplyBy(0.5); //half its magnitude
mid = mid.addVector(delta);
drawFractalLineDragon(g,from,mid,level-1,Direction.Right);
drawFractalLineDragon(g,mid,to,level-1,Direction.Left);
}
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Fractal Curve");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fractal panel = new Fractal();
frame.add(panel);
frame.setSize(600,600);
frame.setVisible(true);
try {
do {
String userInput = JOptionPane.showInputDialog("How Many Levels?");
panel.numLevels = Integer.parseInt(userInput);
frame.repaint(); //don't forget to re-paint it !
} while (true);
} catch (NumberFormatException e) {
//ignore it, just exit program
System.exit(0);
}
}
}
public class Point {
public double x;
public double y;
/**
* We return the nearest int to the current x value.
* By keeping points as double we increase the precision of the final plot.
* We only convert to int when absolutely necessary, that is, when plotting on screen.
* @return
*/
public int getX() {
return (int) Math.round(x);
}
public int getY() {
return (int) Math.round(y);
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + "," + y;
}
/**
* Make a vector from this point to other
* @param other
* @return a new Vector
*/
public Vector getVectorTo(Point other) {
return new Vector(other.x - x,other.y - y);
}
/**
* Returns a Point that lies midway on the line between this point and other
* @param other
* @return a new Point
*/
public Point getMidPoint(Point other) {
return new Point((x + other.x)/ 2, (y +other.y)/ 2);
}
/**
* Move this point by vector v.
* @param v
* @return a new Point
*/
public Point addVector(Vector v) {
return new Point(x + v.x, y + v.y);
}
}
public class Vector extends Point {
public Vector(double x, double y) {
super(x,y);
}
/**
* The magnitude
* @return the magnitude.
*/
public double getMagnitude() {
return Math.sqrt(x*x+y*y);
}
/**
* Creates a new vector that is perpendicular to this one, pointing to the right.
* @return a new vector
*/
public Vector getPerpendicularRight() {
return new Vector(-y, x);
}
/**
* Creates a new vector that is perpendicular to this one, pointing to the left.
* @return a new vector
*/
public Vector getPerpendicularLeft() {
return new Vector(y, -x);
}
/**
* Creates a new vector like this one but scaling both coordinates by d
* @param d
* @return a new vector
*/
public Vector multiplyBy(double d) {
return new Vector(x*d, y*d);
}
}
/** Jose M Vidal
* If that's not me on the line above then I deserve 0 points on this homework. */
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
public class Fractal extends JPanel{
public int numLevels;
public void paintComponent(Graphics g) {
g.setColor(Color.black);
System.out.println("Drawing");
g.drawLine(200, 200, 400, 200);
}
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Fractal Curve");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fractal panel = new Fractal();
frame.add(panel);
frame.setSize(600,600);
frame.setVisible(true);
try {
do {
String userInput = JOptionPane.showInputDialog("How Many Levels?");
panel.numLevels = Integer.parseInt(userInput);
frame.repaint(); //don't forget to re-paint it !
} while (true);
} catch (NumberFormatException e) {
//ignore it, just exit program
System.exit(0);
}
}
}
public class FileTooBigException extends Exception {
public FileTooBigException(String msg) {
super(msg);
}
}
public class NotEnoughDataException extends Exception {
public NotEnoughDataException(String msg) {
super(msg);
}
}
import java.util.Scanner;
public class Day {
private String date;
private double open;
private double high;
private double low;
private double close;
private long volume;
public double getClose() {
return close;
}
public double getVolume() {
return volume;
}
/**
* Creates a new Day object by reading values from istream:
* date, open, high, log, close, volume: in that order.
* We assume the delimiter has been correctly set on istream so values can be read
* by calling nextX()
* @param istream
*/
public Day (Scanner istream) {
date = istream.next();
open = istream.nextDouble();
high = istream.nextDouble();
low = istream.nextDouble();
close = istream.nextDouble();
volume = istream.nextLong();
}
public String toString() {
return date + " " + close + " " + volume;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Scanner;
public class Security {
private Day[] day;
private int lastDay;
private static final int DAY_ARRAY_SIZE = 1000;
/**
* Add day d to the history, but only if its volume > 0.
* @param d
* @throws FileTooBigException
*/
public void addDay(Day d) throws FileTooBigException {
if (d.getVolume() > 0) {
if (lastDay >= DAY_ARRAY_SIZE) {
throw new FileTooBigException("You cannot have more than " + DAY_ARRAY_SIZE + " days.");
}
day[lastDay++] = d;
}
}
public Security () {
day = new Day[DAY_ARRAY_SIZE];
lastDay = 0;
}
/** Read historical values for this security from a csv stream.
*
* @param file
* @throws FileTooBigException
*/
public void readFromStream(Scanner istream) throws FileTooBigException {
istream.useDelimiter("[,\\s]"); //separate on , or on whitespace
if (istream.hasNext()) {
istream.nextLine(); //ignore first line
}
String w = null;
while (istream.hasNext()) {
//System.out.println("----" + istream.next());
Day nextDay = new Day(istream);
addDay(nextDay);
}
}
public double getVolatility(int numDays) throws NotEnoughDataException {
if (numDays > lastDay) {
throw new NotEnoughDataException("Need more historical data");
}
double average = getAverageClose(numDays);
double squareDifference = 0;
for (int i=0; i < numDays; i++) {
squareDifference += Math.pow(day[i].getClose() - average, 2);
}
double deviation = squareDifference / (double) numDays;
return Math.sqrt(deviation);
}
public double getAverageClose(int numDays) {
double sum = 0;
for (int i=0; i< numDays;i++) {
sum += day[i].getClose();
}
return sum / (double)numDays;
}
public String toString() {
String result = "";
for (int i= 0; i < lastDay; i++) {
result += day[i] + "\n";
}
return result;
}
public double getMinClose(int numDays) {
double min = Double.MAX_VALUE; //assume no stock price is ever this high
for (int i = 0; i < numDays; i++) {
if (day[i].getClose() < min)
min = day[i].getClose();
}
return min;
}
public double getMaxClose(int numDays) {
double max = -1;
for (int i = 0; i < numDays; i++) {
if (day[i].getClose() > max)
max = day[i].getClose();
}
return max;
}
/**
* Returns a price distribution array, where the index of the array is the price - getMinClose(numDays)
* whose contents are the number of days we closed at that price within the last numDays.
* @param numDays
* @return array with getMaxClose(numDays) - getMinClose(numDays) + 1 values
*/
public int[] getPriceDistribution(int numDays) {
int min = (int) getMinClose(numDays);
int max = (int) getMaxClose(numDays);
int[] result = new int[max-min + 1];
for (int i =0; i < numDays; i++) {
result[(int)day[i].getClose() - min]++;
}
return result;
}
public void savePriceDistribution(String outFile,int numDays) throws FileNotFoundException {
PrintWriter out = new PrintWriter(new FileOutputStream(outFile, true));
int min = (int) getMinClose(numDays);
int[] distribution = getPriceDistribution(numDays);
for (int i =0; i < distribution.length; i++) {
int p = min + i;
out.write(p + "," + distribution[i] + "\n");
}
out.close();
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner istream = null;
String inputFile = "/Users/jmvidal/data.csv";
try {
istream = new Scanner(new File(inputFile));
} catch (FileNotFoundException e) {
System.out.println("Ooops, no such input file:" + inputFile);
System.exit(1);
}
Security s = new Security(); //Security class will hold all the data
try {
s.readFromStream(istream); //read the contents from istream
} catch (FileTooBigException e1) { //file is to big to read
System.out.println(e1.getMessage());
System.exit(1);
}
System.out.println(s); //print out all the contents. Note: no days with 0 volume.
try {
System.out.println("Volatility in the last 10 days = " + s.getVolatility(10));
System.out.println("Volatility in the last 1000 days = " + s.getVolatility(1000));
} catch (NotEnoughDataException e) {
System.out.println("Sorry, not enough data." + e.getMessage());
}
System.out.println("Price Distribution for the last 10 days.");
System.out.println("price\tnumber of days");
int[] priceDistribution = s.getPriceDistribution(10); //get the distribution array
int minClose = (int)s.getMinClose(10);
for (int i=0; i < priceDistribution.length; i++) { //we need this loop to print it out
int p = minClose + i;
System.out.println(p + "\t" + priceDistribution[i]);
}
try {
//now, save the distribtion for the last 20 days to a file.
s.savePriceDistribution("/Users/jmvidal/distribution-20.csv",20);
} catch (FileNotFoundException e) {
System.out.println("Ooops, bad output file name.");
System.exit(1);
}
}
}