Wednesday, May 2, 2012

Till Next Time

The grades have been posted to VIP. This site will remain up until the next time I teach this class.

If you are a visitor to this site and want to take a free intro to Java class, simply watch the 62 Java tutorial videos (or, watch them without ads at udemy.com) and do the 25 Lab assignments (2-hour programming projects) and 10 homework assignments (longer programming projects) to get some practice. You can then the tests to see how much you have learned. Have fun!

Also, if you want to leave any advise to future students, you can do so in the comments to this post.

Monday, April 30, 2012

Final Tests

These are the final tests. If you want your graded final just send me an email and I will tell you when I'll be in my office so you can pick it up.

  1. (10%) Implement a method that prints out all the numbers between 1 and 10,000,000 except that if the number is a multiple of 3 you will print "GO", if it is a multiple of 7 you print "Cocky" and if its a multiple of both 3 and 7 you print "Go Gamecocks". That is, the first part of the output looks like
    1
    2
    GO
    4
    5
    GO
    Cocky
    8
    GO
    10
    11
    GO
    13
    Cocky
    GO
    16
    17
    GO
    19
    20
    Go Gamecocks
    22
    ...and so on...
  2. (10%) Implement the method int add(String a, String b) (notice, a and b are String) which adds the two arguments and returns the sum, but only if the two are integers. If they are not then it returns 0. For example
    add("5", "3") //returns 8
    add("bob", "3")  //returns 0
    add("bob", "alice")  //returns 0
    add("1.456", "8")  //returns 0
                
  3. (10%) Implement a method String myCode(boolean[] msg) which translates the boolean array into a string using the following
    code:
    true → E
    false true → T
    false false true → A
    false false false → b
    For example,
    boolean[] m1 = {true};
            System.out.println(myCode(m1)); //prints "E"
    
            boolean[] m2 = {false, true, false, false, false};
            System.out.println(myCode(m2)); // "Tb"
    
            boolean[] m3 = {true, false, false, true, false, false, false};
            System.out.println(myCode(m3)); // "EAb"
    
            boolean[] m4 = {false, false, false, false, false, false, false, true};
            System.out.println(myCode(m4)); // "bbT"
                
  4. (10%) Given that you have
    public enum SmartPhone {iphone3g, iphone4, iphone4s, android};
              
    Implement a method that takes SmartPhone as an argument and returns its price, as given by the following table

    ItemPrice
    iphone 3g300
    iphone 4349
    iphone 4s400
    android200
  5. (10%) What does the following program printout?
    public class PrintoutExceptions {
    
        public static String xkcd(int x) throws Exception{
            if (x < 0){
                return "Magnets";
            }
            else if (x < 5){
                return "Sticks";
            }
            else if (x % 2 == 1){
                return "Number:" + Integer.toString(x);
            }
            else throw new Exception("Caramba");
        }
    
    
        public static void main(String[] args) {
    
            int[] a = {-5,0,1,3,7,8};
            for (int i = 0; i < a.length; i++) {
                try {
                    System.out.println(i + "-" +  xkcd( a[i] ));
                } catch (Exception e) {
                    System.out.println("Ooops");
                }
            }
        }
    }
  6. (10%) Does the program below run or crash? If it runs, show what it prints out when it runs. If it crashes, explain why.
    public class A {
    
        public String toString() {
            return "I am A";
        }
    }
    
    public class B extends A {
    
        public String toString() {
            return "I am B";
        }
    }
    
    public class C extends A {
    
        public String toString(){
            return "I am C";
        }
    }
    
    public class Q6 {
    
        public static void main(String[] args) {
            A[] as = new A[3];
            as[0] = new A();
            as[1] = new B();
            as[2] = new C();
            for (A a : as) {
                System.out.println(a.toString());
            }
        }
    } 
  7. (10%) Given the following code:
    public class Person {
    
        private int money;
    
        private Person[] friends;
    
        public int minDistanceToMillionaire(){
            //TODO: implement this method
        }
    }
    implement the missing method using recursion, which will return the distance to the closest millionaire. For example, if the person is a millionaire (has money >= 1,000,000) then it will return 0. Otherwise, if the person has a friend who is a millionaire then it will return 1. Otherwise, if the person has a friend who has a friend that is a millionaire then it will return 2, and so on.
    You can assume that the graph does not have loops in it. That is, you will never see the same Person twice.


  8. (10%) Assume that you are given a class called Person which has a method called int distanceTo(Person other) that returns the distance between where this person lives and where other lives.
    Implement a method
    ArrayList<Person> hasFriendsCloserThan(HashMap<Person, HashSet<Person>> socialNet, int n) 
    that takes as input a socialNet, which is a mapping between a Person and his friends, and returns the list of all the people who have at least one friend that lives a distance of less than n away from them.


The other test:

  1. (10%)Implement a method that returns the sum of all the odd numbers between 1 and 1,000,000 except that those that are multiples of both 3 and 5 count double, while those that are multiples of either just 3 or just 3 don't get counted. For example, if the sum was just between 1 and 20 then you would return 98 because that is the sum of 1 + 7 + 11 + 13 + (15*2) + 17 + 19.
  2. (10%) Implement a method int ssnToInt(String ssn) which, when given a a String represenation of a social security number that looks like "123-45-6789" returns the integer that represents that number, namely 123456789. If given a String that does not match then it returns -1. Specifically,
    ssnToInt("123-45-6789") //returns 123456789
    ssnToInt("123456789") //returns -1
    ssnToInt("12304506789") //returns -1
    ssnToInt("12389") //returns -1
    ssnToInt("7aa-90-879B") //returns -1
            
  3. (10%) Implement a method String compress(String dna) which takes as input a String that contains only the characters A,C,G, and T, and then compresses the string by counting how many times each one appears consecutively. If a character appears more than once in a row the whole sequence is replaced by the character followed by the number of times it appeared in a row. For example:
    String d1 = "ACGT";
            System.out.println(compress(d1)); //prints ACGT
    
            String d2 = "AAAAACGT";
            System.out.println(compress(d2)); //prints A5CGT
    
            String d3 = "CCCTTTTAGGGGG";
            System.out.println(compress(d3)); //prints C3T4AG5
    
            String d4 = "AAAAAA";
            System.out.println(compress(d4)); //prints A6
                
  4. (10%) Given that you have
    public enum Tablet {ipad, ipad2, newipad, galaxy}; 
    Implement a method that takes a SmartPhone and returns its price, as given by the following table

    ItemPrice
    ipad300
    ipad2400
    newipad600
    galaxy300

  5. (10%) What does the following program printout?
    public class PrintoutExceptions {
    
        public static String onion(int x) throws Exception{
            if (x % 2 == 1){
                return "Carrot";
            }
            else if (x <= 0){
                return "Sticks";
            }
            else if (x < 5){
                return "Number:" + Integer.toString(x);
            }
            else throw new Exception("Caramba");
        }
    
    
        public static void main(String[] args) {
    
            int[] a = {-5,0,1,3,7,8};
            for (int i = 0; i < a.length; i++) {
                try {
                    System.out.println(i + "-" +  onion( a[i] ));
                } catch (Exception e) {
                    System.out.println("Ooops");
                }
            }
        }
    }
  6. (10%) Does the program below run or crash? If it runs, show what it prints out when it runs. If it crashes, explain why.
    public class A {
    
        public String toString() {
            return "I am A";
        }
    }
    
    public class B extends A {
    
        public String toString() {
            return "I am B";
        }
    }
    
    public class C extends A {
    
        public String toString(){
            return "I am C";
        }
    }
    
    public class Q6 {
        static void foo(A a){
            System.out.println(a.toString());
        }
    
        public static void main(String[] args) {
            foo(new A());
            foo(new B());
            foo(new C());
        }
    } 
  7. (10%) Given the following code:
    public class Person {
    
        private Person mother;
    
        private Person father;
    
        public int generationsToOldestKnownAncestor(){
            //TODO: implement this method
        }
    
    }
    implement the missing method using recursion, which will return the distance to the oldest known ancestor. If we don't know a Person's mother or father we set those properties to null. For example, if a Person has both mother and father as null then the method should return 0. But, if the person has only a mother, who in turn has both mother and father set to null then it should return 1, and so on.
    You can assume that the graph does not have loops in it. That is, you will never see the same Person twice.

  8. (10%) Implement the method
    String topPerson(HashMap<String, ArrayList<Double>> gradeMap)
    which takes as input a gradeMap, which is a mapping from a student's name to his list of grades, and which returns the name of the student with the highest grade. For example, if Alice has grades of 10, 20, 88, and Bob has grades of 77, 55, then it would return Alice because of her 88.

Final Test Point Distribution

The final test point distribution is below, these are points not grades. You will receive the actual grade along with your class grade in an email that I have just sent.




Wednesday, April 18, 2012

Lab 25: Social Zombies

In this lab you will write a program to simulate the spread of a virus among a population. Our virus of choice is the zombie virus. We assume that each person has the same number of friends, all chosen randomly from the population. Then, at each time step, all zombie persons will randomly choose one of their friends (zombie or not) and bite him. If the friend was not a zombie he will turn into a zombie. Zombie bites on zombies do nothing.

More specifically, for this lab you will implement a Person class and a Graph class.

The Person has (at least, you will need more methods):
  • a data member friends that holds all his friends (which are of type Person)
  • a boolean zombie which tells us if he is a zombie

The Graph class has (at least, you will need more methods)
  • a people data member which holds all the people
  • a getRandomPerson() which returns a random person from people
  • a getRandomOther(Person p) which returns a random person from people that is not p
  • a makeFriends(int x) which gives each person in the graph x randomly chosen friends
  • a infectOne() method which infects (sets as a zombie) one random person
  • a go() method which runs one step of the simulation: all the zombies bite one of their friends at random
Thus, the following main
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the number of people:");
    int numPeople = keyboard.nextInt();
    System.out.print("Enter the number of friends each person has:");
    int numFriends = keyboard.nextInt();
    Graph g = new Graph(numPeople);
    g.makeFriends(numFriends);
    //print it out, for testing.
    //System.out.println(g);
    g.infectOne();
    int day = 1;
    int count = 0;
    do {
      count = g.getNumZombies();
      System.out.println("Day " + day + ": Zombie count is " + count);
      g.go();
      day++;
    } while (count < numPeople);
    System.out.println("Zombieland");
   }
will print out something like:
Enter the number of people:100
Enter the number of friends each person has:5
Day 1: Zombie count is 1
Day 2: Zombie count is 2
Day 3: Zombie count is 4
Day 4: Zombie count is 10
Day 5: Zombie count is 21
Day 6: Zombie count is 35
Day 7: Zombie count is 59
Day 8: Zombie count is 77
Day 9: Zombie count is 89
Day 10: Zombie count is 91
Day 11: Zombie count is 96
Day 12: Zombie count is 97
Day 13: Zombie count is 97
Day 14: Zombie count is 99
Day 15: Zombie count is 100
Zombieland
Note that if you use a small number of friends (say, 2) then it might get into an infinite loop with a fixed number of zombies. This is because none of the zombies have a friend that is not a zombie (what you have then are 2 or more disconnected graphs, in graph theoretic terms). As always, turn it in on the dropbox.cse.sc.edu. You have an extra 48 hours to finish this lab, if you can't finish it during lab.

This is the last lab for the year. See you at the Final!

Test 3 Points Distribution

The points distribution for Test 3 is below. These are points, not grades. I will talk about grades in class.



Monday, April 16, 2012

Test 3

Here are the two tests, with some sample solutions.
  1. (25%) What does the following program print out when run?
    public class Q1 {
    public static boolean swing (int strength) throws Exception{ if (strength < 5) throw new Exception("Too weak"); if (strength > 10) return false; return true; }
    public static void main(String[] args) { int[] strengths = {5,6,-1,12}; for (int s : strengths) { try { if (swing(s)) System.out.println("Homerun"); else System.out.println("Strike!"); } catch (RuntimeException e){ System.out.println("You are OUT!"); } catch (Exception e) { System.out.println(e.getMessage()); } } System.out.println("Done."); } }

  2. (25%)Given a text file called sales.txt which contains data that looks like
    aba 55.99
    akdkd8dj 12.95
    iwjwhe 4
    Iji8keJl 44.99
    ijdddawe 10.00
    ...and so on for many more rows...
    
    where each row represents one item that is for sale in a store. The first column is a String that uniquely identifies the item and the second column is a double that represents the price of the item. Write a program which


    1. Implements a simple Item class that can represent one item.
    2. In the main, your program reads the complete contents of the file sales.txt into an ArrayList<Item> variable called items.
    Answer:
    public class Item {
        private String sku;
    
        private double price;
    
        public Item(String sku, double price){
            this.sku = sku;
            this.price = price;
        }
    
        public String toString(){
            return sku + " " + price;
        }
        public static void main(String[] args) {
            try {
                Scanner in = new Scanner(new FileInputStream("sales.txt"));
                ArrayList<Item> items = new ArrayList<Item>();
                while (in.hasNext()){
                    String sku = in.next();
                    double price = in.nextDouble();
                    items.add(new Item(sku,price));
                }
                System.out.println(items);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
       }
    } 
  3. (25%) Read over the code below and implement the empty method.
    import java.util.ArrayList;
    
    public class Q3 {
    
        private ArrayList<Q3> data;
    
        private Integer number;
    
        public Q3(Integer number){
            data = new ArrayList<Q3>();
            this.number = number;
        }
    
        public void add(Q3 q){
            data.add(q);
        }
    
        public void add(Integer number){
            data.add(new Q3(number));
        }
        
        /**
         * Calculates and returns the sum of all even numbers in
         * this object or in any of the ones in 'data', and so on
         * recursively.
         * @return The sum.
         */
        public int sumEven(){
            //TODO: implement this method
            int result = 0;
            if (number % 2 == 0)
                result = number;
            for (Q3 q: data){
                result += q.sumEven();
            }
            return result;
        }
        
    
        public static void main(String[] args) {
            Q3 q = new Q3(0);
            Q3 first = new Q3(1);
            q.add(first);
            Q3 second = new Q3(2);
            q.add(second);
            q.add(3);
            q.add(4);
            first.add(8);
            second.add(5); 
            System.out.println(q.sumEven());
        }
    }
    For example, when the main above is run it should print out
    14
  4. (25%) Implement a method String mostFrequent(String s) which returns the 3-character substring that appears most frequently in s, or one of the most frequent if there is a tie. For example
    mostFrequent("AABABA") returns "ABA" because "ABA" appears twice
    mostFrequent("AAAAAB") returns "AAA" because it appears 3 times
    mostFrequent("ATATATA") returns "ATA" because it appears 3 times
                
    Answer:
    public static String mostFrequent(String seq){
            HashMap<String, Integer> count = new HashMap<String, Integer>();
            int max = 0;
            String maxKey = null;
            //add them all
            for (int i = 0; i <= seq.length() - 3; i++) {
                String key = seq.substring(i,i+3);
                if (count.containsKey(key))
                    count.put(key, count.get(key) + 1);
                else
                    count.put(key, 1);
                if (count.get(key) > max){
                    max = count.get(key);
                    maxKey = key;
                }
            }
            return maxKey;
        }



And, the other one:


  1. (25%) What does the following program print out when run?

    public class Q1 {
    public static boolean pitch (String type) throws Exception { if (type.startsWith("f")) return true; if (type.startsWith("c")) return false; if (type.startsWith("x")) throw new Exception("Oops"); return true; }
    public static void main(String[] args) { String[] types = {"fast", "foo", "curve", "xoom"}; for (String t : types) { try { if (pitch(t)) System.out.println("Hit"); else System.out.println("Miss"); } catch (RuntimeException e){ System.out.println("You hit the umpire"); } catch (Exception e) { System.out.println(e.getMessage()); } } System.out.println("Done."); } }

  2. (25%) Given a text file called points.txt which contains data that looks like
    1.44 5.666
    12.999 0
    9.163 3.1415
    6 7
    5 6.999
    ...and so on for many more rows...
    
    where each row represents the x and y coordinates of a point in 2-dimensional space. Both columns are doubles. Write a program which


    1. Implements a simple Point class that can represent one point in space.
    2. In the main, your program reads the complete contents of the file points.txt into an ArrayList<Point> variable called points.
    Answer:
    public class Point {
    
        private double x;
        private double y;
        public Point(double x, double y){
            this.x = x;
            this.y = y;
        }
        public String toString(){
            return "(" + x + "," + y + ")";
        }
        public static void main(String[] args) {
            try {
                Scanner in = new Scanner(new FileInputStream("points.txt"));
                ArrayList<Point> points = new ArrayList<Point>();
                while (in.hasNext()){
                    double x= in.nextDouble();
                    double y = in.nextDouble();
                    points.add(new Point(x,y));
                }
                System.out.println(points);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
  3. (25%) Read over the code below and implement the empty method.
    import java.util.ArrayList;
    
    public class Q3 {
    
        private ArrayList<Q3> data;
    
        private Integer number;
    
        public Q3(Integer number){
            data = new ArrayList<Q3>();
            this.number = number;
        }
    
        public void add(Q3 q){
            data.add(q);
        }
    
        public void add(Integer number){
            data.add(new Q3(number));
        }
    
        
        /**
         * Find if x is either equal to number, or equal to one of
         * the numbers in 'data', and so on recursively.
         * @param x the number we are looking for
         * @return true if x is there, false otherwise.
         */
        public boolean find(Integer x){
            //TODO: implement this method
            if (number == x)
                return true;
            for (Q3 q : data) {
                if (q.find(x))
                    return true;
            }
            return false;
        }
    
        public static void main(String[] args) {
            Q3 q = new Q3(0);
            Q3 first = new Q3(1);
            q.add(first);
            Q3 second = new Q3(2);
            q.add(second);
            q.add(3);
            q.add(4);
            first.add(8);
            second.add(5); 
            System.out.println(q.find(3));
            System.out.println(q.find(5));
            System.out.println(q.find(10));
        }
    }
    For example, when the main above is run it should print
    out
    true
    true
    false
  4. (25%) Implement a method String mostPoints(String[] name, int[] points) which returns the name that has the most points, assuming that for all indeces i we have that points[i] has the number of points for name[i]. For example
       String[] name1 = {"a", "b", "c", "a", "b", "a"};
       int[] points1 =  { 1,   2,   7,   4 ,  3,   1};
       mostPoints(name1, points1); //returns "c" because it has 7
       // points and "a" has 6, and "b" has 5.
    
       String[] name2 = {"a", "b", "c", "a", "b", "a"};
       int[] points2 =  { 5,   2,   7,   4 ,  3,   1};
       mostPoints(name2, points2); //returns "a"
    
       String[] name3 = {"a", "a", "a", "a", "b", "c"};
       int[] points3 =  { 1,   1,   1,   1 ,  3,   2};
       mostPoints(name3, points3); //returns "a"
    Answer:
    public static String mostPoints(String[] name, int[] points){
            HashMap<String, Integer> count = new HashMap<String, Integer>();
            int max = 0;
            String maxKey = null;
    
            for (int i = 0; i < points.length; i++) {
                if (count.containsKey(name[i]))
                    count.put(name[i], points[i] + count.get(name[i]));
                else
                    count.put(name[i], points[i]);
                if (count.get(name[i]) > max){
                    max = count.get(name[i]);
                    maxKey = name[i];
                }
            }
            return maxKey;
        }

Wednesday, April 11, 2012

Lab 24: Cards


For this lab you will implement two classes, a Card and a Hand class.

The Card represt a card, which has a number and a Suit, there is also a Joker. The toString() method of this class will return the card's name in English, as shown below.

The Hand class uses a HashSet<Card> to hold a set of cards, which starts out empty. It has an add(Card c) which adds Card c to the hand. It has a methods makeFullDeck() which populates the hand with a full deck of cards (one Joker).

Finally, you will implement a public static HashSet<Hand> getAllHands(int numCards, Hand h) which returns the set of all the hands of numCards cards which can be created using the cards in hand h. You can do this the following recursive algorithm:
getAllHands(int numCards, Hand h)
  if numCards is 1
      then return the set of hands of just 1 card from h  
  hand = h.clone()
  result = empty set of hands
  foreach card in hand:
      remove card from hand
      allOtherHands =  getAllHands(numCards - 1, hand)
      add card to every hand in allOtherHands
      add allOtherHands to result
  return result

For example, the following main
public static void main(String[] args){
        Card twoClubs = new Card(2,Card.Suit.Clubs);
        System.out.println(twoClubs);
        
        Card oneSpades = new Card(1,Card.Suit.Spades);
        System.out.println(oneSpades);
        
        Card joker = new Card(0,Card.Suit.Hearts); //0 is the Joker 
        System.out.println(joker);
        
        Card kingDiamonds = new Card(13, Card.Suit.Diamonds); 
        System.out.println(kingDiamonds);
        
        Hand mine = new Hand();
        mine.add(twoClubs);
        mine.add(oneSpades);
        mine.add(joker); //0 is Joker
        mine.add(kingDiamonds);
        
        System.out.println("My hand is " + mine);

        //All the possible ways to pick 2 cards from mine
        System.out.println("All the possible ways to pick 2 cards from my hand are:");
        HashSet<Hand> pickTwo = getAllHands(2, mine);
        for (Hand hand : pickTwo) {
            System.out.println(hand);
        }
        System.out.println("Thus, there are " + pickTwo.size() + " possible ways.");
        System.out.println("");
        
        //All the possible ways to pick 3 cards from mine
        System.out.println("All the possible ways to pick 3 cards from my hand are:");
        HashSet<Hand> pickThree = getAllHands(3, mine);
        for (Hand hand : pickThree) {
            System.out.println(hand);
        }
        System.out.println("Thus, there are " + pickThree.size() + " possible ways.");
        System.out.println("");
        

        Hand deck = new Hand();
        deck.makeFullDeck(); //makes a full deck, with 1 Joker.
        System.out.println("The full deck is:");
        System.out.println(deck);
        
        System.out.println("All the possible ways to pick 2 cards from a full duck are:");
        HashSet<Hand> a = getAllHands(2, deck); //this will take a few seconds to run
        for (Hand hand : a) { //and a minute to print
            System.out.println(hand);
        }
        System.out.println("Thus, there are " + a.size() + " possible ways.");
        
        System.out.println("All the possible ways to pick 4 cards from a full duck are:");
        a = getAllHands(4, deck); //this will take a few seconds to run
        for (Hand hand : a) { //and a minute to print
            System.out.println(hand);
        }
        System.out.println("Thus, there are " + a.size() + " possible ways.");
    }

Should print out:
2 of Clubs
Ace of Spades
Joker
King of Diamonds
My hand is (Ace of Spades, King of Diamonds, 2 of Clubs, Joker)
All the possible ways to pick 2 cards from my hand are:
(Ace of Spades, 2 of Clubs)
(King of Diamonds, 2 of Clubs)
(Ace of Spades, King of Diamonds)
(King of Diamonds, Joker)
(Ace of Spades, Joker)
(2 of Clubs, Joker)
Thus, there are 6 possible ways.

All the possible ways to pick 3 cards from my hand are:
(Ace of Spades, King of Diamonds, Joker)
(Ace of Spades, King of Diamonds, 2 of Clubs)
(Ace of Spades, 2 of Clubs, Joker)
(King of Diamonds, 2 of Clubs, Joker)
Thus, there are 4 possible ways.

The full deck is:
(4 of Spades, 5 of Clubs, Queen of Spades, 8 of Spades, 8 of Clubs, Jack of Spades, Ace of Diamonds, Ace of Hearts, Queen of Clubs, 10 of Clubs, 3 of Spades, Queen of Diamonds, King of Spades, Ace of Spades, 6 of Diamonds, 9 of Clubs, King of Hearts, 7 of Clubs, 9 of Hearts, 4 of Hearts, Jack of Hearts, 3 of Diamonds, 4 of Diamonds, 10 of Hearts, Jack of Diamonds, 5 of Spades, Joker, 2 of Hearts, 9 of Diamonds, Ace of Clubs, 3 of Clubs, Jack of Clubs, King of Clubs, 5 of Diamonds, 10 of Diamonds, 7 of Diamonds, 8 of Hearts, King of Diamonds, 6 of Hearts, 9 of Spades, 7 of Spades, 6 of Clubs, 4 of Clubs, 3 of Hearts, 2 of Diamonds, 10 of Spades, 8 of Diamonds, 2 of Clubs, 6 of Spades, 5 of Hearts, Queen of Hearts, 2 of Spades, 7 of Hearts)
All the possible ways to pick 2 cards from a full duck are:
(Queen of Spades, Ace of Spades)
(Jack of Clubs, 5 of Hearts)
(2 of Diamonds, 5 of Clubs)
...and so on...
(King of Hearts, 3 of Diamonds)
(Jack of Clubs, 7 of Hearts)
(5 of Diamonds, Ace of Clubs)
Thus, there are 1378 possible ways.

All the possible ways to pick 4 cards from a full duck are:
(10 of Spades, 5 of Diamonds, Jack of Diamonds, Ace of Hearts)
(10 of Spades, 9 of Spades, Jack of Hearts, 7 of Diamonds)
(2 of Clubs, 7 of Hearts, Jack of Diamonds, 4 of Diamonds)
...and so on...
(6 of Diamonds, 9 of Diamonds, Ace of Hearts, 9 of Clubs)
(6 of Diamonds, 8 of Hearts, 7 of Clubs, King of Spades)
(King of Diamonds, 9 of Hearts, Jack of Hearts, 5 of Spades)
(Jack of Clubs, 10 of Hearts, 9 of Diamonds, 4 of Clubs)
(2 of Clubs, 4 of Spades, 4 of Clubs, 9 of Clubs)
Thus, there are 292825 possible ways.

Getting the recursive algorithm working might take you longer than the allotted lab time, so you can turn in this lab within 48 hours of the end time of your lab, in the dropbox.cse.sc.edu.

Hint: You will probably need to use an Iterator, because you need to Iterator.remove().

Lab and Homework Solutions

Here are my solutions to past labs:

and homeworks:


CodingBat Bonus

As in the previous tests, you will get an extra point in Test 3 for each one of the following codingbat sections you finish before Monday at noon: AP-1, Recursion-1 and Recursion-2. Remember that to get credit you have to login to coding bat, then click 'prefs' and under 'Share To' put jmvidal@gmail.com, also set your name to the name as it appears on my roster.

Also remember to study all of Chapters 9--12, as they cover material that is not in the codingbat questions but will be on the test. Do the programming problems from the back of these chapters.

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"