Showing posts with label homework. Show all posts
Showing posts with label homework. Show all posts

Wednesday, April 11, 2012

Lab and Homework Solutions

Here are my solutions to past labs:

and homeworks:


Sample Programming Questions

Below are a few programming questions that are good practice for the next test and the final (some of these questions are from past topcoder competitions. We will be solving (some of) these in class today.

  1. Implement a method 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"
    
  2. Implement a method 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
    
  3. Implement a method 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
    
  4. Implement a method 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"
    

Monday, April 2, 2012

HW 10: Word Cloud

Word Cloud for Pride and Prejudice
Word clouds, like the one you see on the right that I made with wordle, are created by first scanning over a text, figuring out which words are most common in that text but not in others and then printing these words in font size proportional to how often those words appear. For this homework you will write a program that finds the most frequent words in a text and prints out how many times they appear.

Your program will
  1. Read in a text file, one word at a time.
  2. Clean up the word by throwing away any non-letter characters, like ".,!? and turning it to lowercase.
  3. If the word is not a stop word then keep track of how many times it appears on the file.
  4. Printout the number of unique words you found and the top 20 most frequent words found along with the number of times they appear in the file.

Here is the output of the program 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

and here is for Sense and Sensibility
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

The list of stop words you will use is
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"};

Your program will use a HashMap to keep track of the counts. You might also want to use the a HashSet.

This homework is due Monday, 9 April @noon in the dropbox.cse.sc.edu.

Monday, March 26, 2012

HW 9: Numbers

For this homework you will write a program that prints out the numbers between 1 and 1000000 in English. That is, it will print out:
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

You can download all the numbers if you want to see all of them.

Note that you must use a recursive method to generate the numbers. Look carefully at the numbers and notice the pattern, for example, the English for 136 is "one", then the words "hundred and" then the English for 36.

This homework is due Monday, April 2 @noon in the dropbox.cse.sc.edu.

Friday, March 16, 2012

HW 8: Employment Data

You are working in the University admissions office and students keep asking you about how the job market for different majors is fearing. You figure that a good place to start in answering that question is by looking at how many people currently work in each particular job in the US. You figure that someone must have already gathered that data and, after a bit of googling (or, binging) around, you come across the occupational employment statistics page from the Bureau of Labor Statistics. In that page you find a link to the raw data files.

For this homework you will only need to download the oe.occupation and oe.data.0.Current files.

First, take a look at the 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.

The 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 like
series_id year period value footnote_codes
OEUM001018000000000000001      2010 S01        61790 
OEUM001018000000000000002      2010 S01          2.2 
OEUM001018000000000000003      2010 S01        16.72 
OEUM001018000000000000004      2010 S01        34780 

The 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

For this HW we are only interested in lines with a 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.

Your program will first read in and parse the occupations from the 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.

Here are a few more sample outputs so you can see the sums that I got. I am omitting the list of occupations as it is always the same.
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.


I note that my numbers do not exactly match theirs. For example, for "Computer Programmers" I got 335,330 but their webpage shows 333,620 (wepage with all occupations). I blame it on shoddy accounting in the Obama administration. Still, its pretty close.

TIP: You will want to create a class that holds the collection of occupations from the oe.occupation file, along with an Occupation class which holds just one occupation: its name and its code.

TIP: It takes my laptop about 15 seconds to process the whole file. That is way too long when trying to debug the program, so I added temporary code to only read in the first few thousand lines. I then get rid of that code when the program works. BTW, the file has about 5 million lines.

This homework is due in the dropbox.cse.sc.edu on Monday, March 26 @noon. When you turn it in, do not upload the text files. We already have a copy, and we don't need 120 more copies.



Monday, February 27, 2012

Homework 7: Camelot

The Thing class hierarchy.
For this thy sixth homework, which does appear after the fifth but before the seventh, you shall implement the simple game of Camelot. Camelot, you see, is a silly place where peasants pathetically move about insisting they are not dead yet while brave knights honor thy King by slashing them to bits.

You will implement the classes shown in in the figure, along with a Game class which holds the board description. The specific methods that each class will implement are explained in detail in the Javadoc documents for Camelot (which you must read and follow). Notice that the documentation tells you exactly which methods and which properties you need to implement for every class. The Animated class has a protected enum Direction {N,S,E,W}; which shows up as Animated.Direction in the javadocs.

The program will have a 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.

Basically, the user tells the 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.

The 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.

I recommend you implement this program in the following order:
  1. The Thing hierarchy, start at the top and work your way down. Start with the properties, then the toString() methods, then the move() methods.
  2. The Game class, its properties and constructor.
  3. Game.toString(), test it.
  4. Game.add()
  5. Game.remove()
  6. Game.thingsAt()
  7. Game.moveAll(): this should just call move() on every thing.
  8. Finally, Game.removeConflicts()
This homework is due on Monday, March 12 @noon. Camelot, it is a silly place.


Monday, February 20, 2012

Homework 6: Frequency Stability

How random can you be? How can we tell how random you are? Watch the following video to learn how we determine someone's frequency stability.



For this problem you will implement a program that asks the user to type in a random sequence of 0's and 1's and then prints a distribution of all the length-3 substrings in his input, as well as the standard deviation in these numbers. The following is a sample interaction of the user with the program:
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.

Finally, the program generates a random sequence of 0s and 1s of the same length as the user's and then prints out the same calculations for this sequence. Here is another run, one where I try to be random:
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.

You will want to use arrays in this program.

This homework is due Monday, February 27 @noon in the dropbox.cse.sc.edu.

Monday, February 13, 2012

Homework 5: Family Tree

In this homework you will implement a simple Person class that has the following data members:

  • String: name
  • int: yearOfBirth
  • boolean: isFemale
  • Person: mother
  • Person: father
and which implements the following methods:
  • Person(String name, boolean isFemale, int yearOfBirth): constructor
  • Person(String name, boolean isFemale, int yearOfBirth, Person mother, Person father): constructor
  • equals(Person other): returns true if this person and other have the same name and were born in the same year.
  • boolean isSiblingOf(Person other): returns true if this person and other are siblings
  • boolean isCousinOf(Person other): return true if this person and other are first cousins (at least one of their parents are siblings)
  • Person getPaternalGrandfather(): returns the paternal grandfather (dad's dad).

To test your program us the following main (cf. The Weasley Family)
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));

 }

When you run that main it should print out:
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

This homework is due Monday, February 20 @noon in the dropbox.cse.sc.edu.

Monday, February 6, 2012

Homework 4: Moire


In this homework you will start with the code I gave you in Lab 7 change the program so that it generates the Moire pattern shown on the right.

What you are seeing in the screenshot are two sets of concentric circles. The centers of the circles are 100 pixels apart. The circles have a width of 5, and the diameter of a circle is 20 pixels larger than its next smallest one. Diameters range from 20 to 480 pixels.

Hint: You can change the width of the 'pen' used for drawing to 5 pixels with the line g2.setStroke(new BasicStroke(5)).

Hint: A circle is just an oval whose width and height are the same.

This homework is due Monday, February 13 @noon in the dropbox.cse.sc.edu.

Monday, January 30, 2012

Homework 2 Solution

You can view my solution to HW2. Notice how loops make programs shorter and more general: this solution will work on secrets of any length, just change secretLength.

Friday, January 27, 2012

Homework 3: Magic

For this homework you will write a program that guesses what number the user is thinking of. Below is a sample transcript:
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

The program prints out 8 sets of numbers. Notice the pattern:
  1. starting at 1 print the number, skip the next one, print the next one, skip the next one, etc.
  2. starting at 2 print the next 2 numbers, skip the next 2, print the next 2, skip the next 2, etc.
  3. starting at 4 print the next 4 numbers, skip the next 4, print the next 4, skip the next 4, etc.
  4. starting at 8 print the next 8 numbers, skip the next 8, print the next 8, skip the next 8, etc.
  5. etc

You will implement this using nested for loops to print out the 8 sets of numbers (that is, you cannot just cut-n-paste these numbers into your program).

You can then calculate the number the person is thinking of by simply adding up the first number in each one of the lists the user said "yes" to. In the example above this would be 1+4+8+64 = 77.

The homework is due on Monday, February 6 @noon at the dropbox.cse.sc.edu as usual. Yes, this is the same time as your Test 1.

Monday, January 23, 2012

Homework 1 Solution

Here is my solution to HW1. Please look at it and compare it with your solution.

We will not be taking off points for "style" issues in this class as our goal is just to learn to write programs that work. However, for those of you that want to get better at programming, notice that if you had the line .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.

In this case, the 'knowledge' that e turns into a 3 must appear only once in your program. There are two main reasons for this:
  1. If the knowledge changes in the future you will have to change the code in multiple places. For example, if we wanted e to turn into a 3 or # then we would have to make this change in multiple places. This change might have to be made by a different person from the one who initially wrote the code, so it might not be obvious, and he might just change it in one place, thus introducing a nasty bug.
  2. Because it is harder to change the program, we are now less likely to do so, even if it would be profitable. We humans are lazy, illogically so sometimes. If you can make your program easy to change then you will change it lot more, new features will be added, more bugs will be fixed, more costumers will be pleased, mo' money in your pocket. If your program does not change, it dies.

Homework 2: MasterMindz



For this homework you will implement a variation of the Mastermind board game, where we are using digits instead of colors and changing the rules a little bit. In this game your program will generate a random 4-digit number that the user then has to guess (use Math.random() to generate a random number). After the user makes a guess your program will tell him:

  1. how many of the digits in his guess are correct, that is, they have the same value and in the same position as in the secret,
  2. how many digits in his guess are not found in the secret.

Below is a sample run. Notice that the program is telling the user the secret. This is useful for debugging. The program you turn in should also tell the user the secret so as to make it easier for us to grade it.
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.


This homework is due Monday, Jann 30 @noon in the dropbox.cse.sc.edu

Wednesday, January 18, 2012

Homework Grading Rubric

The homework assignments will be graded out of 10 points. The grade assignment will follow these guidelines:

  • If it works for all inputs, and has the student(s)' names on a comment, has at least a couple short comments explaining what it does, and is properly indented then 10 points.
  • If it works for all inputs but is missing one of the other requirements then 9 points.
  • If it does not work for some inputs or in some cases but works in others, then 8 points.
  • If it does not compile then it will get a maximum of 7 points, maybe less depending on how much working code is there.

Saturday, January 14, 2012

HomeWork 1: Tweet to Leet

For the first homework you will implement a simple twitter message to Leet translator. You will need to use the String class (Chapter 2) and if-else statements (Chapter 3) which we will cover the week of Jan. 16. Your program will ask the user for a tweet, change all the characters in the tweet to lower case, then it will print out that tweet but translated to Leet using the substitutions below.

Replace thiswith this
and&
a4
b8
e3
g6
l1
o0
s5
t7
z2

The message can also contain up to one hash tag. A hash tag starts with a # then some non-space characters, then ends with a space. So #hello is a hashtag but # by itself is just a #. Your program will find and print out this hash tag, if there. Also, the hashtag should not be changed into Leet. You can assume that there is at most 1 hash mark in the message the user types in.

Finally, you will print out the length of the tweet and if it is more than 140 characters you will print out an error message.

Below are some examples.


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.


Remember that work on pairs if at all possible.

This homework is due Monday January 23 @noon in the dropbox.cse.sc.edu.

Thursday, November 18, 2010

HW7 Solution

Below is my solution to the homework:

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);
  }
 }

}

Tuesday, November 9, 2010

HW 7: Fractals

In this homework you will practice recursion by drawing some well-known fractal curves. You have to use the Point and Vector classes I provide below to do your arithmetic. I will explain them in class today. The code below also creates a window and draws a line. You will use that as a starting point for your project.
The first curve you will implement is known as the Levy C Curve and its stages are shown on the first figure. A level 0 curve is just a line between two points:start and end. At level 1, instead of drawing a line between the two points, we
  1. find the midpoint between the two points,
  2. find the vector that is perpendicular to the line, scale it by .5
  3. add the perpendicular vector to the midpoint to get a new point, call it NP
  4. recursively draw a c-curve from the start to NP and another one from NP to the end point.
The above set of steps is pseudo-code for the Java recursive function you will write to draw the C Curve.
The second curve you will implement is the Dragon Curve which is nearly identical to the C curve expect that sometimes we use one perpendicular (right) and sometimes the other (left). You will implement another method which draws the Dragon curve.
The third fractal you will implement is the Sierpinsky triangle. This one is different in that, instead of drawing a line by breaking it up into two pieces, you will be drawing a triangle by breaking it up into three smaller triangles. The recursion will be similar but the drawing code will be different.
Finally, after you get these to run then go back and change them so that they calculate and printout the length of the fractal they have just drawn. That is, the sum of the length of all the little line segments.
This homework is due on Thursday, November 18 @9am. Below is the code for Point and Vector which you must use as well as a short program that draws a line, to get you started.
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);
  }
 }
}

HW6 Solution

Below is my solution to HW6:
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);
  }
 }
}