Header

divider
Links
• Home
• Contact Me
• 
Aeries Portal
• Royal High School
• Simi Valley USD

divider

AP Statistics

• Course Calendar
• Chapter Notes
• Practice Tests
• Statistics Links

divider
AP Comp-Sci
 Course Content
• Programs
• Practice Tests
• Comp-Sci Links

divider

CP Statistics
• Course Calendar
• Chapter Notes
• Practice Tests
• Statistics Links


divider

Algebra
• Table of Contents
Geometry
• Table of Contents

Math Power
• Table of Contents

AP Computer Science Unit 4 Programs
Data Structures: Arrays, Strings and ArrayLists

WORKING WITH TEXT FILES
 

(1) Write a program that will read an unknown number of single-digit integers from a text file located in h:\\txtfiles\\numbers.txt. The numbers should be displayed on the screen as they are read and the summary statistics determined and displayed as shown below.

Write a program that will read an unknown number of single-digit integers from a text file located in h:\\txtfiles\\numbers.txt. The numbers should be displayed on the screen and the summary statistics determined and displayed as shown below.

N=15
Average = 5.8

High = 9

Low = 2

(2)  

(3)

(4)  

 

(5)  


WORKING WITH ONE-DIMENSIONAL ARRAYS

(1)   Write a program that tests the randomness of the computer’s random number generator. Generate 10,000 integers in the range 0 to 9 and display a list of the counts for each number at the end. Since there is a 1 in 10 chance for each number, there should be about 1000 of each when done.

         Sample Output

     0’s: 1007
     1’s: 1024
     2’s: 989
     etc...

(2)   Write a program that generates 10 random integers from 1 to 100. Display a list of the odd and even integers, with results displayed as shown below.

         Sample Output

     Odds: 11  75  43  89

     Evens: 26  32  68  52  84  40

(3) Roll a pair of dice and find their sum 250 times. Count the frequency of each sum in an array and then display a bar graph of the results, like that shown below:

2: ********
3: **************
4: ********************
5: *******************************
6: **************************************************
7: **********************************************************
8: ********************************************
9: **************************
10: ******************
11: ************
12: ******

 

(4)   A teacher wants to select up to 10 students from a class of size N (N>=20, as chosen by the user) to take part in a survey. In order to eliminate bias on the part of the teacher, a computer program will be used to randomly select the students. Each student will be assigned a unique integer from 1 to N and the program will generate the numbers of the students randomly. Each student may be chosen only once (i.e., no repeats) and a list of the students’ numbers will be printed to the screen. Begin the program by asking the teacher how many students are in the class. Then ask for the number of students to generate (must be from 1 to 10). Finally, display the random student numbers.

Example Run of the program:

How many students are in the class? 32
How many students to randomly select? 5

Students selected are:   13  25  7  8  30

 

(5)   Super Flakes© cereal is giving away a set of four toys, one in each cereal box. They have made an equal number of each toy, and randomly distributed the toys in the cereal boxes. Your goal is to collect the entire set. How many boxes of Super Flakes can you expect to buy? Perform a simulation using 10,000 trials to determine the average # of boxes needed to get a complete set of the four toys. Enter the number of trials as input. Display the average, rounded to 2 places. If you would like to see a demonstration of a version of this problem go to: http://www.mste.uiuc.edu/reese/cereal/maincereal.html.

Display the results of each trial as follows:

Toy 1 = 3,  Toy 2 = 2, Toy 3 = 1, Toy 4 = 2     Total = 8 boxes

Where each number represents the number of each toy received in that trial. Note that at least one of these will always be 1 (the last toy received to complete the set).

(6)      Write a program that allows the user to pick 6 unique Lotto numbers (range: 1–51). The program will then simulate a Lotto drawing by randomly selecting 6 unique numbers in the range of 1-51. Display the random Lotto numbers and the number the user got right.

Note: Both the users chosen numbers and the random Lotto numbers should be stored in integer arrays. Also, the order of the numbers does not matter when matching. Error checking must be done to ensure that the user does not give the same number twice.

 

 

WORKING WITH TWO-DIMENSIONAL ARRAYS)

(1) Write a program to generate a random playing field for the game Minesweeper. Begin the program by asking what the dimensions of the field should be (max: 10 x 10). Then ask for the number of mines to be placed (error-check to make sure that there are enough spaces for the specified number of mines). Next, randomly place the mines on the field. Then display the field to the screen showing:

  • X's for squares containing mines
  • A number corresponding the number of adjacent mines for each box that is adjacent to at least one mine
  • 0’s for squares that are not adjacent to mines

Here is an example for a 5x5 field with 6 mines:

0

1

1

2

1

1

2

X

3

X

1

X

2

3

X

2

3

3

2

1

1

X

X

1

0

 

(2)  Write a program to simulate the random movement of an ant walking on a coordinate grid with dimensions 9x9. Position the ant in cell (5,5) to begin. Then allow the ant to move randomly up, down, left or right. The ant stops when it falls off of the grid (goes to 0 or 10 in either direction). In the example below, the ant falls off the grid to the South, noted by the X. As the ant is moving, you need to keep track of the following information:

  • The number of moves before falling off
  • The number of times the ant visited each cell (displayed in the matrix)
  • Which direction the ant fell off the grid (North, South, East or West)

Note: You must update and redisplay the matrix after each movement

0

0

0

0

0

0

0

0

0

0

0

1

0

0

0

0

0

0

0

0

2

1

0

0

0

0

0

0

0

1

2

1

0

0

0

0

0

1

2

1

2

0

0

0

0

0

0

1

0

0

0

0

0

0

0

0

1

0

0

0

0

0

0

0

0

2

2

0

0

0

0

0

0

0

1

1

0

0

0

0

0

X

 

(3) In the carnival game Penny Pitch, a two-dimensional board of numbers is laid out at follows:

1
1
1
1
1
1
2
2
2
1
1
2
3
2
1
1
2
2
2
1
1
1
1
1
1

A player tosses three pennies on the board, aiming for the number with the highest value. At the end of the game, the sum total of the three tosses is returned. Write a program that plays this game. The program should perform the following steps for each new game:

  • Generate two random numbers for the row and column of the toss
  • Add the number at this position to a running total
  • Display the board, replacing the numbers with P’s where the penny lands

Note: Each penny must land in a separate space. This requires a separate, Boolean matrix to ensure no duplicates are used.

 

(4)  The “Game of Life” is a genetics simulation, which is popular with mathematicians and computer scientists. It is called a game because of the various outcomes over generations of times. The game was invented by John Conway, a noted mathematician, to model the life cycles of simple organisms.

In the Game of Life, a given organism occupies a single space in a two-dimensional array of n rows and m columns. The current population is considered a generation for a small game:

 

 

%

 

 

 

 

 

 

%

%

%

 

 

 

%

%

%

 

 

 

 

 

 

In one version of the game, the species live and die according to the following rules:

  1. Each empty space with three adjacent occupied spaces will be occupied in the next generation
  2. Any occupied space with only one or with no neighbors will die of loneliness and be empty in the next generation.
  3. Any occupied space with four or more neighbors will die of overcrowding and be empty in the next generation.
  4. Any occupied space with two or three neighbors will live into the next generation.

Write a program to play the game of life over 10 generations, showing one generation at a time. Use a field 20x20 and start with 50 randomly selected occupied cells. The screen should clear and show the next generation when the user presses enter (or any other key if you wish).

See these links to get a better understanding of this "game":
http://www.math.com/students/wonders/life/life.html
http://www.ibiblio.org/lifepatterns/

 

(5)  

 

(6)   

  


WORKING WITH THE STRING CLASS

(1)   Write a program that asks for a single word, then displays that word backwards.

     Sample Output

     input:   stressed
     output:   desserts

(2)  Write a program to accept a word, then display the word as shown in the following examples:

Input:        Royal                                         

Output:    
R
                                                   
RO                         
ROY                        
ROYA                       
ROYAL

Note: the output requires that the input string be changed to all caps for output.

(3) Write a program that will allow the entry of a name consisting of a first and last name (with a space separating the two). The input is to be made into a single string. The program should then output the results in the form last, first. See the example below:

Input:        Jerry Seinfeld                           

Output:       Seinfeld, Jerry

 

(4) Write a program to put a given word into Pig Latin. There are many forms of this made up language, but here are the rules we will use:

  • If the word begins with a vowel, put way on the end of it. Example: apple becomes appleway.
  • If the word begins with a consonant, move all leading consonants to the end and put ay after it. Examples: night becomes ightnay and scram becomes amscray.
  • A special case (optional): Words with qu at the beginning require that the u goes to the end along with the q. Examples: quit becomes itquay, square becomes aresquay.

(5) Write a program to analyze the words in a sentence. This program should accept a sentence into a string, and then determine the number of words in that sentence, the average word length and the length of the longest word. Hint: a word is detected when a space or punctuation mark is encountered. For example, if the sentence is “The quick silver fox jumped over the lazy brown dog.”, the output of the program will be:

Number of Words: 10
Average Length: 4.2
Longest Word: 6

 

(6) Write a program that will accept both a sentence and a single letter into separate variables.  The program should then display all words in the sentence that contain the given letter. See the following examples:

Input:

Sentence: Where are they now?

Letter: e

Output:

Where
are
they

Input:

Sentence: I went to the store.

Letter: o

Output:

to
store

If there is no occurrence of the letter in the sentence, display a message stating so.

 

(7) Write a program that will accept 3 words into 3 separate strings, and then display the words in alphabetical order, one line at a time. Use the compare method See the example below.

Input words: Royal, Simi, Santa

Output:

ROYAL
SANTA
SIMI

Note that all words must be capitalized to do this.

 


WORKING WITH THE ARRAYLIST CLASS

  1. GET IN LINE – Write a program that uses an ArrayList to store a list of names for people who are standing in a line. Initially, the list should contain (in the order given): Andrew, Sarah, Will, Evelyn and David. The program should then carry out the following activities:  

·   Steven joins the end of the line

·        Evelyn gets out of the line

·        Samantha cuts in line in and gets in position #1 (recall that positions start with 0)

·        Display the current position # for Will (recall that positions start with 0)*

·        Jessica joins the end of the line

·        Will gets out of the line and rejoins it at the end, behind Jessica

·        Display the name of the person currently in the next to last position in line**

·        The first and last people in line switch places

·        Display a message declaring whether or not a person named David is in the line.***

·        The user enters the name of a new person (use “Chris”) and a position for them to enter the line (use 3). Be sure to error-check the position #, as the line may not contain enough people to make that position possible.

·        All people whose names start with the letter “S” get out of line

·        Display the final order of the people in the line. Also, error-check to ensure that there are still people in line before attempting to print the list.****

          The displayed results should be as follows (use the *’s for reference):

                  * 3

                  **Jessica

                  *** YES or TRUE

                  **** [Will, Chris, David, Jessica, Andrew].

            NOTE: In writing this program, you will need to use EVERY ArrayList method at least once. At least I think so!

2.    Distinct Words – Write a program that will read a list of words out of a file and display all words (without duplications), in alphabetical order. As it reads each word, it should determine whether that word is already in the list. If it is, disregard it - if not, put in place in its correct position for alphabetization. Display the words one line at a time as shown below (which is the desired result). All words in the text file are lowercase. There are 20 total words in the file. The file is words.txt.

a
boy
dog
fast
good
is
run
runs
see
spot

 

 

 

 

Home  •  About Me  •  Aeries Portal  •  Contact Me
© DanShuster.com