March 2010 Exam Solutions
<< | OtherProjectsTrailIndex | >>
MazeBug
import info.gridworld.grid.*; import info.gridworld.actor.*; import java.util.ArrayList; public class MazeBug extends Bug { //part a public boolean isValidGrid() { Grid<Actor> gr =getGrid(); if (gr==null) return false; ArrayList<Location> occupiedLocs = gr.getOccupiedLocations(); for (Location loc: occupiedLocs) { Actor a = gr.get(loc); if (!(a instanceof Rock || a instanceof Flower) && a!=this) return false; } return true; } public void act() { if (canMoveLeft()) moveLeft(); else super.act(); } //part b public void moveLeft() { setDirection(getDirection() + Location.LEFT); move(); } //part c public boolean canMoveLeft() { Grid gr = getGrid(); if (gr == null) return false; Location loc = getLocation(); Location next = loc.getAdjacentLocation(getDirection() - 90); Location corner = loc.getAdjacentLocation(getDirection() - 135); return gr.isValid(next) && !(gr.get(next) instanceof Rock) && (!gr.isValid(corner) ||gr.get(corner) instanceof Rock); } //part d public void turn() { super.turn(); super.turn(); } }
ScoreUp
public class ScoreUpTest { //part a public static int scoreUp(String[] key, String[] answers) { int score=0; for (int i=0; i<key.length; i++) if (key[i].equals(answers[i])) score+=4; else if (!answers[i].equals("?")) score--; return score; } //part b public static String[] split(String s) { String[] result=new String[s.length()]; for (int i=0; i<s.length(); i++) result[i]=s.substring(i,i+1); return result; } public static int scoreUp(String key, String answers) { String[] keyArray=split(key); String[] answerArray = split(answers); return scoreUp(keyArray, answerArray); } public static void main(String[] args) { String[] key1={"a", "a", "b", "b"}; String[] six={"a", "c", "b", "c"}; String[] elf={"a", "a", "b", "c"}; String[] sixteen={"a", "a", "b", "b"}; String[] seven={"a", "a", "?", "c"}; System.out.println("Part (a) Test:"); System.out.println("Should be 6->"+scoreUp(key1, six) ); System.out.println("Should be 11->"+scoreUp(key1, elf) ); System.out.println("Should be 16->"+scoreUp(key1, sixteen) ); System.out.println("Should be 7->"+scoreUp(key1, seven) ); System.out.println("Part (b) Test:"); String key="aabb"; int abbyScore = scoreUp(key, "acbc"); int beckyScore = scoreUp(key, "aabc"); int clarissaScore = scoreUp(key, "aabb"); int darlaScore = scoreUp(key, "aa?c"); System.out.println("Should be 6->"+abbyScore); System.out.println("Should be 6->"+beckyScore); System.out.println("Should be 6->"+clarissaScore); System.out.println("Should be 6->"+darlaScore); } }