Skip to content

Instantly share code, notes, and snippets.

@gschaffner
Last active April 28, 2016 04:51
Show Gist options
  • Save gschaffner/ef92053bc2a07cedcd64c630e3b03c78 to your computer and use it in GitHub Desktop.
Save gschaffner/ef92053bc2a07cedcd64c630e3b03c78 to your computer and use it in GitHub Desktop.
APCS Written Test Practice 2015
// 1a
public static int arraySum(int[] arr) {
int sum = 0;
for(int elem : arr)
if(elem != null)
sum += elem;
return sum;
}
// 1b
public static int[] rowSums(int[][] arr2D) {
int[] out = new int[arr2D.length];
for(int i = 0; i < out.length; i++)
out[i] = arraySum(i);
return out;
}
// 1c
public static boolean isDiverse(int[][] arr2D) {
int[] arr1D = rowSums(arr2D);
for(int i = 0; i < arr1D.length; i++)
for(int j = 0; j < i; j++)
if(arr1D[i] == arr1D[j])
return false;
return true;
}
// 2
public class HiddenWord {
private String word;
public HiddenWord(String newWord) {
word = newWord;
}
pulic String getHint(String guess) {
String toReturn = "";
for(int i = 0; i < guess.length(); i++) {
if(guess.charAt(i).equals(word.charAt(i)))
// Answer keys uses substring(i, i + 1) instead of charAt(i).
// Is charAt(i) fine?
toReturn += guess.charAt(i);
else if(word.indexOf(guess.charAt(i)) != -1)
toReturn += "+";
else
toReturn += "*";
}
return toReturn;
}
}
// 3a
public int getValueAt(int row, int col) {
for(SparseArrayEntry elem : entries) {
if(elem.getRow() == row && elem.getCol() == col)
return elem.getValue();
}
return 0;
}
// 3b
public void removeColumn(int col) {
for(int i = 0; i < entries.size(); i++) {
if(entries.get(i).getCol() == col) {
entries.remove(i);
i--;
} else if(entries.get(i).getCol() > col) {
entries.set(i, new SparseArrayEntry(entries.get(i).getRow(), entries.get(i).getCol() - 1,
entries.get(i).getValue()));
}
}
numCols--;
}
// 4a
public interface NumberGroup {
// I didn't know whether the interface should have an array of integers or not, but I guessed not.
boolean contains(int num);
}
// 4b
// This is what I originally did; apparently it didn't want the class to actually have an array? It never specified...
//public class Range implements NumberGroup {
int[] myArray;
public Range(int low, int high) {
myArray = new int[high - low + 1];
int current = low;
for(int i = 0; i < myArray.length; i++) {
myArray[i] = current;
current++;
}
}
}
public class Range implements NumberGroup {
// I forgot private on these variables the first time
private int min;
private int max;
public Range(int mi, int ma) {
min = mi;
max = ma;
}
public boolean contains(int num) {
return (min <= num && num <= max);
}
}
// 4c
public boolean contains(int num) {
for(NumberGroup elem : groupList) {
if(elem.contains(num)) return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment