teaching machines

CS 145 Lab 5 – Arrays

November 6, 2015 by . Filed under cs145, fall 2015, labs.

First, if you have checkpoints left over from last lab, get them inspected during the first 15 minutes of this lab. No credit will be awarded past these 15 minutes.

Don’t forget to work in pairs! Where possible, please work with someone that you did not work with last week. The exchange of new ideas and perspectives is not an opportunity of which you want to rob yourself.

Objective

In this lab you will learn about storing and working with collections of data in arrays. Arrays let us number our data, making it easy to loop through the collection or associate data with the natural numbers.

Checkpoints 1 and 2

Solve two of the following problems:

  1. Suppose you have an array of 10 String names. You want to select 5 of them for a drug test. Repeat subjects are not allowed. Write a method that accepts the list of 10 and prints 5 unique names drawn at random.
  2. You have a list of people running for election stored in a String array. Write a method that receives this array as a parameter and enumerates all possible president/vice president pairs. For example, if the list contains Alice, Bob, and Carol, then the possible tickets are:
    P: Alice, VP: Bob
    P: Alice, VP: Carol
    P: Bob, VP: Alice
    P: Bob, VP: Carol
    P: Carol, VP: Alice
    P: Carol, VP: Bob
  3. A lot of data is impossible to use if it’s not sorted. (Find me an unsorted phonebook!) There are many algorithms for sorting data in an array. One simple one is called the selection sort. It can be described in pseudocode:
    for each cell in the list
      find the smallest value in the sublist starting at the current cell
      swap that smallest value with the value in the current cell

    Translate this algorithm into Java and sort an array of ints.