## Hurray, arrays!

posted by: Ms. Martin 14 December 2010 One Comment
1. 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).
2. Write a method shuffle that given an array of Strings, randomly orders it.  Do you have to return the array?  Can you use the swap method we wrote together?  Use the Math.random static method.  Shuffle your deck of cards and print it out using Arrays.toString
3. 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.
4. 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?

(30 votes, average: 2.83 out of 5)