(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.
public class DiverseArray {
public static int arraySum (int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static void main (String args[]) {
int[] testArray = {1, 3, 2, 7, 3};
int sum = arraySum(testArray);
System.out.println(sum);
}
}
DiverseArray.main(null);
16
(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
import java.util.Arrays;
public class DiverseArray {
public static int arraySum (int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static int[] rowSums (int[][] arr2D) {
int numRows = arr2D.length;
int[] summedRows = new int[numRows];
for (int i = 0; i < numRows; i++) {
int sumRow = arraySum (arr2D[i]);
summedRows[i] = sumRow;
}
return summedRows;
}
public static void main (String args[]) {
int[][] mat1 = {
{1, 3, 2, 7, 3},
{10, 10, 4, 6, 2},
{5, 3, 5, 9, 6},
{7, 6, 4, 2, 1}
};
int[] result = rowSums(mat1);
System.out.println(Arrays.toString(result));
}
}
DiverseArray.main(null);
[16, 32, 28, 20]
(c) 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.
public class DiverseArray {
public static int arraySum (int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static int[] rowSums (int[][] arr2D) {
int numRows = arr2D.length;
int[] summedRows = new int[numRows];
for (int i = 0; i < numRows; i++) {
int sumRow = arraySum (arr2D[i]);
summedRows[i] = sumRow;
}
return summedRows;
}
public static boolean isDiverse(int[][] arr2D) {
int[] summedRowArr = rowSums(arr2D);
for (int i = 0; i < summedRowArr.length; i++) {
int marker = summedRowArr[i];
for (int j = i+1; j < summedRowArr.length; j++) {
if (marker == summedRowArr[j]) {
return false;
}
}
}
return true;
}
public static void main (String args[]) {
int[][] mat1 = {
{1, 3, 2, 7, 3},
{10, 10, 4, 6, 2},
{5, 3, 5, 9, 6},
{7, 6, 4, 2, 1}
};
int[][] mat2 = {
{1, 1, 5, 3, 4},
{12, 7, 6, 1, 9},
{8, 11, 10, 2, 5},
{3, 2, 3, 0, 6}
};
System.out.println(isDiverse(mat1));
System.out.println(isDiverse(mat2));
}
}
DiverseArray.main(null);
true
false
Method and Control Structure Question
2.Consider a guessing game in which a player tries to guess a hidden word. The hidden word contains only capitalletters and has a length known to the player. A guess contains only capital letters and has the same length as the hidden word.
After a guess is made, the player is given a hint that is based on a comparison between the hidden word and the guess. Each position in the hint contains a character that corresponds to the letter in the same position in the guess. The following rules determine the characters that appear in the hint.
The HiddenWord class will be used to represent the hidden word in the game. The hidden word is passed to the constructor. The class contains a method, getHint, that takes a guess and produces a hint.
Write the complete HiddenWord class, including any necessary instance variables, its constructor, and the method, getHint, described above. You may assume that the length of the guess is the same as the length of the hidden word.
public class HiddenWord {
private String hiddenWord; //Hidden Word Field
public HiddenWord(String hiddenWord) { //contrsuctor for the hidden word
this.hiddenWord = hiddenWord;
}
public String getHint (String guess) {
StringBuilder hint = new StringBuilder(); //Builder for making the hint
for (int i = 0; i < guess.length(); i++) {
char guessChar = guess.charAt(i); // Character from the guess
char hiddenChar = hiddenWord.charAt(i); // Corresponding character from the hidden word
if (guessChar == hiddenChar) {
hint.append(guessChar); // If characters match, add the character to the hint
} else if (hiddenWord.contains(String.valueOf(guessChar))) {
hint.append("+"); // If the guess character is in the hidden word but in a different position
} else {
hint.append("*"); // If the guess character is not in the hidden word
}
}
return hint.toString(); //Convert StringBuilder to String and return hint
}
public static void main (String args[]) {
HiddenWord puzzle = new HiddenWord("HARPS");
System.out.println(puzzle.getHint("AAAAA"));
System.out.println(puzzle.getHint("HELLO"));
System.out.println(puzzle.getHint("HEART"));
System.out.println(puzzle.getHint("HARMS"));
System.out.println(puzzle.getHint("HARPS"));
}
}
HiddenWord.main(null);
+A+++
H****
H*++*
HAR*S
HARPS
Array/ArrayLists Question
A two-dimensional array of integers in which most elements are zero is called a sparse array. Because most elements have a value of zero, memory can be saved by storing only the non-zero values along with their row and column indexes. The following complete SparseArrayEntry
class is used to represent non-zero elements in a sparse array. A SparseArrayEntry
object cannot be modified after it has been constructed.
public class SparseArrayEntry {
/** The row index and column index for this entry in the sparse array */
private int row;
private int col;
/** The value of this entry in the sparse array */
private int value;
/** Constructs a SparseArrayEntry object that represents a sparse array element
* with row index r and column index c, containing value v.
*/
public SparseArrayEntry(int r, int c, int v) {
row = r;
col = c;
value = v;
}
/** Returns the row index of this sparse array element. */
public int getRow() {
return row;
}
public void setRow(int newRow) {
this.row = newRow;
}
/** Returns the column index of this sparse array element. */
public int getCol() {
return col;
}
public void setCol(int newCol) {
this.col = newCol;
}
/** Returns the value of this sparse array element. */
public int getValue() {
return value;
}
public void setValue(int newValue) {
this.value = newValue;
}
//Allows for the printing out of a SparseArrayEntry to the console in a visually appealing fashion
@Override
public String toString() {
return "SparseArrayEntry{" +
"row=" + row +
", col=" + col +
", value=" + value +
'}';
}
}
public class SparseArray {
/** The number of rows and columns in the sparse array. */
private int numRows;
private int numCols;
/** The list of entries representing the non-zero elements of the sparse array. Entries are stored in the
* list in no particular order. Each non-zero element is represented by exactly one entry in the list.
*/
private List<SparseArrayEntry> entries;
/** Constructs an empty SparseArray. */
public SparseArray() {
entries = new ArrayList<SparseArrayEntry>();
}
/** Adds an Entry to the Sparse Array */
public void addEntry(SparseArrayEntry entry) {
entries.add(entry);
}
/** A nice way to print out the entries so we can ensure the remove column method works */
public void printEntries() {
for (SparseArrayEntry entry : entries) {
System.out.println(entry);
}
}
/** Returns the number of rows in the sparse array. */
public int getNumRows() {
return numRows;
}
public void setNumRows(int newNumRows) {
this.numRows = newNumRows;
}
/** Returns the number of columns in the sparse array. */
public int getNumCols() {
return numCols;
}
public void setNumCols(int newNumCols) {
this.numCols = newNumCols;
}
/** Returns the value of the element at row index row and column index col in the sparse array.
* Precondition: 0 row < getNumRows()
* 0 col < getNumCols()
*/
public int getValueAt(int row, int col) { /* to be implemented in part (a) */
for (int i = 0; i < entries.size(); i++) {
SparseArrayEntry entry = entries.get(i);
int rowNumber = entry.getRow();
int colNumber = entry.getCol();
if (rowNumber == row && colNumber == col) {
return entry.getValue();
}
}
return 0;
}
/** Removes the column col from the sparse array.
* Precondition: 0 col < getNumCols()
*/
public void removeColumn(int col) {
Iterator<SparseArrayEntry> iterator = entries.iterator();
while (iterator.hasNext()) {
SparseArrayEntry entry = iterator.next();
int colNumber = entry.getCol();
if (colNumber == col) {
iterator.remove();
} else if (colNumber > col) {
entry.setCol(colNumber - 1);
}
}
this.setNumCols(this.getNumCols() - 1);
}
// There may be instance variables, constructors, and methods that are not shown.
public static void main(String args[]) {
SparseArray sparseArray = new SparseArray();
// Set the number of rows and columns
sparseArray.setNumRows(6);
sparseArray.setNumCols(5);
// Add entries to the sparse array
sparseArray.addEntry(new SparseArrayEntry(1, 4, 4));
sparseArray.addEntry(new SparseArrayEntry(2, 0, 1));
sparseArray.addEntry(new SparseArrayEntry(3, 1, -9));
sparseArray.addEntry(new SparseArrayEntry(1, 1, 5));
System.out.println("Exepected Outputs for part (a)");
System.out.println(sparseArray.getValueAt(3, 1));
System.out.println(sparseArray.getValueAt(3, 3));
System.out.println("\nEntries Before removing column 1:");
sparseArray.printEntries();
sparseArray.removeColumn(1);
System.out.println("\nExpected Outputs for part (b)");
System.out.println("numRows: " + sparseArray.getNumRows());
System.out.println("numCols: " + sparseArray.getNumCols());
System.out.println("\nEntries After removing column 1:");
sparseArray.printEntries();
}
}
SparseArray.main(null);
Exepected Outputs for part (a)
-9
0
Entries Before removing column 1:
SparseArrayEntry{row=1, col=4, value=4}
SparseArrayEntry{row=2, col=0, value=1}
SparseArrayEntry{row=3, col=1, value=-9}
SparseArrayEntry{row=1, col=1, value=5}
Expected Outputs for part (b)
numRows: 6
numCols: 4
Entries After removing column 1:
SparseArrayEntry{row=1, col=3, value=4}
SparseArrayEntry{row=2, col=0, value=1}
Classes Question
4.A number group represents a group of integers defined in some way. It could be empty, or it could contain one or more integers.
Write an interface named NumberGroup that represents a group of integers. The interface should have a single contains method that determines if a given integer is in the group. For example, if group1 is of type NumberGroup, and it contains only the two numbers -5 and 3, then group1.contains(-5) would return true, and group1.contains(2) would return false.
(a) Write the complete NumberGroup interface. It must have exactly one method.
public interface NumberGroup {
//Logic for the method will be present in the class that implements the interface.
boolean contains(int value);
}
(b) A range represents a number group that contains all (and only) the integers between a minimum value and a maximum value, inclusive.
Write the Range class, which is a NumberGroup. The Range class represents the group of int values that range from a given minimum value up through a given maximum value, inclusive. For example, the declaration
NumberGroup range1 = new Range(-3, 2); represents the group of integer values -3, -2, -1, 0, 1, 2.
Write the complete Range class. Include all necessary instance variables and methods as well as a constructor that takes two int parameters. The first parameter represents the minimum value, and the second parameter represents the maximum value of the range. You may assume that the minimum is less than or equal to the maximum.
public class Range implements NumberGroup {
private int min;
private int max;
public Range(int min, int max) {
this.min = min;
this.max = max;
}
@Override
public boolean contains(int number) {
if (number >= min && number <= max) {
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
Range Range1 = new Range(-3, 2);
System.out.println(Range1.contains(-4));
System.out.println(Range1.contains(0));
}
}
Range.main(null);
false
true
(c) The MultipleGroups class (not shown) represents a collection of NumberGroup objects and is a NumberGroup. The MultipleGroups class stores the number groups in the instance variable groupList (shown below), which is initialized in the constructor.
private List<NumberGroup> groupList;
Write the MultipleGroups method contains. The method takes an integer and returns true if and only if the integer is contained in one or more of the number groups in groupList.
For example, suppose multiple1 has been declared as an instance of MultipleGroups and consists of the three ranges created by the calls new Range(5, 8), new Range(10, 12), and new Range(1, 6). The following table shows the results of several calls to contains.
public class MultipleGroups implements NumberGroup {
private List<NumberGroup> groupList;
public MultipleGroups () {
groupList = new ArrayList<NumberGroup>();
}
public void addGroup (NumberGroup group) {
groupList.add(group);
}
@Override
public boolean contains (int number) {
for (NumberGroup group : groupList) {
if (group.contains(number)) {
return true;
}
}
return false;
}
public static void main (String args[]) {
MultipleGroups multiple1 = new MultipleGroups();
multiple1.addGroup(new Range(5, 8));
multiple1.addGroup(new Range(10, 12));
multiple1.addGroup(new Range(1, 6));
System.out.println(multiple1.contains(7));
System.out.println(multiple1.contains(9));
}
}
MultipleGroups.main(null);
true
false