Arrays as Parameters Worksheet

posted by: Mr. Bergquist 12 January 2012 No Comment

Class Resources: Arrays by ReferenceArrays, Part I & Handout: Arrays.

A few Practice It warm up’s before some Arrays as Parameters, do these first five and then try the later set… (updated to use BJB 3rd Edition)

  1. numbersArray (BJP3 Self-Check 7.5)

  2. An Array Mystery (BJP3 Self-Check 7.23)

  3. All Less (BJP3 Self-Check 7.17)
  4. Deck of Cards: Use this Starter Code for these two Deck of Card methods (4 & 5):  PlayCards.java
    Consider the two following arrays:
    String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};
    String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"}; 
    Write a method that returns an array containing all possible playing cards as strings in the format “rank of suits” (use nested loops).
  5. Shuffle Cards: Write a method shuffle that given an array of Strings (use the array from the previous problem), randomly orders it.  Do you have to return the array?  Can you use the swap method in the presentation?  Use the Math.random static method.  Shuffle your deck of cards and print it out using Arrays.toString

Done Already?  Then try these interesting challenges:

  1. The birthday problem is a fascinating probability puzzle with implications in cryptography.  To investigate this problem, you will write a simulation to see on average how many people have to enter a room before two share a birthday.  Assume birthdays are represented by an integer between 0 and 364, each with an even probability.  Look at the die-rolling example done in class for ideas.  You will need a counter array of size 365.
  2. Write a method that given an integer n returns an array of all primes up to and including n.  You will use a technique called the Sieve of Eratosthenes.  You will use a boolean array isPrime of size n where isPrime[i] is true if i is prime and false otherwise.  Initially, set all array elements to true.  Then repeat the following steps as long as i <= n/i:
    • Find the next smallest i where isPrime[i] is true
    • For all multiples of i, set the isPrime entries to false

    Once this is complete, the array should have a true for each prime and false for each non-prime. Collect the primes into an array (how many passes over the array does this take?)

    Compare this strategy to a more naive strategy that counts the factors for each number up to n.  What is the speed difference like?

1 Star2 Stars3 Stars4 Stars5 Stars (9 votes, average: 4.33 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>