Java- Data Structures Question

Anonymous
timer Asked: Jun 23rd, 2018
account_balance_wallet $20

Question description

In this lab you will complete two applications that use the Abstract Data Type (ADT) list. The word documents are Java files (I cannot upload .java files)

/** An interface for the ADT list. * Entries in the list have positions that begin with 1. * * This code is from Chapter 12 of * Data Structures and Abstractions with Java 4/e * by Carrano */ public interface ListInterface { /** Adds a new entry to the end of this list. Entries currently in the list are unaffected. The list's size is increased by 1. * @param newEntry The object to be added as a new entry. */ public void add(T newEntry); /** Adds a new entry at a specified position within this list. * Entries originally at and above the specified position * are at the next higher position within the list. * The list's size is increased by 1. * @param newPosition An integer that specifies the desired * position of the new entry. * @param newEntry The object to be added as a new entry. * @throws IndexOutOfBoundsException if either * newPosition less than 1, or * newPosition greater than getLength()+1. */ public void add(int newPosition, T newEntry); /** Removes the entry at a given position from this list. * Entries originally at positions higher than the given * position are at the next lower position within the list, * and the list's size is decreased by 1. * @param givenPosition An integer that indicates the position of * the entry to be removed. * @return A reference to the removed entry. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T remove(int givenPosition); /** Removes all entries from this list. */ public void clear(); /** Replaces the entry at a given position in this list. * @param givenPosition An integer that indicates the position of the * entry to be replaced. * @param newEntry The object that will replace the entry at the * position givenPosition. * @return The original entry that was replaced. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T replace(int givenPosition, T newEntry); /** Retrieves the entry at a given position in this list. * @param givenPosition An integer that indicates the position of * the desired entry. * @return A reference to the indicated entry. * @throws IndexOutOfBoundsException if either * givenPosition less than 1, or * givenPosition greater than getLength()+1. */ public T getEntry(int givenPosition); /** Sees whether this list contains a given entry. * @param anEntry The object that is the desired entry. * @return True if the list contains anEntry, or false if not. */ public boolean contains(T anEntry); /** Gets the length of this list. * @return The integer number of entries currently in the list. */ public int getLength(); /** Sees whether this list is empty. * @return True if the list is empty, or false if not. */ public boolean isEmpty(); /** Retrieves all entries that are in this list in the order in which they occur in the list. @return A newly allocated array of all the entries in the list. */ public T[] toArray(); } // end ListInterface
import java.io.*; import java.util.*; /** * Primes is a program that will compute prime numbers using the sieve of Eratosthenes. * * @author Charles Hoot * @version 4.0 */ public class Primes { public static void main(String args[]) { int max; System.out.println("Please enter the maximum value to test for primality"); max = getInt(" It should be an integer value greater than or equal to 2."); // COMPLETE THE MAIN } /** * getComposites - Remove the composite values from possibles list and * put them in the composites list. * * @param candidates A list of integers holding the possible values. * @param composites A list of integers holding the composite values. * @param prime An Integer that is prime. */ public static void getComposites(ListInterface candidates, ListInterface composites, Integer prime) { // COMPLETE THIS METHOD } /** * Get an integer value. * * @return An integer. */ private static int getInt(String rangePrompt) { Scanner input; int result = 10; //Default value is 10 try { input = new Scanner(System.in); System.out.println(rangePrompt); result = input.nextInt(); } catch(NumberFormatException e) { System.out.println("Could not convert input to an integer"); System.out.println(e.getMessage()); System.out.println("Will use 10 as the default value"); } catch(Exception e) { System.out.println("There was an error with System.in"); System.out.println(e.getMessage()); System.out.println("Will use 10 as the default value"); } return result; } }
import java.io.*; import java.util.*; /** * CountingGame is a program that will simulate a children's counting game used to select * someone. * * @author Charles Hoot * @version 4.0 */ public class CountingGame { public static void main(String args[]) { ListInterface players = null; ListInterface rhyme = null; int max; int position = 1; // always start with the first player System.out.println("Please enter the number of players."); max = getInt(" It should be an integer value greater than or equal to 2."); System.out.println("Constructing list of players"); // ADD CODE HERE TO CREATE THE LIST OF PLAYERS System.out.println("The players list is " + players); rhyme = getRhyme(); // ADD CODE HERE TO PLAY THE GAME System.out.println("The winner is " + players.getEntry(1)); } /** * Do the rhyme with the players in the list and remove the selected * player. * * @param players A list holding the players. * @param rhyme A list holding the words of the rhyme. * @param startAt A position to start the rhyme at. * * @return The position of the player eliminated. */ public static int doRhyme(ListInterface players, ListInterface rhyme, int startAt) { // COMPLETE THIS METHOD return -1; } /** * Get an integer value. * * @return An integer. */ private static int getInt(String rangePrompt) { Scanner input; int result = 10; //Default value is 10 try { input = new Scanner(System.in); System.out.println(rangePrompt); result = input.nextInt(); } catch(NumberFormatException e) { System.out.println("Could not convert input to an integer"); System.out.println(e.getMessage()); System.out.println("Will use 10 as the default value"); } catch(Exception e) { System.out.println("There was an error with System.in"); System.out.println(e.getMessage()); System.out.println("Will use 10 as the default value"); } return result; } /** * getRhyme - Get the rhyme. * * @return A list of words that is the rhyme. */ private static ListInterface getRhyme() { Scanner input; String inString = ""; ListInterface rhyme = new AList(); try { input = new Scanner( System.in ); System.out.println("Please enter a rhyme"); inString = input.nextLine().trim(); Scanner rhymeWords = new Scanner(inString); while(rhymeWords.hasNext()) { rhyme.add(rhymeWords.next()); } } catch(Exception e) { System.out.println("There was an error with System.in"); System.out.println(e.getMessage()); System.out.println("Will use a rhyme of size one"); } // Make sure there is at least one word in the rhyme if(rhyme.getLength() < 1) rhyme.add("Default"); return (ListInterface)rhyme; } }
import java.util.Arrays; /** A class that implements a list of objects by using an array. * Entries in a list have positions that begin with. * Duplicate entries are allowed. * The size of the array doubles until it exceeds the maximum allowed * capacity, where upon an exception is thrown. * * This code is from Chapter 13 of * Data Structures and Abstractions with Java 4/e * @author Frank M. Carrano * * The toString method is overwritten to give a nice display of the items in * the list in this format { <1> <2> <3> <4> } * Modification by Charles Hoot */ class AList implements ListInterface { private T[] list; //Array of list entries; ignore list[0] private int numberOfEntries; // current number of entries in list private boolean initialized = false; private static final int DEFAULT_CAPACITY = 25; private static final int MAX_CAPACITY = 10000; public AList() { this(DEFAULT_CAPACITY); // Call next constructor } // end default constructor public AList(int initialCapacity) { // Is initialCapacity too small? if (initialCapacity < DEFAULT_CAPACITY) initialCapacity = DEFAULT_CAPACITY; else // Is initialCapacity too big? checkCapacity(initialCapacity); // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] tempList = (T[]) new Object[initialCapacity + 1]; list = tempList; numberOfEntries = 0; initialized = true; } // end constructor /** Throws an exception if this object is not initialized. * */ private void checkInitialization(){ if (!initialized) throw new SecurityException("ArrayBag object is not initialized " + "properly."); } // end checkInitialization /** Throws an exception if the desired capacity exceeds the maximum. * */ private void checkCapacity(int desiredCapacity){ if(desiredCapacity > MAX_CAPACITY) throw new IllegalStateException("Attempt to create a bag " + "whose capacity exceeds " + "allowed maximum."); } // end checkCapacity public void add(T newEntry) { checkInitialization(); list[numberOfEntries+1] = newEntry; numberOfEntries++; ensureCapacity(); } // end add // Precondition: The array list has room for another entry public void add(int newPosition, T newEntry) { checkInitialization(); if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) { if (newPosition <= numberOfEntries) { makeRoom(newPosition); } list[newPosition] = newEntry; numberOfEntries++; ensureCapacity(); // Ensure enough room for next add } else { throw new IndexOutOfBoundsException("Illegal position given to add operation."); } } // end add public T remove(int givenPosition) { checkInitialization(); if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); T result = list[givenPosition ]; // Get entry to be removed // Move subsequent entries toward entry to be removed, // unless it is last in list if (givenPosition < numberOfEntries) { removeGap(givenPosition); } numberOfEntries--; return result; // Return reference to removed entry } else throw new IndexOutOfBoundsException("Illegal position given to remove operation."); } // end remove public void clear() { numberOfEntries = 0; } // end clear public T replace(int givenPosition, T newEntry) { checkInitialization(); if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); T originalEntry = list[givenPosition]; list[givenPosition] = newEntry; return originalEntry; } else throw new IndexOutOfBoundsException("Illegal position given to replace operation."); } // end replace public T getEntry(int givenPosition) { checkInitialization(); if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); return list[givenPosition]; } else throw new IndexOutOfBoundsException("Illegal position give to getEntry operation."); } // end getEntry public boolean contains(T anEntry) { checkInitialization(); boolean found = false; int index = 1; while (!found && (index <= numberOfEntries)) { if (anEntry.equals(list[index])) { found = true; } index++; } // end for return found; } // end contains public int getLength() { return numberOfEntries; } // end getLength public boolean isEmpty() { return numberOfEntries == 0; } // end isEmpty public T[] toArray() { checkInitialization(); // the cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] result = (T[]) new Object[numberOfEntries]; for (int index = 0; index < numberOfEntries; index++) { result[index] = list[index+1]; } // end for return result; } // end toArray // Doubles the size of the array list if it is full. private void ensureCapacity() { int capacity = list.length - 1; if (numberOfEntries >= capacity) { int newCapacity = 2 * capacity; checkCapacity(newCapacity); // Is capacity too big? list = Arrays.copyOf(list, newCapacity + 1); } } // end ensureCapacity /** Makes room for a new entry at newPosition. * Precondition: 1 <= newPosition <= numberOfEntries+1; * numberOfEntries is list's length before addition. * checkInitialization has been called. */ private void makeRoom(int newPosition) { assert (newPosition >= 1) && (newPosition <= numberOfEntries + 1); int newIndex = newPosition; int lastIndex = numberOfEntries; // Move each entry to next higher index, starting at end of // array and continuing until the entry at newIndex is moved for (int index = lastIndex; index >= newIndex; index--) { list[index + 1] = list[index]; } } // end makeRoom /** Shifts entries that are beyond the entry to be removed * to the next lower position. * Precondition: 1 <= givenPosition < numberOfEntries; * numberOfEntries is list's length before removal. * checkInitialization has been called. */ private void removeGap(int givenPosition) { assert (givenPosition >= 1) && (givenPosition < numberOfEntries); int removedIndex = givenPosition; int lastIndex = numberOfEntries; for (int index = removedIndex; index < lastIndex; index++) list[index] = list[index + 1]; } // end removeGap /** Build a string representation of the list * * @return A string showing the state of the list. */ public String toString() { String result = "{ "; for (int i = 0; i < numberOfEntries; i++) { result = result + "<" + list[i+1] + "> "; } result = result + "}"; return result; } }
Lab 12 List Client Goal In this lab you will complete two applications that use the Abstract Data Type (ADT) list. Resources • • Chapter 12: Lists docs.oracle.com/javase/8/docs/api/ —API documentation for the Java List interface In javadoc directory • ListInterface.html—Interface documentation for the interface ListInterface Java Files • • • • AList.java CountingGame.java ListInterface.java Primes.java Introduction The ADT list is one of the basic tools for use in developing software applications. It is an ordered collection of objects that can be accessed based on their position. Before continuing the lab you should review the material in Chapter 12. In particular, review the documentation of the interface ListInterface.java. While not all of the methods will be used in our applications, most of them will. The first application you will complete implements a child's selection game. In the standard version of this game, a group of children gather in a circle and begin a rhyme. (One such rhyme goes “Engine, engine number nine, going down Chicago line. If the train should jump the track, will you get your money back? My mother told me to pick the very best one and you are not it.”) Each word in the rhyme is chanted in turn by one person in the circle. The last person is out of the game and the rhyme is restarted from the next person. Eventually, one person is left and he or she is the lucky individual that has been selected. This application will read the number of players in the game and the rhyme from the keyboard. The final output will be the number of the selected person. You will use two lists in this application. The first will be a list of numbers representing the players in the game. The second will be a list of words in the rhyme. The second application is one that computes prime numbers using the Sieve of Eratosthenes. Pre-Lab Visualization Counting Game Suppose we have six players named 1, 2, 3, 4, 5, and 6. Further, suppose the rhyme has three words A, B, C. There will be five rounds played with one player eliminated in each round. In the following table, fill in the players next to the part of the rhyme they say in each round. Cross out the players as they are eliminated. The first round has been completed for you. Lab Manual for Data Structures and Abstractions with Java ™ 165 Round 1 1 2 3 A B C Eliminated Players: Round 2 1 2 3 4 5 Round 3 Round 4 Round 5 6 Suppose we have five players named 1, 2, 3, 4, and 5. And the rhyme has six words A, B, C, D, E, F. There will be four rounds played. In the following table, fill in the players next to the part of the rhyme they say in each round. Cross out the players as they are eliminated. Round 1 Round 2 Round 3 Round 4 A B C D E F Eliminated Players: 1 2 3 4 5 Primes Suppose you are interested in finding the primes between 2 and 15 inclusive. The list of candidates is: Candidates: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The algorithm proceeds in rounds. In each round a single prime is discovered and numbers that have that prime as a factor are eliminated. Round 1: Cross the first value off of the Candidates list and add it to the Primes list. Cross out any candidate that is divisible by the prime you have just discovered and add it to the composites list. Primes: Composites: 166 Lab 12 List Client Round 2: To make the operation of the algorithm clearer, copy the contents of the lists as they appear at the end of the previous round. Cross the first value off of the Candidates list and add it to the Primes list. Cross out any candidate that is divisible by the prime you have just discovered and add it to the composites list. Candidates: Primes: Composites: Round 3: Again, copy the contents of the lists as they appear at the end of the previous round. Cross the first value off of the Candidates list and add it to the Primes list. Cross out any candidate that is divisible by the prime you have just discovered and add it to the composites list. Candidates: Primes: Composites: You can complete the other rounds if you wish, but most of the interesting work has been completed. Finding Composites The heart of this algorithm is removing the composite values from the candidates list. Let's examine this process more closely. In the first round, after removing the 2, the list of candidates is Candidates: 3 4 5 6 7 8 9 10 11 12 13 14 15 How many values are in the list? Lab Manual for Data Structures and Abstractions with Java ™ 167 The first value to be examined is the 3. What is its index? The second value to be examined is the 4. What is its index? Since 4 is divisible by 2, we need to remove it from the list of candidates. What is the new list of candidates after the 4 is removed? Candidates: The third value to be examined is the 5. What is its index? The fourth value to be examined is the 6. What is its index? Since 6 is divisible by 2, we need to remove it from the list of candidates. What is the new list of candidates after the 6 is removed? Candidates: The fifth value to be examined is the 7. What is its index? Can you simply loop over the indices from 1 to 13 to examine all the candidates? 168 Lab 12 List Client Develop an algorithm to examine all the values in the candidates list and remove them if they are divisible by the given prime. Directed Lab Work Counting Game Pieces of the CountingGame class already exist and are in CountingGame.java. Take a look at that code now if you have not done so already. Also before you start, make sure you are familiar with the methods available to you in the AList class (check ListInterface.html). Step 1. Compile the classes CountingGame and AList. Run the main method in CountingGame. Checkpoint: If all has gone well, the program will run and accept input. It will then generate a null pointer exception. The goal now is to create the list of players. Step 2. Create a new Alist and assign it to players. Step 3. Using a loop, add new objects of type Integer to the players list. Checkpoint: Compile and run the program. Enter 3 for the number of players. The program should print out { <1> <2> <3> } for the players list. The next goal is to do one round of the game. It will be encapsulated in the method doRhyme(). Step 4. Complete the doRhyme() method. Use the following algorithm. For each word in the rhyme Print the word in the rhyme and the player that says it. Print the name of the player to be removed. Remove that player from the list. Return the index of the player that will start the next round. Step 5. Call doRhyme(players, rhyme, position) in main after the call to getRhyme(). Step 6. Print out the new player list. Lab Manual for Data Structures and Abstractions with Java ™ 169 Checkpoint: Compile and run the program. Enter 6 for the number of players. Enter A B C for the rhyme. It should print out something similar to Player 1: A Player 2: B Player 3: C Removing player 3 The players list is { <1> <2> <4> <5> <6> } Enter 5 for the number of players. Enter A B C D E F for the rhyme. Compare your result with your answers in the pre-lab. Reconcile any differences. The final goal is to do multiple rounds. Step 7. Wrap the lines of code from the previous two steps in a while loop that continues as long as there is more than one player left. Final checkpoint: Compile and run the program. Enter 6 for the number of players. Enter A B C for the rhyme. The players should be removed in the order 3, 6, 4, 2, 5. The winner should be player 1. Enter 5 for the number of players. Enter A B C D E F for the rhyme. Compare your result with your answers in the pre-lab exercises. Reconcile any differences. Primes The skeleton of the Primes class already exists and is in Primes.java. Step 1. Look at the skeleton in Primes.java. Compile Primes. Run the main method in Primes. Checkpoint: If all has gone well, the program will run and accept input. It will then end. The goal now is to create the list of candidates. Step 2. In main declare and create the candidates list. Add in the values. Step 3. Print out the candidates list. Checkpoint: Compile and run the program. Enter 7 for the maximum value. You should see the list { <2> <3> <4> <5> <6> <7> }. The next goal is to do a single round finding a prime in the candidates list. Step 4. In main declare and create the primes and composites lists. Step 5. Remove the first value from the primes list and remember it in a variable. Step 6. Print out the prime that was discovered. Step 7. Add it to the primes list. Step 8. Print out all three lists. Checkpoint: Compile and run the program. Enter 7 for the maximum value. The value 2 should be removed from the candidates list and added to the primes. Now all values that are divisible by the prime should be removed from the candidates list and added to the composites list. Next, this procedure will be encapsulated in the method getComposites(). Step 9. Refer to the pre-lab exercises and complete the getComposites() method. To determine if one integer value is divisible by another, you can use the modulus operator (% in Java). Step 10. 170 Between the code from steps 7 and 8, call getComposites(). Lab 12 List Client Checkpoint: Compile and run the program. Enter 15 for the maximum value. Compare the results with the pre-lab exercises. Reconcile any differences. Just as in the counting game, a loop will be used to do the rounds. Step 11. Wrap the code from steps 5 through 8 in a while loop that continues as long as the candidates list is not empty. Final checkpoint: Compile and run the program. Enter 15 for the maximum value. Compare the results with the pre-lab exercises. Reconcile any differences. Run the program with 100 as the maximum value. Carefully verify your results. Post-Lab Follow-Ups 1. Modify the counting game program to compute the winning player for different numbers of players from 2 up to an input value. Figure out which player wins for a rhyme of length three for games with 2 to 20 players and record the results in a table. Can you discover a relation between the size of the player list, the length of the rhyme, and the winning player? 2. After a certain point in our iteration, all the remaining values in the candidates list are prime. Modify the program to just copy values directly when that point has been reached. 3. Write a program that will get a list of words and then remove any duplicates. 4. Write a program that will get two lists of words and will create a third list that consists of any words in common between the two input lists. 5. Write a program that will read in a list of words and will create and display two lists. The first list will be the words in odd positions of the original list. The second list will be all the remaining words. 6. Write a program that will get a list of integer values each of which is greater than one and determines if all the posible pairs of values from the list are relatively prime. Two values are relatively prime if they share no prime factors. For example, the values 10 and 77 are relatively prime, but 10 and 55 are not since the share 5 as a factor. If we look at the list {6, 25, 77} each of the pairs (6, 25), (6, 77), and (25,77) are relatively prime and it passes our test. On the other hand the list {6, 25, 14} will fail the test. While the pairs (6, 25) and (25, 14) are relatively prime, the pair (6,14) is not. Lab Manual for Data Structures and Abstractions with Java ™ 171 172 Lab 12 List Client

Tutor Answer

JoeMart30814886
School: UCLA

for the primes

Lab 12

List Client

Goal
In this lab you will complete two applications that use the Abstract Data Type (ADT) list.

Resources



Chapter 12: Lists
docs.oracle.com/javase/8/docs/api/ —API documentation for the Java List interface

In javadoc directory
• ListInterface.html—Interface documentation for the interface ListInterface

Java Files





AList.java
CountingGame.java
ListInterface.java
Primes.java

Introduction
The ADT list is one of the basic tools for use in developing software applications. It is an ordered collection of
objects that can be accessed based on their position. Before continuing the lab you should review the material
in Chapter 12. In particular, review the documentation of the interface ListInterface.java. While not all
of the methods will be used in our applications, most of them will.

The first application you will complete implements a child's selection game. In the standard version of this
game, a group of children gather in a circle and begin a rhyme. (One such rhyme goes “Engine, engine number
nine, going down Chicago line. If the train should jump the track, will you get your money back? My mother
told me to pick the very best one and you are not it.”) Each word in the rhyme is chanted in turn by one person
in the circle. The last person is out of the game and the rhyme is restarted from the next person. Eventually,
one person is left and he or she is the lucky individual that has been selected. This application will read the
number of players in the game and the rhyme from the keyboard. The final output will be the number of the
selected person. You will use two lists in this application. The first will be a list of numbers representing the
players in the game. The second will be a list of words in the rhyme.
The second application is one that computes prime numbers using the Sieve of Eratosthenes.

Pre-Lab Visualization
Counting Game
Suppose we have six players named 1, 2, 3, 4, 5, and 6. Further, suppose the rhyme has three words A, B, C.
There will be five rounds played with one player eliminated in each round. In the following table, fill in the
players next to the part of the rhyme they say in each round. Cross out the players as they are eliminated. The
first round has been completed for you.

Lab Manual for Data Structures and Abstractions with Java ™

165

Round 1
1
2
3

A
B
C

Eliminated Players:

Round 2

1

2

3

4

5

Round 3

Round 4

Round 5

6

Suppose we have five players named 1, 2, 3, 4, and 5. And the rhyme has six words A, B, C, D, E, F. There
will be four rounds played. In the following table, fill in the players next to the part of ...

flag Report DMCA
Review

Anonymous
Totally impressed with results!! :-)

Similar Questions
Hot Questions
Related Tags

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors