AP CSA Unit 7+8 FRQ

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

A crossword puzzle grid is a two-dimensional rectangular array of black and white squares. Some of the white squares are labeled with a positive number according to the crossword labeling rule. The crossword labeling rule identifies squares to be labeled with a positive number as follows. A square is labeled with a positive number if and only if the square is white and the square does not have a white square immediately above it, or it does not have a white square immediately to its left, or both. The squares identified by these criteria are labeled with consecutive numbers in row-major order, starting at 1. The following diagram shows a crossword puzzle grid and the labeling of the squares according to the crossword labeling rule. This question uses two classes, a Square class that represents an individual square in the puzzle and a Crossword class that represents a crossword puzzle grid. A partial declaration of the Square class is shown below. A partial declaration of the Crossword class is shown below. You will implement one method and the constructor in the Crossword class. a) Write the Crossword method toBeLabeled. The method returns true if the square indexed by row r, column c in a crossword puzzle grid should be labeled with a positive number according to the crossword labeling rule; otherwise it returns false. The parameter blackSquares indicates which squares in the crossword puzzle grid are black. Complete method toBeLabeled below. b) Write the Crossword constructor. The constructor should initialize the crossword puzzle grid to have the same dimensions as the parameter blackSquares. Each element of the puzzle grid should be initialized with a reference to a Square object with the appropriate color and number. The number is positive if the square is labeled and 0 if the square is not labeled. Assume that toBeLabeled works as specified, regardless of what you wrote in part (a). You must use toBeLabeled appropriately to receive full credit. Complete the Crossword constructor below.

a) private boolean toBeLabeled(int r, int c, boolean[][] blackSquares) { if(blackSquares[r][c]) return false; if(r == 0 || blackSquares[r - 1][c]) return true; if(c == 0 || blackSquares[r][c - 1]) return true; return false; } b) public Crossword(boolean[][] blackSquares) { puzzle = new Square[blackSquares.length][blackSquares[0].length]; int num = 1; for(int r = 0; r < puzzle.length; r++) { for(int c = 0; c < puzzle[0].length; c++) { if(toBeLabeled(r, c, blackSquares)) { puzzle[r][c] = new Square(false, num); num++; } else puzzle[r][c] = new Square(blackSquares[r][c], 0); } } }

This question involves the scheduling of car repairs. The classes used in the question are used to record information about car repairs. The methods shown and the methods to be written involve the mechanic performing a repair and the bay in which the repair takes place. A bay is an area of a repair shop in which a car is parked while a mechanic performs a repair. Mechanics and bays are identified by sequential integer identification numbers that start with 0. An individual car repair is represented by the following CarRepair class. public class CarRepair{ private int mechanicNum; private int bayNum; public CarRepair(int m, int b){ mechanicNum = m; bayNum = b;} public int getMechanicNum() { return mechanicNum; } public int getBayNum() { return bayNum; } // There may be other instance variables, constructors, and methods not shown.} The following RepairSchedule class represents the use of bays by mechanics repairing cars. You will write two methods of the RepairSchedule class. public class RepairSchedule{ /** Each element represents a repair by an individual mechanic in a bay. */ private ArrayList<CarRepair> schedule; /** Number of mechanics available in this schedule. */ private int numberOfMechanics; /** Constructs a RepairSchedule object. * Precondition: n >= 0 */ public RepairSchedule(int n){ schedule = new ArrayList<CarRepair>(); numberOfMechanics = n;} /** Attempts to schedule a repair by a given mechanic in a given bay as described in part (a). * Precondition: 0 <= m < numberOfMechanics and b >= 0 */ public boolean addRepair(int m, int b){ /* to be implemented in part (a) */} /** Returns an ArrayList containing the mechanic identifiers of all available mechanics, * as described in part (b). */ public ArrayList<Integer> availableMechanics(){ /* to be implemented in part (b) */} /** Removes an element from schedule when a repair is complete. */ public void carOut(int b){ /* implementation not shown */}} (a) Write the addRepair method. The method attempts to schedule a repair by the mechanic with identifier m in the bay with identifier b. The repair can be scheduled if mechanic m and bay b are both available. A mechanic is available if the given mechanic number does not appear in an element of schedule and a bay is available if the given bay number does not appear in an element of schedule. If the mechanic and bay are both available, the addRepair method adds the repair to schedule and returns true. If either the mechanic or the bay are not available, the addRepair method returns false. The following sequence of statements provides examples of the behavior of the addRepair method. The statement RepairSchedule r = new RepairSchedule(6); constructs a new RepairSchedule object r. No repairs have been scheduled. Mechanics are numbered 0 through 5. The call r.addRepair(3, 4) returns true because neither mechanic 3 nor bay 4 are present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(0, 1) returns true because neither mechanic 0 nor bay 1 are present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(0, 2) returns false because mechanic 0 is present in schedule. The contents of schedule after the call are as follows. The call r.addRepair(2, 4) returns false because bay 4 is present in schedule. The contents of schedule after the call are as follows. The call r.carOut(4) removes the repair in bay 4 from schedule. The carOut method is shown here to illustrate that bays and mechanics become available when car repairs are complete. You do not need to write or call this method. The contents of schedule after the call are as follows. The call r.addRepair(1, 4) returns true because neither mechanic 1 nor bay 4 are present in schedule. The contents of schedule after the call are as follows. Complete the addRepair method. /** Attempts to schedule a repair by a given mechanic in a given bay as described in part (a). * Precondition: 0 <= m < numberOfMechanics and b >= 0 */ public boolean addRepair(int m, int b) (b) Write the availableMechanics method, which returns an ArrayList containing the mechanic numbers of all available mechanics. If there is no available mechanic, an empty list is returned. A mechanic is available if the mechanic's identifier does not appear in schedule. Suppose schedule has the following contents. For these contents of schedule, availableMechanic should return an ArrayList containing the values 2, 3, 4, and 5 (in any order). Complete the availableMechanics method. Assume that addRepair works as specified, regardless of what you wrote in part (a). /** Returns an ArrayList containing the mechanic identifiers of all available mechanics, * as described in part (b). */ public ArrayList<Integer> availableMechanics()

a) public boolean addRepair(int m, int b) { for (CarRepiar c : schedule) { if (c.getMechanicNum()==m || c.getBayNum==b) { return false; }} schedule.add(new Carrepair(m,b)); return true; } b) public ArrayList<Integer> availableMechanics() { ArrayList<Integer> availableList = new ArrayList<Integer>(); for (int i=0; i<numberofMechanics; i++) { int count=0; for (CarRepair c: schedule) { if (c.getMechanicNum()=i) { count++; }} if (count==0) { availableList.add(i); }} retuurn availableList; }

A two-dimensional array of temperatures is represented in the above class. a) Write method computeTemp, which computes and returns the new temperature for a given element of temps according to the following rules. 1. If the element is in the border of the array (in the first row or last row or first column or last column), the new temperature is the same as the old temperature. 2. Otherwise, the new temperature is the average (arithmetic mean) of the temperatures of the four adjacent values in the table (located above, below, to the left, and to the right of the element). If temps is the table shown below, temps.length is 5 and temps[0].length is 6. The following table shows the results of several calls to computeTemp. (b) Write method updateAllTemps, which computes the new temperature for every element of temps.The new values should be based on the original values, so it will be necessary to create another two-dimensional array in which to store the new values. Once all the computations are complete, the new values should replace the corresponding positions of temps. Method updateAllTemps also determines whether every new temperature is within tolerance of the corresponding old temperature (i.e., the absolute value of the difference between the old temperature and the new temperature is less than or equal to tolerance). If so, it returns true; otherwise, it returns false. If temps contains the values shown in the first table below, then the call updateAllTemps(0.01)should update temps as shown in the second table. In the example shown, the call updateAllTemps (0.01) should return false because there are several new temperatures that are not within the given tolerance of the corresponding old temperature. For example, the updated value in temps[2][3] is 37.5, the original value in temps[2][3] was 40.0, and the absolute value of (37.5 - 40.0) is greater than the value of tolerance (0.01). Assume that computeTemp works as specified, regardless of what you wrote in part (a).

a) private double computeTemp (int row, int col) { if (row == 0 || row == temps.length - 1 || col == 0 || col == temps[0].length - 1) return temps[row][col]; double sum = temps[row-1][col] + temps[row+1][col] + temps[row][col-1] + temps[row][col+1]; return sum/4.0; } b) public boolean updateAllTemps (double tolerance) { double[][]newTemps = new double[temps.length][temps[0].length]; boolean within = true; for (int r = 0; r < temps.length; r++) { for (int c = 0; c < temps[0].length; c++) { newTemps[r][c] = computeTemp(r,c); if (Math.abs(newTemps[r][c] - temps[r][c]) > tolerance) within = false; } } temps = newTemps; return within; }

A game uses square tiles that have numbers on their sides. Each tile is labeled with a number on each of its four sides and may be rotated clockwise, as illustrated below. The tiles are represented by the NumberTile class, as given below. Tiles are placed on a game board so that the adjoining sides of adjacent tiles have the same number. The following figure illustrates an arrangement of tiles and shows a new tile that is to be placed on the game board. In its original orientation, the new tile can be inserted between the tiles at positions 2 and 3 or between the tiles at positions 3 and 4. If the new tile is rotated once, it can be inserted before the tile at position 0 (the first tile) or after the tile at position 4 (the last tile). Assume that the new tile, in its original orientation, is inserted between the tiles at positions 2 and 3. As a result of the insertion, the tiles at positions 3 and 4 are moved one location to the right, and the new tile is inserted at position 3, as shown below. A partial definition of the TileGame class is given below. a) Write the TileGame method getIndexForFit that determines where a given tile, in its current orientation, fits on the game board. A tile can be inserted at either end of a game board or between two existing tiles if the side(s) of the new tile match the adjacent side(s) of the tile(s) currently on the game board. If there are no tiles on the game board, the position for the insert is 0. The method returns the position that the new tile will occupy on the game board after it has been inserted. If there are multiple possible positions for the tile, the method will return any one of them. If the given tile does not fit anywhere on the game board, the method returns -1. For example, the following diagram shows a game board and two potential tiles to be placed. The call getIndexForFit(tile1) can return either 3 or 4 because tile1 can be inserted between the tiles at positions 2 and 3, or between the tiles at positions 3 and 4. The call getIndexForFit(tile2) returns -1 because tile2, in its current orientation, does not fit anywhere on the game board. Complete method getIndexForFit below. b) Write the TileGame method insertTile that attempts to insert the given tile on the game board. The method returns true if the tile is inserted successfully and false only if the tile cannot be placed on the board in any orientation. Assume that getIndexForFit works as specified, regardless of what you wrote in part (a). Complete method insertTile below.

a) private int getIndexForFir (NumberTitle tile) { if(board.get(0).getleft() == tle.getRight()) return 0; if (board.size != 1) { for (int c = 0; c < (board.size()-1); c++) { if(board.get(c).getRight)_ == tile.getLeft() && board.get(c+1).getLeft == tile.getRight()) return c+1;}} if (board.get(board.size()-1).getRight() == tile.getLeft()) return board.size(); return -1;} b) public boolean insertTile (Numbertile tile) { for (int c = 0; c < 4; c++) { if (getIndexForFit(tile) != -1) { board.add(getIndexForFit(tile), tile); return true; } else tile.rotate(); } return false; }

Many encoded strings contain delimiters. A delimiter is a non-empty string that acts as a boundary between different parts of a larger string. The delimiters involved in this question occur in pairs that must be balanced, with each pair having an open delimiter and a close delimiter. There will be only one type of delimiter for each string. The following are examples of delimiters. Example 1Expressions in mathematics use open parentheses "(" and close parentheses ")" as delimiters. For each open parenthesis, there must be a matching close parenthesis. (x + y) * 5 is a valid mathematical expression. (x + (y) is NOT a valid mathematical expression because there are more open delimiters than close delimiters. Example 2HTML uses <B> and </B> as delimiters. For each open delimiter <B>, there must be a matching close delimiter </B>. <B> Make this text bold </B> is valid HTML. <B> Make this text bold </UB> is NOT valid HTML because there is one open delimiter and no matching close delimiter. In this question, you will write two methods in the following Delimiters class. public class Delimiters{ /** The open and close delimiters. */ private String openDel; private String closeDel; /** Constructs a Delimiters object where open is the open delimiter and close is the * close delimiter. * Precondition: open and close are non-empty strings. */ public Delimiters(String open, String close){ openDel = open; closeDel = close;} /** Returns an ArrayList of delimiters from the array tokens, as described in part (a). */ public ArrayList<String> getDelimitersList(String[] tokens) { /* to be implemented in part (a) */ } /** Returns true if the delimiters are balanced and false otherwise, as described in part (b). * Precondition: delimiters contains only valid open and close delimiters. */ public boolean isBalanced(ArrayList<String> delimiters) { /* to be implemented in part (b) */ } // There may be instance variables, constructors, and methods that are not shown.} (a) A string containing text and possibly delimiters has been split into tokens and stored in String[] tokens. Each token is either an open delimiter, a close delimiter, or a substring that is not a delimiter. You will write the method getDelimitersList, which returns an ArrayList containing all the open and close delimiters found in tokens in their original order. The following examples show the contents of an ArrayList returned by getDelimitersList for different open and close delimiters and different tokens arrays. Example 1 Example 2 Class information for this question public class Delimiters private String openDel private String closeDel public Delimiters(String open, String close) public ArrayList<String> getDelimitersList(String[] tokens) public boolean isBalanced(ArrayList<String> delimiters) Complete method getDelimitersList below. /** Returns an ArrayList of delimiters from the array tokens, as described in part (a). */ public ArrayList<String> getDelimitersList(String[] tokens) (b) Write the method isBalanced, which returns true when the delimiters are balanced and returns false otherwise. The delimiters are balanced when both of the following conditions are satisfied; otherwise, they are not balanced. When traversing the ArrayList from the first element to the last element, there is no point at which there are more close delimiters than open delimiters at or before that point. The total number of open delimiters is equal to the total number of close delimiters. Consider a Delimiters object for which openDel is "<sup>" and closeDel is "</sup>". The examples below show different ArrayList objects that could be returned by calls to getDelimitersList and the value that would be returned by a call to isBalanced. Example 1The following example shows an ArrayList for which isBalanced returns true. As tokens are examined from first to last, the number of open delimiters is always greater than or equal to the number of close delimiters. After examining all tokens, there are an equal number of open and close delimiters. Example 2The following example shows an ArrayList for which isBalanced returns false. Example 3The following example shows an ArrayList for which isBalanced returns false. Example 4The following example shows an ArrayList for which isBalanced returns false because the second condition is violated. After examining all tokens, there are not an equal number of open and close delimiters. Class information for this question public class Delimiters private String openDel private String closeDel public Delimiters(String open, String close) public ArrayList<String> getDelimitersList(String[] tokens) public boolean isBalanced(ArrayList<String> delimiters) Complete method isBalanced below. /** Returns true if the delimiters are balanced and false otherwise, as described in part (b). * Precondition: delimiters contains only valid open and close delimiters. */ public boolean isBalanced(ArrayList<String> delimiters)

a) public ArrayList<String> getDelimitersList(String[] tokens) { ArrayList<String> d=new ArrayList<String>(); for (String str : tokens) { if (str.equals(openDel) || str.equals(closeDel)) { d.add(str);}} return d; } b) public boolean isBalanced(ArrayList<String> delimiters) { int openCount=0; int closeCount=0; for (String str : delimiters) { if (str.equals(openDel)) { openCount++;} else { closeCount++;} if(closeCount>openCount) { return false; }} if (openCount==closeCount) { return true; } else { return false;}}

This question involves generating a list of possible nicknames from a person's name. For the purposes of this question, a person's name contains a first (given) name and a last (family) name. You may assume that all punctuation has been removed so that names contain only letters and that all letters are in uppercase. A partial declaration of the NicknameGenerator class is shown below. You will write two methods of the NicknameGenerator class. public class NicknameGenerator{ /** The person's first name in all uppercase letters, initialized * by the constructor. */ private String firstName; /** The person's last name in all uppercase letters, initialized * by the constructor. */ private String lastName; // Constructor not shown /** Returns the number of vowels in lastName. */ private int numVowels() { /* implementation not shown */ } /** Returns the index of the first vowel in lastName. * Returns -1 if there are no vowels in lastName. */ private int indexOfFirstVowel() { /* implementation not shown */ } /** Returns a list of shortened last names, as described * in part (a). */ public ArrayList<String> shortLastNames() { /* to be implemented in part (a) */ } /** Returns a list of nicknames, as described in part (b). */ public ArrayList<String> nicknames() { /* to be implemented in part (b) */ }} Write the method shortLastNames, which returns a list of the shortened forms of a last name, according to the rules below. Each shortened last name must appear exactly once in the list. The following rules are used to produce the list of shortened last names. If the last name contains fewer than two vowels, the list contains the complete last name as its only element. If the last name contains two or more vowels, the first shortened last name in the list contains all characters from the original last name up to and including the first vowel. Each subsequent shortened last name is produced by adding one additional character from the original last name. The list ends with the complete last name. The NicknameGenerator class provides two helper methods. The method numVowels returns the number of vowels in lastName. The method indexOfFirstVowel returns the index of the first vowel in lastName or -1 if there are no vowels in lastName. In the table below, the vowels in each last name are underlined. Last nameList of shortened last namesNG["NG"]SMITH["SMITH"]LOPES​["LO", "LOP", "LOPE", "LOPES"]ASHE["A", "AS", "ASH", "ASHE"] Complete method shortLastNames. The helper methods numVowels and indexOfFirstVowel have been provided for you. /** Returns a list of shortened last names, as described * in part (a). */ public ArrayList<String> shortLastNames() Write the method nicknames, which returns a list of all possible nicknames. Each nickname must appear exactly once in the list. A nickname is generated with the first letter of the first name, followed by "-", followed by one of the possible shortened forms of the last name. The table below shows several names and the list of nicknames that are generated from the name. NameList of nicknamesCELESTE NG["C-NG"]GLEN SMITH["G-SMITH"]​JUANITA LOPES["J-LO", "J-LOP", "J-LOPE", "J-LOPES"]MARY ASHE["M-A", "M-AS", "M-ASH", "M-ASHE"]​ Assume that shortLastNames works as specified, regardless of what you wrote in part (a). You must use shortLastNames appropriately to receive full credit. Complete method nicknames. /** Returns a list of nicknames, as described in part (b). */ public ArrayList<String> nicknames()

a) public ArrayList<String> shortLastNames() { ArrayList<String> shortNames=new ArrayList<String>(); if (numVowels()<2){ shortNames.add(lastName); } else { for (int i=indexOfFirstVowel()+1; i<=lastName.length(); i++) { shortNames.add(lastName.substring(0,i)); }} return shortNames; } b) public ArrayList<String> nicknames() { ArrayList<String> nnList=new ArrayList<String>(); ArrayList<String> lastNames=shortLastNames(); for (String name:lastNames) { nnList.add(firstName.substring(0,1)+"-"+name);} return nnList; }

This question involves identifying and processing the digits of a non-negative integer. The declaration of the Digits class is shown below. You will write the constructor and one method for the Digits class. (a) Write the constructor for the Digits class. The constructor initializes and fills digitlist with the digits from the non-negative integer num. The elements in digitlist must be Integer objects representing single digits, and appear in the same order as the digits in num. Each of the following examples shows the declaration of a Digits object and the contents of digitist as initialized by the constructor. Complete the Digits constructor below. (b) Write the Digits method isStrictlyIncreasing. The method returns true if the elements of digitlist appear in strictly increasing order; otherwise, it returns false. A list is considered strictly increasing if each element after the first is greater than (but not equal to) the preceding element. The following table shows the results of several calls to isStrictlyIncreasing. Complete method isStrictlyIncreasing below.

a) public Digits(int num){ digitList = new ArrayList<Integer>(); if (num == 0){ digitList.add(new Integer(0));} while (num > 0){ digitList.add(0, new Integer(num % 10)); num /= 10;}} b) public boolean isStrictlyIncreasing(){ for (int i = 0; i < digitList.size()-1; i++){ if (digitList.get(i).intValue() >= digitList.get(i+1).intValue()){ return false;}} return true;}

The LightBoard class models a two-dimensional display of lights, where each light is either on or off, as represented by a Boolean value. You will implement a constructor to initialize the display and a method to evaluate a light. public class LightBoard{ /** The lights on the board, where true represents on and false represents off. */ private boolean[][] lights; /** Constructs a LightBoard object having numRows rows and numCols columns. * Precondition: numRows > 0, numCols > 0 * Postcondition: each light has a 40% probability of being set to on. */ public LightBoard(int numRows, int numCols) { /* to be implemented in part (a) */ } /** Evaluates a light in row index row and column index col and returns a status * as described in part (b). * Precondition: row and col are valid indexes in lights. */ public boolean evaluateLight(int row, int col) { /* to be implemented in part (b) */ } // There may be additional instance variables, constructors, and methods not shown.} (a) Write the constructor for the LightBoard class, which initializes lights so that each light is set to on with a 40% probability. The notation lights[r][c] represents the array element at row r and column c. Complete the LightBoard constructor below. /** Constructs a LightBoard object having numRows rows and numCols columns. * Precondition: numRows > 0, numCols > 0 * Postcondition: each light has a 40% probability of being set to on. */ public LightBoard(int numRows, int numCols) (b) Write the method evaluateLight, which computes and returns the status of a light at a given row and column based on the following rules. If the light is on, return false if the number of lights in its column that are on is even, including the current light. If the light is off, return true if the number of lights in its column that are on is divisible by three. Otherwise, return the light's current status. For example, suppose that LightBoard sim = new LightBoard(7, 5) creates a light board with the initial state shown below, where true represents a light that is on and false represents a light that is off. Lights that are off are shaded. lights Sample calls to evaluateLight are shown below. Call to evaluateLightValueReturnedExplanationsim.evaluateLight(0, 3);falseThe light is on, and the number of lights that are on in its column is even.sim.evaluateLight(6, 0);trueThe light is off, and the number of lights that are on in its column is divisible by 3.sim.evaluateLight(4, 1);falseReturns the light's current status.sim.evaluateLight(5, 4);trueReturns the light's current status. Class information for this question public class LightBoard private boolean[][] lights public LightBoard(int numRows, int numCols) public boolean evaluateLight(int row, int col) Complete the evaluateLight method below. /** Evaluates a light in row index row and column index col and returns a status * as described in part (b). * Precondition: row and col are valid indexes in lights. */ public boolean evaluateLight(int row, int col)

a) public LightBoard(int numRows, int numCols) { lights=new boolean[numRows][numCols]; for (int r=0; r<numRows; r++){for (int c=0; c<numCols; c++){ double rnd=Math.random(); lights[r][c]=rnd<0.4;}}} b) public boolean evaluateLight (int row, int col) { int numOn=0; for (int r=0; r<lights.length; r++) { if (lights[r][col]) { numOn++;} } if (lights[row][col] && numOn%2==0){ return false;} if (!lights[row][col] && numOn%3==0){ return true;} return lights[row][col];}

A student in a school is represented by the following class. The class SeatingChart, shown below, uses a two-dimensional array to represent the seating arrangement of students in a classroom. The seats in the classroom are in a rectangular arrangement of rows and columns. a) Write the constructor for the SeatingChart class. The constructor initializes the seats instance variable to a two-dimensional array with the given number of rows and columns. The students in studentList are copied into the seating chart in the order in which they appear in studentList. The students are assigned to consecutive locations in the array seats, starting at seats[0][0] and filling the array column by column. Empty seats in the seating chart are represented by null. For example, suppose a variable List roster contains references to Student objects in the following order. A SeatingChart object created with the call new SeatingChart(roster, 3, 4) would have seats initialized with the following values. Complete the SeatingChart constructor below. b) Write the removeAbsentStudents method, which removes students who have more than a given number of absences from the seating chart and returns the number of students that were removed. When a student is removed from the seating chart, a null is placed in the entry for that student in the array seats. For example, suppose the variable SeatingChart introCS has been created such that the array seats contains the following entries showing both students and their number of absences. After the call introCS.removeAbsentStudents(4) has executed, the array seats would contain the following values and the method would return the value 3. Complete method removeAbsentStudents below.

a) public SeatingChart(List studentList, int rows, int cols) { seats = new Student[rows][cols]; int sIndex = 0; for(int c = 0; c < seats[0].length; c++) { for(int r = 0; r < seats.length; r++) { if(sIndex < studentList.size()) { seats[r][c] = studentList.get(sIndex); sIndex++; } } } } b) public int removeAbsentStudents(int allowedAbsences) { int removed = 0; for(int r = 0; r < seats.length; r++) { for(int c = 0; c < seats[0].length; c++) { if(seats[r][c] != null && seats[r][c].getAbsenceCount() > allowedAbsences) { seats[r][c] = null; removed++; } } } return removed; }

A telescope scans a rectangular area of the night sky and collects the data into a 1-dimensional array. Each data value scanned is a number representing the amount of light detected by the telescope. The telescope scans back and forth across the sky (alternating between left to right and right to left) in the pattern indicated below by the arrows. The back-and-forth ordering of the values received from the scan is called telescope order. The telescope records the data in telescope order into a 1-dimensional array of double values. This 1-dimensional array of information received from a single scan will be transferred into a 2-dimensional array, which reconstructs the original view of the rectangular area of the sky. This 2-dimensional array is part of the SkyView class, shown below. In this question you will write a constructor and a method for this class. a) Write the constructor for the SkyView class. The constructor initializes the view instance variable to a 2-dimensional array with numRows rows and numCols columns. The information from scanned, which is stored in the telescope order, is copied into view to reconstruct the sky view as originally seen by the telescope. The information in scanned must be rearranged as it is stored into view so that the sky view is oriented properly. For example, suppose scanned contains values, as shown in the following array. Using the scanned array above, a SkyView object created with new SkyView(4, 3, scanned), would have view initialized with the following values. For another example, suppose scanned contains the following values. A SkyView object created with new SkyView(3, 2, scanned), would have view initialized with the following values. Complete the SkyView constructor below. b) Write the SkyView method getAverage, which returns the average of the elements of the section of view with row indexes from startRow through endRow, inclusive, and column indexes from startCol through endCol, inclusive. For example, if nightSky is a SkyView object where view contains the values shown below, the call nightSky.getAverage(1, 2, 0, 1) should return 0.8. (The average is (1.1 + 1.4 + 0.2 + 0.5) / 4, which equals 0.8). The section being averaged is indicated by the dark outline in the table below. Complete method getAverage below.

a) public SkyView(int numRows, int numCols doube[] scanned) { view = new double [numRows][numCols]; int k = 0; for (int r = 0; r < numRows; r++) { if (r % 2 == 0) { for (int c = 0; c < numCols; c++) { view[r][c] = scanned[k]; k++; }} else { for (int c = numCols-1; c >=0; c--) { view[r][c] = scanned[k]; k++; } } } } b) public double getAverage (int startRow, int endRow, int startCol, int endCol) { int width = endCol - startCol + 1; int height = endRow - startRow + 1; int numValues = width + height; int sum = 0; for (int r = startRow; r <= endRow; r++) { for (int c = startCol; c <= endCol; c++) { sum += view[r][c]; } } return sum/numValues; }

This question uses two classes: an Item class that represents an item that has a name and value and an ItemGrid class that manages a two-dimensional array of items. A definition of the Item class is shown below. public class Item{ private String name; private int value; public Item(String itemName, int itemValue){ name = itemName; value = itemValue;} public String getName(){ return name;} public int getValue(){ return value;}} The ItemGrid class below uses the two-dimensional array grid to represent a group of Item objects. public class ItemGrid{ private Item[][] grid; // Constructor not shown /** Returns true if xPos is a valid row index and yPos is a valid * column index and returns false otherwise. */ public boolean isValid(int xPos, int yPos) { /* implementation not shown */ } /** Compares the item in row r and column c to the items to its * left and to its right. Returns the name of the item with * the greatest value, as described in part (a). * Precondition: r and c are valid indices */ public String mostValuableNeighbor(int r, int c) { /* to be implemented in part (a) */ } /** Returns the average value of all the items in grid, * as described in part (b). */ public double findAverage() { /* to be implemented in part (b) */ } } (a) Write the mostValuableNeighbor method, which compares the item in row r and column c to the items to its left and to its right. The method determines which of the three items has the greatest value and returns its name. If more than one of the values have a value that is greatest, then any of their names can be returned. If the item has no item to its left, it is compared only to the item to its right. If the item has no item to its right, it is compared only to the item to its left. The helper method isValid has been provided. The isValid method returns true if xPos is a valid row index and yPos is a valid column index in the two-dimensional array grid, and returns false otherwise. Assume that the ItemGrid object ig has been created such that the two-dimensional array grid contains the following item objects. The following table shows some examples of the behavior of the mostValuableNeighbor method. Method CallReturn ValueExplanationig.mostValuableNeighbor(0, 2)"book"The item at row 0, column 2 ("carrot") is compared with the items to its left and right ("book" and "desk"). Of the three items, "book" has the greatest value (10).ig.mostValuableNeighbor(1, 1)"flag" or "globe"The item at row 1, column 1 ("flag") is compared with the items to its left and right ("egg" and "globe"). Of the three items, both "flag" and "globe" have the greatest value (8), so either can be returned.ig.mostValuableNeighbor(2, 0)"jacket"The item at row 2, column 0 ("island") has no item to its left, so it is only compared with the item to its right ("jacket"). Of the two items, "jacket" has the greater value (19).ig.mostValuableNeighbor(2, 3)"lunch"The item at row 2, column 3 ("lunch") has no item to its right, so it is only compared with the item to its left ("kale"). Of the two items, "lunch" has the greater value (16). Complete the mostValuableNeighbor method below. You must use isValid appropriately to receive full credit. Assume that grid has been initialized with at least three rows and three columns, and contains no null elements. /** Compares the item in row r and column c to the items to its * left and to its right. Returns the name of the item with * the greatest value, as described in part (a). * Precondition: r and c are valid indices */ public String mostValuableNeighbor(int r, int c) (b) Write the findAverage method, which returns the average value of all items in grid. For example, for the ItemGrid object ig shown in part (a), the findAverage method should return 9.5, which is the average value of the twelve items in the 2D array. Complete the findAverage method below. /** Returns the average value of all the items in grid, * as described in part (b). */ public double findAverage()

a) public String mostValuableNeighbor (int r, int c) { int maxVal=grid[r][c].getName(); if (isValid(r,c+1)) { if (grid[r][c-1].getValue()>maxVal) { maxVal=grid[r][c-1].getValue(); maxName = grid[r][c-1].getName(); }} return maxName; } b) public double findAverage() { double sum=0; for (Item[] row: grid) { for (Item element : row) { sum+=element.getValue(); } return sum/(grid.length*grid[0].length); }

A theater contains rows of seats with the same number of seats in each row. Some rows contain tier 1 seats, and the remaining rows contain tier 2 seats. Tier 1 seats are closer to the stage and are more desirable. All seats in a row share the same tier. The Seat class, shown below, represents seats in the theater. The boolean instance variable available is false if a ticket for the seat has been sold (the seat is no longer available). The int instance variable tier indicates whether the seat is a tier 1 or tier 2 seat. public class Seat{ private boolean available; private int tier; public Seat(boolean isAvail, int tierNum){ available = isAvail; tier = tierNum;} public boolean isAvailable() { return available; } public int getTier() { return tier; } public void setAvailability(boolean isAvail) { available = isAvail; }} The Theater class represents a theater of seats. The number of seats per row and the number of tier 1 and tier 2 rows are determined by the parameters of the Theater constructor. Row 0 of the theaterSeats array represents the row closest to the stage. public class Theater{ private Seat[][] theaterSeats; /** Constructs a Theater object, as described in part (a). * Precondition: seatsPerRow > 0; tier1Rows > 0; tier2Rows >= 0 */ public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) { /* to be implemented in part (a) */ } /** Returns true if a seat holder was reassigned from the seat at fromRow, fromCol * to the seat at toRow, toCol; otherwise it returns false, as described in part (b). * Precondition: fromRow, fromCol, toRow, and toCol represent valid row and * column positions in the theater. * The seat at fromRow, fromCol is not available. */ public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol) { /* to be implemented in part (b) */ }} (a) Write the constructor for the Theater class. The constructor takes three int parameters, representing the number of seats per row, the number of tier 1 rows, and the number of tier 2 rows, respectively. The constructor initializes the theaterSeats instance variable so that it has the given number of seats per row and the given number of tier 1 and tier 2 rows and all seats are available and have the appropriate tier designation. Row 0 of the theaterSeats array represents the row closest to the stage. All tier 1 seats are closer to the stage than tier 2 seats. Complete the Theater constructor. /** Constructs a Theater object, as described in part (a). * Precondition: seatsPerRow > 0; tier1Rows > 0; tier2Rows >= 0 */ public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) Class information for this question public class Seat private boolean available private int tier public Seat(boolean isAvail, int tierNum) public boolean isAvailable() public int getTier() public void setAvailability(boolean isAvail) public class Theater private Seat[][] theaterSeats public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol) (b) Write the reassignSeat method, which attempts to move a person from a source seat to a destination seat. The reassignment can be made if the destination seat is available and has the same or greater tier than the source seat (that is, it is equally or less desirable). For example, a person in a tier 1 seat can be moved to a different tier 1 seat or to a tier 2 seat, but a person in a tier 2 seat can only be moved to a different tier 2 seat. The reassignSeat method has four int parameters representing the row and column indexes of the source ("from") and destination ("to") seats. If the reassignment is possible, the source seat becomes available, the destination seat becomes unavailable, and the method returns true. If the seat reassignment is not possible, no changes are made to either seat and the method returns false. Assume that the source seat is occupied when the method is called. Complete method reassignSeat. /** Returns true if a seat holder was reassigned from the seat at fromRow, fromCol * to the seat at toRow, toCol; otherwise it returns false, as described in part (b). * Precondition: fromRow, fromCol, toRow, and toCol represent valid row and * column positions in the theater. * The seat at fromRow, fromCol is not available. */ public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol)

a) public Theater(int seatsPerRow, int tier1Rows, int tier2Rows) { theaterSeats=new Seat[tier1Rows+tier2Rows][seatsPerRow]; for (int r=0; r<tier1Rows+tier2Rows;r++) { for (int c=0; c<seatsPerRow; c++) { if (r<tier1Rows) { theaterSeats[r][c]=new Seat(true,1); } else { theaterSeats[r][c]=new Seat(true,2); }}}} b) public boolean reassignSeat(int fromRow, int fromCol, int toRow, int toCol) { Seat toS=theaterSeats[toRow][toCol]; if (!toS.isAvailable()) { return false; } Seat fromS=theaterSeats[fromRow][fromCol]; if (toS.getTier()<fromS.getTier()){ return false; } toS.setAvailability(false); fromS.setAvailability(true); return true; }

Consider a system for processing student test scores. The following class will be used as part of this system and contains a student's name and the student's answers for a multiple-choice test. The answers are represented as strings of length one with an omitted answer being represented by a string containing a single question mark ("?"). These answers are stored in an ArrayList in which the position of the answer corresponds to the question number on the test (question numbers start at 0). A student's score on the test is computed by comparing the student's answers with the corresponding answers in the answer key for the test. One point is awarded for each correct answer and ¼ of a point is deducted for each incorrect answer. Omitted answers (indicated by "?") do not change the student's score. The following table shows an example of an answer key, a student's answers, and the corresponding point values that would be awarded for the student's answers. In this example, there are six correct answers, three incorrect answers, and one omitted answer. The student's score is ((6 * 1) - (3 * 0.25)) = 5.25 . a) Write the StudentAnswerSheet method getScore. The parameter passed to method getScore is an ArrayList of strings representing the correct answer key for the test being scored. The method computes and returns a double that represents the score for the student's test answers when compared with the answer key. One point is awarded for each correct answer and ¼ of a point is deducted for each incorrect answer. Omitted answers (indicated by "?") do not change the student's score. Complete method getScore below. b) Consider the following class that represents the test results of a group of students that took a multiple-choice test. Write the TestResults method highestScoringStudent, which returns the name of the student who received the highest score on the test represented by the parameter key. If there is more than one student with the highest score, the name of any one of these highest-scoring students may be returned. You may assume that the size of each answer sheet represented in the ArrayList sheets is equal to the size of the ArrayList key. In writing highestScoringStudent, assume that getScore works as specified, regardless of what you wrote in part (a). Complete method highestScoringStudent below

a) public double getScore (ArrayList<String> key) { double score = 0.0; for (int i = 0; i < answers.size(); i++) { if (answers.get(i).equals(key.get(i))) score += 1.0; else if (!answers.get(i).equals("?")) score -= 0.25; }} return score; } b) public String highestScoringStudent (ArrayList<String> key) { StudentAnswerSheet highest = sheets.get(0); for (StudentAnswerSheet sheet : sheets) { if (Sheet.getScore(key) > highest.getScore(key)) { highest = sheet; }} return highest.getName(); }

A grayscale image is represented by a 2-dimensional rectangular array of pixels (picture elements). A pixel is an integer value that represents a shade of gray. In this question, pixel values can be in the range from 0 through 255, inclusive. A black pixel is represented by 0, and a white pixel is represented by 255. The declaration of the GrayImage class is shown below. You will write two unrelated methods of the GrayImage class. a) Write the method countWhitePixels that returns the number of pixels in the image that contain the value WHITE. For example, assume that pixelValues contains the following image. A call to countWhitePixels method would return 5 because there are 5 entries (shown in boldface) that have the value WHITE. Complete method countWhitePixels below. b) Write the method processImage that modifies the image by changing the values in the instance variable pixelValues according to the following description. The pixels in the image are processed one at a time in row-major order. Row-major order processes the first row in the array from left to right and then processes the second row from left to right, continuing until all rows are processed from left to right. The first index of pixelValues represents the row number, and the second index represents the column number. The pixel value at position (row, col) is decreased by the value at position (row + 2, col + 2) if such a position exists. If the result of the subtraction is less than the value BLACK, the pixel is assigned the value of BLACK. The values of the pixels for which there is no pixel at position (row + 2, col + 2) remain unchanged. You may assume that all the original values in the array are within the range [BLACK, WHITE], inclusive. The following diagram shows the contents of the instance variable pixelValues before and after a call to processImage. The values shown in boldface represent the pixels that could be modified in a grayscale image with 4 rows and 5 columns. Complete method processImage below.

a) public int countWhitePixels() { int whitePixelCount = 0; for (int row = 0; row < pixelValues.length; row++) { for (int col = 0; col < pixelValues[row].length; col++) { if (pixelValues[row][col] == WHITE) { whitePixelCount++;}} return whitePixelCount;} b) public void processImage(){ for (int row = 0; row < pixelValues.length-2; row++) { for (int col = 0; col < pixelValues[row].length-2; col++) { pixelValues[row][col] -= pixelValues[row+2][col+2]; if (pixelValues[row][col] < BLACK) { pixelValues[row][col] = BLACK;}}}}

This question involves manipulating a two-dimensional array of integers. You will write two static methods of the ArrayResizer class, which is shown below. public class ArrayResizer { /** Returns true if and only if every value in row r of array2D * is non-zero. * Precondition: r is a valid row index in array2D. * Postcondition: array2D is unchanged. */ public static boolean isNonZeroRow(int[][] array2D, int r) { /* to be implemented in part (a) */ } /** Returns the number of rows in array2D that contain all * non-zero values. * Postcondition: array2D is unchanged. */ public static int numNonZeroRows(int[][] array2D) { /* implementation not shown */ } /** Returns a new, possibly smaller, two-dimensional array that * contains only rows from array2D with no zeros, as described * in part (b). * Precondition: array2D contains at least one column * and at least one row with no zeros. * Postcondition: array2D is unchanged. */ public static int[][] resize(int[][] array2D) { /* to be implemented in part (b) */ } } (a) Write the method isNonZeroRow, which returns true if and only if all elements in row r of a two-dimensional array array2D are not equal to zero. For example, consider the following statement, which initializes a two-dimensional array. int[][] arr = {{2, 1, 0}, {1, 3, 2}, {0, 0, 0}, {4, 5, 6}}; Sample calls to isNonZeroRow are shown below. Call to isNonZeroRowValue ReturnedExplanationArrayResizer.isNonZeroRow(arr, 0)falseAt least one value in row 0 is zero.ArrayResizer.isNonZeroRow(arr, 1)trueAll values in row 1 are non-zero.ArrayResizer.isNonZeroRow(arr, 2)falseAt least one value in row 2 is zero.ArrayResizer.isNonZeroRow(arr, 3)trueAll values in row 3 are non-zero. Complete the isNonZeroRow method. /** Returns true if and only if every value in row r of array2D * is non-zero. * Precondition: r is a valid row index in array2D. * Postcondition: array2D is unchanged. */ public static boolean isNonZeroRow(int[][] array2D, int r) (b) Write the method resize, which returns a new two-dimensional array containing only rows from array2D with all non-zero values. The elements in the new array should appear in the same order as the order in which they appeared in the original array. The following code segment initializes a two-dimensional array and calls the resize method. int[][] arr = {{2, 1, 0}, {1, 3, 2}, {0, 0, 0}, {4, 5, 6}}; int[][] smaller = ArrayResizer.resize(arr); When the code segment completes, the following will be the contents of smaller. {{1, 3, 2}, {4, 5, 6}} A helper method, numNonZeroRows, has been provided for you. The method returns the number of rows in its two-dimensional array parameter that contain no zero values. Complete the resize method. Assume that isNonZeroRow works as specified, regardless of what you wrote in part (a). You must use numNonZeroRows and isNonZeroRow appropriately to receive full credit. /** Returns a new, possibly smaller, two-dimensional array that * contains only rows from array2D with no zeros, as described * in part (b). * Precondition: array2D contains at least one column * and at least one row with no zeros. * Postcondition: array2D is unchanged. */ public static int[][] resize(int[][] array2D)

a) public static boolean isNonZeroRow(int[][] array2D, int r) { for (int col = 0; col < array2D[0].length; col++) { if (array2D[r][col]==0) { return false; } } return true; } b) public static int[][] resize(int[][] array2D) { int numRows=array2D.length; int numCols=array2D[0].length; int[][] result=new int[numNonZeroRows(array2D)][numCols]; int newRowIndex=0; for (int r=0; r<numRows; r++) { if (isNonZeroRow(array2D, r)) { for (int c=0; c<numCOls; c++) { result[newRowIndex][c]=array2D[r][c]; } newRowIndex++; }} return result; }

This question involves reasoning about one-dimensional and two-dimensional arrays of integers. You will write three static methods, all of which are in a single enclosing class, named DiverseArray (not shown). The first method returns the sum of the values of a one-dimensional array; the second method returns an array that represents the sums of the rows of a two-dimensional array; and the third method analyzes row sums. (a) Write a static method arraySum that calculates and returns the sum of the entries in a specified one-dimensional array. The following example shows an array arr1 and the value returned by a call to arraySum. Complete method arraySum below. / * * Returns the sum of the entries in the one-dimensional array arr. * / public static int arraySum (int [ ] arr) (b) Write a static method rowSums that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one-dimensional array. The method has one parameter, a two-dimensional array arr2D of int values. The array is in row-major order: arr2D [ r ] [ c ] is the entry at row r and column c. The method returns a one-dimensional array with one entry for each row of arr2D such that each entry is the sum of the corresponding row in arr2D. As a reminder, each row of a two-dimensional array is a one-dimensional array.For example, if mat1 is the array represented by the following table, the call rowSums(mat1) returns the array {16, 32, 28, 20}. Assume that arraySum works as specified, regardless of what you wrote in part (a). You must use arraySum appropriately to receive full credit. Complete method rowSums below. / * * Returns a one-dimensional array in which the entry at index k is the sum of * the entries of row k of the two-dimensional array arr2D. * / public static int [ ] rowSums(int [ ] [ ] arr2D) (c) A two-dimensional array is diverse if no two of its rows have entries that sum to the same value. In the following examples, the array mat1 is diverse because each row sum is different, but the array mat2 is not diverse because the first and last rows have the same sum. Write a static method isDiverse that determines whether or not a given two-dimensional array is diverse. The method has one parameter: a two-dimensional array arr2D of int values. The method should return true if all the row sums in the given array are unique; otherwise, it should return false. In the arrays shown above, the call isDiverse (mat1) returns true and the call isDiverse(mat2) returns false. Assume that arraySum and rowSums work as specified, regardless of what you wrote in parts (a) and(b). You must use rowSums appropriately to receive full credit.Complete method isDiverse below. / * * Returns true if all rows in arr2D have different row sums;* false otherwise. * /public static boolean isDiverse(int [ ] [ ] arr2D)

a) public static int arraySUm(int[] arr) { int sum=0; for (int elem : arr) { sum+=elem; } return sum; } b) public static int[] rowSums(int[][] arr2D) { int[] sums=new int[arr2D.length]; int rowNum=0; for(int[]row:arr2D) { sums[rowNum]=arraySum(row); rowNum++; } return sums; } c) public static boolean isDiverse(int[][] arr2D) { int[] sums=rowSums(arr2D); for (int i=0; i<sums.length; i++){ for (int j=i+1; j<sums.length;j++) { if(sums[i]==sums[j]){ return false;}}} return true; }

This question involves performing arithmetic operations on two-dimensional (2D) arrays of integers. You will write two static methods, both of which are in a class named MatrixOp (not shown). (a) Write the method diagonalOp, which returns the sum of the products of the corresponding entries on the main diagonals of two given square 2D arrays that have the same dimensions. The main diagonal goes from the top-left corner to the bottom-right corner in a square 2D array. For example, assume that mat1 and mat2 are properly defined 2D arrays containing the values shown below. The main diagonals have been shaded in gray. After the call int sum = MatrixOp.diagonalOp(mat1, mat2), sum would contain 21, as illustrated below. sum = (2 * -1) + (5 * 3) + (4 * 2) = 21 Complete method diagonalOp. /** Returns an integer, as described in part (a). * Precondition: matA and matB are 2D arrays that are both square, * have at least one row, and have the same dimensions. */ public static int diagonalOp(int[][] matA, int[][] matB) (b) Write the method expandMatrix, which returns an expanded version of a given 2D array. To expand a 2D array, a new 2D array must be created and filled with values such that each element of the original 2D array occurs a total of four times in the new 2D array, arranged as shown in the example below. For example, assume that mat3 is a properly defined 2D array containing the values shown below. After the call int[][] mat4 = MatrixOp.expandMatrix(mat3), the array mat4 would contain the values shown below. Complete method expandMatrix. /** Returns a 2D array, as described in part (b). * Precondition: matA is a 2D array with at least one row and * at least one column. */ public static int[][] expandMatrix(int[][] matA)

a) public static int diagonalOp(int[][] matA, int[][] matB) { int result=0; for (int i=0; i<matA.length; i++) { result+=matA[i][i]*matB[i][i];} return result;} b) public static int[][] expandMatrix(int[][] matA) { int[][] result=new int(2*matA.length][2*matA[0].length]; for (int r=0; r<result.length; r++) { for (int c=0; c<result[0].length; c++) { result[r][c]=matA[r/2][c/2]; }} return result;}

This question involves reasoning about arrays of integers. You will write two static methods, both of which are in a class named ArrayTester. a) Write a static method getColumn, which returns a one-dimensional array containing the elements of a single column in a two-dimensional array. The elements in the returned array should be in the same order as they appear in the given column. The notation arr2D[r][c] represents the array element at row r and column c. The following code segment initializes an array and calls the getColumn method. int[][] arr2D = { {0,1,2},{3,4,5},{6,7,8},{9,5,3}}; int[] result = ArrayTester.getColumn(arr2D,1); When the code segment has completed execution, the variable result will have the following contents. result: {1,4,7,5} Complete method getColumn below. b) Write the static method isLatin, which returns true if a given two-dimensional square array is a Latin square, and otherwise, returns false. A two-dimensional square array of integers is a Latin square if the following conditions are true. • The first row has no duplicate values. • All values in the first row of the square appear in each row of the square. • All values in the first row of the square appear in each column of the square. The ArrayTester class provides two helper methods: containsDuplicates and hasAllValues. The method containsDuplicates returns true if the given one-dimensional array arr contains any duplicate values and false otherwise. The method hasAllValues returns true if and only if every value in arr1 appears in arr2. You do not need to write the code for these methods. Complete method isLatin below. Assume that getColumn works as specified, regardless of what you wrote in part (a). You must use getColumn, hasAllValues, and containsDuplicates appropriately to receive full credit.

a) public static int[] getColumn(int[][] arr2D, int c){ int[] result = new int[arr2D.length]; for (int r = 0; r < arr2D.length; r++){ result[r] = arr2D[r][c];} return result;} b) public static boolean isLatin(int[][] square){ if (containsDuplicates(square[0])){ return false;} for (int r = 1; r < square.length; r++){ if (!hasAllValues(square[0], square[r])){ return false;}} for (int c = 0; c < square[0].length; c++){ if (!hasAllValues(square[0], getColumn(square, c))){ return false;}} return true;}

A high school club maintains information about its members in a MemberInfo object. A MemberInfo object stores a club member's name, year of graduation, and whether or not the club member is in good standing. A member who is in good standing has fulfilled all the responsibilities of club membership. A partial declaration of the MemberInfo class is shown below. public class MemberInfo{ /** Constructs a MemberInfo object for the club member with name * name, graduation year gradYear, and standing hasGoodStanding. */ public MemberInfo(String name, int gradYear, boolean hasGoodStanding) { /* implementation not shown */ } /** Returns the graduation year of the club member. */ public int getGradYear() { /* implementation not shown */ } /** Returns true if the member is in good standing and false * otherwise. */ public boolean inGoodStanding() { /* implementation not shown */ } // There may be instance variables, constructors, and methods // that are not shown. } The ClubMembers class maintains a list of current club members. The declaration of the ClubMembers class is shown below. public class ClubMembers{ private ArrayList<MemberInfo> memberList; /** Adds new club members to memberList, as described in part (a). * Precondition: names is a non-empty array. */ public void addMembers(String[] names, int gradYear) { /* to be implemented in part (a) */ } /** Removes members who have graduated and returns a list of * members who have graduated and are in good standing, * as described in part (b). */ public ArrayList<MemberInfo> removeMembers(int year) { /* to be implemented in part (b) */ } // There may be instance variables, constructors, and methods // that are not shown. } (a) Write the ClubMembers method addMembers, which takes two parameters. The first parameter is a String array containing the names of new club members to be added. The second parameter is the graduation year of all the new club members. The method adds the new members to the memberList instance variable. The names can be added in any order. All members added are initially in good standing and share the same graduation year, gradYear. Complete the addMembers method. /** Adds new club members to memberList, as described in part (a). * Precondition: names is a non-empty array. */ public void addMembers(String[] names, int gradYear) (b) Write the ClubMembers method removeMembers, which takes the following actions. Returns a list of all students who have graduated and are in good standing. A member has graduated if the member's graduation year is less than or equal to the method's year parameter. If no members meet these criteria, an empty list is returned. Removes from memberList all members who have graduated, regardless of whether or not they are in good standing. The following example illustrates the results of a call to removeMembers. The ArrayList memberList before the method call removeMembers(2018): "SMITH, JANE" 2019 false ​ ​"FOX, STEVE" 2018​ true​ "XIN, MICHAEL" 2017 false "GARCIA, MARIA" 2020 true The ArrayList memberList after the method call removeMembers(2018): "SMITH, JANE" 2019 false "GARCIA, MARIA" 2020 true The ArrayList returned by the method call removeMembers(2018): "FOX, STEVE" 2018​ true​ Complete the removeMembers method. /** Removes members who have graduated and returns a list of * members who have graduated and are in good standing, * as described in part (b). */

a) public void addMembers(String[] names, int gradYear) { for (String n : names) { MemberInfo newM=new MemberInfo(n, gradYear, true); memberList.add(newM); }} b) public ArrayList<MemberInfo> removeMembers (int year) {ArrayList<MemberInfo> removed=new ArrayList<MemberInfo>();for (int i=memberList.size()-1; i>=0; i--) {if (memberList.get(i).getGradYear()<=year) {if (memberList.get(i).inGoodStanding()) {removed.add(memberList.get(i)); }memberList.remove(i); } }return removed; }

In this question you will write two methods for a class RouteCipher that encrypts (puts into a coded form) a message by changing the order of the characters in the message. The route cipher fills a two-dimensional array with single-character substrings of the original message in row-major order, encrypting the message by retrieving the single-character substrings in column-major order. For example, the word "Surprise" can be encrypted using a 2-row, 4-column array as follows. An incomplete implementation of the RouteCipher class is shown below. a) Write the method fillBlock that fills the two-dimensional array letterBlock with one-character strings from the string passed as parameter str. The array must be filled in row-major order—the first row is filled from left to right, then the second row is filled from left to right, and so on, until all rows are filled. If the length of the parameter str is smaller than the number of elements of the array, the string "A" is placed in each of the unfilled cells. If the length of str is larger than the number of elements in the array, the trailing characters are ignored. For example, if letterBlock has 3 rows and 5 columns and str is the string "Meet at noon", the resulting contents of letterBlock would be as shown in the following table. If letterBlock has 3 rows and 5 columns and str is the string "Meet at midnight", the resulting contents of letterBlock would be as shown in the following table. The following expression may be used to obtain a single-character string at position k of the string str. str.substring(k, k + 1) Complete method fillBlock below. b) Write the method encryptMessage that encrypts its string parameter message. The method builds an encrypted version of message by repeatedly calling fillBlock with consecutive, nonoverlapping substrings of message and concatenating the results returned by a call to encryptBlock after each call to fillBlock. When all of message has been processed, the concatenated string is returned. Note that if message is the empty string, encryptMessage returns an empty string. The following example shows the process carried out if letterBlock has 2 rows and 3 columns and encryptMessage("Meet at midnight") is executed. In this example, the method returns the string "Mte eati dmnitgAhA". Assume that fillBlock and encryptBlock methods work as specified. Solutions that reimplement the functionality of one or both of these methods will not receive full credit. Complete method encryptMessage below.

a) public void fillBlock(String str) { int cell = 0; for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { String letter; if ( cell < str.length() ) { letter = str.charAt(cell++) + ""; } else { letter = "A"; } letterBlock[r][c] = letter; } } } b) public String encryptMessage(String message) { message = message.trim(); if ( message.equals("") ) return ""; int size = numRows * numCols; int blocks = (int) Math.ceil( (double)message.length() / size ); int processed = 0; String encrypted = ""; while ( processed < blocks ) { int start = processed * size, end; if ( ((processed+1) * size) > message.length() ) { end = message.length(); } else { end = (processed+1) * size; } fillBlock( message.substring( start, end ) ); encrypted += encryptBlock(); processed++; } return encrypted; } }


संबंधित स्टडी सेट्स

Test 3- Immunity, Metabolism, and Cellular Regulation

View Set

Accounting Ch.12 Securities Classified "Trading" debt or FVTNI equity

View Set

Chapter 7.1 civil rights and 7.2 and 7.3

View Set

Womens Health: Combined Oral Contraceptives (Case 2)

View Set