CMSC 206: Data Structures Harry Potter and the Practice Final Exam AND THE CS EXAM

Similar documents
Movement of the pieces

Chess Handbook: Course One

If a pawn is still on its original square, it can move two squares or one square ahead. Pawn Movement

YourTurnMyTurn.com: chess rules. Jan Willem Schoonhoven Copyright 2018 YourTurnMyTurn.com

ChesServe Test Plan. ChesServe CS 451 Allan Caffee Charles Conroy Kyle Golrick Christopher Gore David Kerkeslager

After learning the Rules, What should beginners learn next?


a b c d e f g h i j k l m n

Introduction to Spring 2009 Artificial Intelligence Final Exam

The Basic Rules of Chess

ENGR170 Assignment Problem Solving with Recursion Dr Michael M. Marefat

Chess Puzzle Mate in N-Moves Solver with Branch and Bound Algorithm

In the game of Chess a queen can move any number of spaces in any linear direction: horizontally, vertically, or along a diagonal.

Summer Reading You know it, you love it, you look forward to it every year.

Reality Chess. Yellow. White

The 2013 British Informatics Olympiad

CS61B Lecture #22. Today: Backtracking searches, game trees (DSIJ, Section 6.5) Last modified: Mon Oct 17 20:55: CS61B: Lecture #22 1

Summer Reading You know it, you love it, you look forward to it every year.

Chess Rules- The Ultimate Guide for Beginners

The game of Paco Ŝako

Structured Programming Using Procedural Languages INSS Spring 2018

More Recursion: NQueens

Assignment 6 Play A Game: Minesweeper or Battleship!!! Due: Sunday, December 3rd, :59pm

CSC Curriculum Term One Lesson Plans

The Pieces Lesson. In your chess set there are six different types of piece.

HARRY POTTER, RON WEASLEY, HERMIONE GRANGER

OCTAGON 5 IN 1 GAME SET

A Simple Pawn End Game

Eight Queens Puzzle Solution Using MATLAB EE2013 Project

The Game. Getting Sarted

LEARN TO PLAY CHESS CONTENTS 1 INTRODUCTION. Terry Marris December 2004

DELUXE 3 IN 1 GAME SET

Fun and Games on a Chess Board

Project Connect Four (Version 1.1)

Essential Chess Basics (Updated Version) provided by Chessolutions.com

Figure 1: A Checker-Stacks Position

arxiv: v1 [math.co] 24 Oct 2018

3. Bishops b. The main objective of this lesson is to teach the rules of movement for the bishops.

Boulder Chess. [0] Object of Game A. The Object of the Game is to fill the opposing Royal Chambers with Boulders. [1] The Board and the Pieces

Fun and Games on a Chess Board II

Tic-tac-toe. Lars-Henrik Eriksson. Functional Programming 1. Original presentation by Tjark Weber. Lars-Henrik Eriksson (UU) Tic-tac-toe 1 / 23

If a word starts with a vowel, add yay on to the end of the word, e.g. engineering becomes engineeringyay

Problem A. Ancient Keyboard

Pointers. The Rectangle Game. Robb T. Koether. Hampden-Sydney College. Mon, Jan 21, 2013

John Griffin Chess Club Rules and Etiquette

Lecture 20: Combinatorial Search (1997) Steven Skiena. skiena

NSCL LUDI CHESS RULES

03/05/14 20:47:19 readme

A1 Problem Statement Unit Pricing

Royal Battles. A Tactical Game using playing cards and chess pieces. by Jeff Moore

1 2-step and other basic conditional probability problems

CS61B Lecture #33. Today: Backtracking searches, game trees (DSIJ, Section 6.5)

Exp. 2: Chess. 2-1 Discussion. 2-2 Objective

CS 540-2: Introduction to Artificial Intelligence Homework Assignment #2. Assigned: Monday, February 6 Due: Saturday, February 18

1 Modified Othello. Assignment 2. Total marks: 100. Out: February 10 Due: March 5 at 14:30

The 8-queens problem

THE COMPLETE RULES OF TIME-CUBE CHESS

Welcome to the Brain Games Chess Help File.

Perry High School. 2 nd Semester!

G51PGP: Software Paradigms. Object Oriented Coursework 4

The Limits of Game Playing. J. K. Rowling s Harry Potter and the Sorcerer s Stone & Harry Potter and the Goblet of Fire

FOR THE CROWN Sample Play

: Principles of Automated Reasoning and Decision Making Midterm

Adversary Search. Ref: Chapter 5

Due: Sunday 13 November by 10:59pm Worth: 8%

Software Requirements Specification

Junior Circle Games with coins and chessboards

5.4 Imperfect, Real-Time Decisions

CS1020 Sit-In Lab #03 AY2015/16 Semester 2. Eels and Escalators

Game, Set, and Match Carl W. Lee September 2016

Problem Set 7: Network Flows Fall 2018

Southeastern European Regional Programming Contest Bucharest, Romania Vinnytsya, Ukraine October 21, Problem A Concerts

5.4 Imperfect, Real-Time Decisions

LESSON 2: THE INCLUSION-EXCLUSION PRINCIPLE

MAS336 Computational Problem Solving. Problem 3: Eight Queens

Lecture 19 November 6, 2014

Microchess 2.0 gives you a unique and exciting way to use your Apple II to enjoy the intellectually stimulating game of chess. The complete program lo

Basic Introduction to Breakthrough

Third year Project School of Computer Science University of Manchester Chess Game

DUNGEON THE ADVENTURE OF THE RINGS

BALDWIN WALLACE UNIVERSITY 2013 PROGRAMMING CONTEST

CSE548, AMS542: Analysis of Algorithms, Fall 2016 Date: Sep 25. Homework #1. ( Due: Oct 10 ) Figure 1: The laser game.

Grade 6 Math Circles February 15, 2012 Math Puzzles

THROUGH THE LOOKING GLASS CHESS

The Caster Chronicles Comprehensive Rules ver. 1.0 Last Update:October 20 th, 2017 Effective:October 20 th, 2017

CPSC 217 Assignment 3 Due Date: Friday March 30, 2018 at 11:59pm

Grade 7/8 Math Circles. Visual Group Theory

Monte Carlo tree search techniques in the game of Kriegspiel

An End Game in West Valley City, Utah (at the Harman Chess Club)

Over ===* Three games of strategy and chance Unique solitaire puzzles. For I to 4 players Ages 12 to adult. PassTM

Assignment II: Set. Objective. Materials

Second Annual University of Oregon Programming Contest, 1998

Your Name and ID. (a) ( 3 points) Breadth First Search is complete even if zero step-costs are allowed.

UNIVERSITY of PENNSYLVANIA CIS 391/521: Fundamentals of AI Midterm 1, Spring 2010

Project 2 - Blackjack Due 7/1/12 by Midnight

Week 1 Assignment Word Search

Sharing analysis in the Pawns compiler

Final Practice Problems: Dynamic Programming and Max Flow Problems (I) Dynamic Programming Practice Problems

Embedded Systems Lab

A few chessboards pieces: 2 for each student, to play the role of knights.

Transcription:

CMSC 206: Data Structures Harry Potter and the Practice Final Exam AND THE CS EXAM Many, far and wide, have read about the adventures of Harry, Ron, and Hermione. What you have read is a fabrication a simplified version, suitable for lay readers. Herein lies the true tale of how the trio saved life as we know it. Herein lies the true tale of Harry Potter and the Factorer's Stone. Harry, Ron, and Hermione deftly snuck past Fluffy the three-headed guard dog by playing Hagrid's flute to lull him to sleep. They jumped down the trapdoor at his feet. They landed on Devil's Snare, a plant that curls around the limbs (and sometimes necks) of unsuspecting Hogwarts students. 1

We represent each tentacle of the Devil's Snare as a linked list composed of Nodes. (See the Node.java file posted with Lab #10 for CS206.) To save our heroes from the evil plant, we must identify the links in the list that have a grip on one of their body parts. Each student is very well aware of what part of the plant is touching them they each have a Set<Node> containing all the Nodes that are touching. In other words, each has a set of nodes that must be removed. We shall use these class definitions: public class Student // a set of all nodes that must be removed to survive private Set<Node> touchingnodes = new HashSet<ListNode>(); public boolean istouching(node n) /* to be implemented below public class DevilsSnare // the heads of the tentacle lists private Node[] heads; public Node[] getheads() return heads; We wish to write methods, not placed in either of these classes, that free a student from the Devil's Snare. We will do this by iterating through the lists, looking for nodes that ought be removed, and removing them. 2

1. (4 pts) Neville Longbottom (another Hogwarts student), in reviewing the trio's actions, suggests that we simply iterate through a student's set of nodes, removing each one from its respective list. Which of the following statements is false? A. This approach, if implemented, would be slower than the approach above. B. It is impossible to write a method remove(node node) without knowing the head of the list. C. The running time of Neville's approach, if properly implemented, would be O(TSL), where T is the number of touching nodes, S is the number of different tentacles (the size of the heads array), and L is the maximum length of a tentacle (the maximum number of nodes in a list representing a tentacle). D. It is slow to iterate through a HashSet that is why this approach is not used. E. Neville's approach would require significant searching, causing it to be slow. 2. (4 pts) We will first write a method that determines if a given Node is touching a Student. Write the istouching method in the Student class: /* preconditions: the touchingnodes field is properly * set up to hold all the Nodes that * are touching us. * postconditions: the touchingnodes field is unchanged; * returns true if the node n is * touching, and false otherwise public boolean istouching(node n) 3

3. (4 pts) What is the running time of the istouching method? Let T be the number of nodes stored in touchingnodes and let L be the length of the list referred to by n. A. O(1) B. O(T) C. O(TL) D. O(L) E. O(T 2 ) The remaining methods to write are in neither the Student nor the DevilsSnare classes. The actual location of the methods is irrelevant. 4

4. (16 pts) Write a method that takes one tentacle and removes all the nodes touching a given student from that tentacle: /* preconditions: head refers to the head of a list of * Node objects; stu refers to a * proper Student object * postconditions: all nodes that are touching stu are * removed; the new head of the list is * returned public Node removetouching(node head, Student stu) 5

5. (4 pts) Write a method that takes a DevilsSnare and frees a student: /* preconditions: all parameters are properly set up * postconditions: all nodes from all lists that are * touching stu are removed. public void freestudent(devilssnare snare, Student stu) 6. (4 pts) There are potentially many students involved. Write a method that will free all of them: /* preconditions: all parameters are set up. * postconditions: all nodes touching any student are * removed. public void freeall(devilssnare snare, List<Student> studs) 6

7. (4 pts) What is the total running time of this method? Let T be the maximum number of nodes stored in one student's touchingnodes; let L be the maximum length of a list representing a tentacle; let S be the number of different tentacles (the size of the heads array); and let H be the number of students involved. A. O(TLSH) B. O(LSH) C. O(TLH) D. O(TSH) E. O(TLS) After successfully escaping from the Devil's Snare, Harry, Ron, and Hermione continue into the next chamber. There, they see a heavy wooden door. Looking up, they see many glittering birds. After Ron discovers the door is locked, Harry suddenly realizes that the flying creatures aren't birds they're keys. The challenge in this chamber is to find the key that fits the door. Harry, Ron, and Hermione all take to brooms to fly about the chamber, searching for the key. Harry suggests binary search, saying, "Ron, you come at it from above Hermione, stay below and I'll try and catch it." 1 1 Harry Potter and the Sorcerer's Stone, by J.K. Rowling, page 280. 7

8. (4 pts) We have a collection of objects of a class Key that we are searching among. What are the requirements in order to use binary search? I. The Keys must be stored in some kind of List or array. II. The class Key must implement the Comparable interface. III. The Keys must be in order. A. I only B. III only C. I and II only D. II and III only E. I, II, and III 9. (4 pts) In planning to use binary search for the key, Harry remembers the following method for binary search from his Algorithms class, taught by Professor Sedgewick. 2 2 Robert Sedgewick, though he has a name vaguely reminiscent of Professor Flitwick at Hogwarts, is a real Computer Science professor who wrote a widely-distributed book on algorithms. 8

/* preconditions: all necessary requirements for * binary search are met * postconditions: the array is unchanged; the index * of value is returned; -1 is * returned if the value is not in the * array 1 public int binarysearch(int[] arr, int value) 2 3 int end = arr.length - 1; 4 int start = 0; 5 int mid = (end + start) / 2; 6 7 while(arr[mid]!= value && end > start) 8 9 if(value > arr[mid]) 10 11 start = mid + 1; 12 13 else 14 15 end = mid; 16 17 18 mid = (end + start) / 2; 19 20 21 if(arr[mid] == value) 22 23 return mid; 24 25 else 26 27 return -1; 28 29 What statement is true about the preceding method? A. It works as specified. B. The method does not work properly; line 11 should read start = mid; C. The method does not work properly; line 13 should read else if(value < arr[mid]) D. The method does not work properly; it will not find the element if value is the first element in the list. E. The method does not work properly; it will not find the element if value is the last element in the list. 9

As it turns out, binary search will not work for finding the key to the locked wooden door something about keys does not meet those requirements you discovered above. Instead, we have a Set<Key> that stores all the keys. Here are relevant class definitions: public class Door public void unlock(rightkey k) /* unlocks door so that our heroes may pass public abstract class Key public abstract void unlockdoor(door d); public class WrongKey extends Key public void unlockdoor(door d) d.unlock(this); public class RightKey extends Key public class unlockdoor(door d) d.unlock(this); 10. (4 pts) What statement is true about the preceding code? (out of scope for CS206 exam, but still something we covered this semester) A. All of the code compiles. B. The keyword this is used improperly in the unlockdoor methods. C. The code will not compile because there is an abstract method in a concrete class. D. The code will not compile because there are no constructors written. E. The code will not compile because of a type mismatch error. 10

11. (6 pts) Write a method that will find the right key among a Set of Keys and return it. Code that contains unnecessary casts will not receive full credit. (out of scope for CS206 exam, but still something we covered this semester) public RightKey findkey(set<key> keys) 12. (6 pts) Write a method that will use findkey to find the key and unlock the door. Code that contains unnecessary casts will not receive full credit. (out of scope for CS206 exam, but still something we covered this semester) public void usekey(set<key> keys, Door d) With the help of those methods, our heroes proceed to the next room. Before them appears a life-size chess board. As the three quickly figure out, they must take the place of three of the black chess pieces and win a chess game to cross the room. To do that, we need to help them figure out how some of the chess pieces move. 11

The chessboard is represented by an 8x8 matrix of ChessPiece elements. Here are some relevant classes: public class Location private int rw; // both rw and cl count from 0 private int cl; // thus, the range is 0.. 7 public int row() return rw; public int col() return cl; public Location(int r, int c) rw = r; cl = c; public abstract class ChessPiece /* other methods, etc. shown below public boolean iswhite() /* implementation not shown public class Chess /* the matrix of chess pieces. Empty squares are denoted by null ChessPiece[][] board = new ChessPiece[8][8]; /* checks whether a location is empty * preconditions: The board is properly set up; loc * is a valid location in the chess * board. * postconditions: the board is unchanged; true is * returned if loc is empty, or false * otherwise private boolean isempty(location loc) /* to be implemented below 12

/* checks whether a location contains a friendly piece * preconditions: The board is properly set up; * iswhite indicates whether the * current player is white or black; * loc is a valid location in the * chess board. * postconditions: the board is unchanged; true is * returned if loc contains a friendly * piece, or false otherwise private boolean containsfriendly(location loc, boolean iswhite) /* to be implemented below /* checks whether a location contains an enemy piece * preconditions: The board is properly set up; * iswhite indicates whether the * current player is white or black; * loc is a valid location in the * chess board. * postconditions: the board is unchanged; true is * returned if loc contains an enemy * piece, or false otherwise private boolean containsenemy(location loc, boolean iswhite) /* to be implemented below /* Compute the Locations a given piece can move to. * preconditions: The board is properly set up; the * piece under consideration can move * in the direction indicated by * rowstep and colstep * postconditions: The chess board is unchanged; a * List of Locations is returned that * contains all possible squares * accessible from the starting * location in the direction given by * rowstep and colstep. public List<Location> getpossibledestinations(location startingloc, int rowstep, int colstep, boolean iswhite) /* to be implemented below 13

13. (4 pts) Write the method isempty. Hint: Yes, this is as simple as it seems. /* checks whether a location is empty * preconditions: The board is properly set up; loc * is a valid location in the chess * board. * postconditions: the board is unchanged; true is * returned if loc is empty, or false * otherwise private boolean isempty(location loc) 14

14. (4 pts) Write the method containsfriendly. This method checks a given location to see if it contains a friendly piece. In other words, this returns true if the location given contains a piece and that piece's color agrees with the iswhite parameter to this method. /* checks whether a location contains a friendly piece * preconditions: The board is properly set up; * iswhite indicates whether the * current player is white or black; * loc is a valid location in the * chess board. * postconditions: the board is unchanged; true is * returned if loc contains a friendly * piece, or false otherwise private boolean containsfriendly(location loc, boolean iswhite) 15

15. (4 pts) Write the method containsenemy. This method is just like containsfriendly, but it returns true for a location containing a piece whose color does not match what is in the iswhite parameter. /* checks whether a location contains an enemy piece * preconditions: The board is properly set up; * iswhite indicates whether the * current player is white or black; * loc is a valid location in the * chess board. * postconditions: the board is unchanged; true is * returned if loc contains an enemy * piece, or false otherwise private boolean containsenemy(location loc, boolean iswhite) 16. (20 pts) Write the getpossibledestinations method. The idea behind this method is that it returns possible destinations for a chess piece. Rooks, Bishops, and Queens move similarly in chess, and this method helps simplify their implementation. Any of these pieces move along a line. Depending on the piece, that line can be horizontal, vertical, or along either diagonal. The line starts at the piece's current location and extends until the end of the board is reached or a non-empty location is reached. If the non-empty location holds a friendly piece, the line ends one square before it; if the non-empty location holds an enemy piece, the line ends on that square (and the enemy piece is liable to be captured). Here is an illustration, using a Rook, which can move along any vertical or horizontal line: 16

Here, the Rook (denoted by the ), can move to any of the shaded squares. It is blocked by the edge of the board on the right and bottom, blocked by a friendly piece on the left, and blocked by an enemy piece above. Note that the Rook can travel to the location the enemy piece occupies, but no further. The Rook cannot travel to the location the friendly piece occupies. The getpossibledestinations method works only along one line. Thus, for a Rook, one would have to call getpossibledestinations four times to collect all possible destinations. The rowstep and colstep parameters control which line is being investigated. For the Rook, we would call getpossibledestinations once with a rowstep of 1 and a colstep of 0; this would get the destinations below the Rook. We would call the method again with 0 and 1 to get the destinations to the right of the Rook. The next call would be with -1 and 0 to get the destinations above, and the last would be 0 and -1 to get the destinations on the left. The order of these calls does not matter. To seek destinations along a diagonal, both the rowstep and colstep parameters would be non-zero. Write the method here. It is worth 4 extra credit points if written recursively. A helper method is unnecessary. 17

/* Compute the Locations a given piece can move to. * preconditions: The board is properly set up; the * piece under consideration can move * in the direction indicated by * rowstep and colstep * postconditions: The chess board is unchanged; a * List of Locations is returned that * contains all possible squares * accessible from the starting * location in the direction given by * rowstep and colstep. private List<Location> getpossibledestinations(location startingloc, int rowstep, int colstep, boolean iswhite) 18

Now that we have a functioning chess board, we must use it to move some of the pieces. Here are the relevant classes: public abstract class ChessPiece // repeated from above private boolean white; // true if white; false if black private Location loc; // current location of piece /* returns true if white; false if black public boolean iswhite() return white; /* returns the current location public Location location() return loc; /* preconditions: The board is properly set up * postconditions: The board is unchanged; a list of * all possible destinations for this * chess piece is returned public abstract List<Location> getalldestinations(chess board); /* other methods not shown public class Rook extends ChessPiece /* a Rook can move vertically or horizontally public List<Location> getalldestinations(chess board) /* to be implemented below /* other methods not shown 19

public class Bishop extends ChessPiece /* a Bishop can move only along either diagonal public List<Location> getalldestinations(chess board) /* to be implemented below /* other methods not shown 17. (6 pts) Write the Rook method getalldestinations. A Rook can move either way along both a horizontal and vertical line. // IN THE Rook CLASS: /* preconditions: The board is properly set up * postconditions: The board is unchanged; a list of * all possible destinations for this * chess piece is returned public List<Location> getalldestinations(chess board) 20

18. (6 pts) Write the Bishop method getalldestinations. A Bishop can either way along either diagonal. // IN THE Bishop CLASS: /* preconditions: The board is properly set up * postconditions: The board is unchanged; a list of * all possible destinations for this * chess piece is returned public List<Location> getalldestinations(chess board) 19. (4 pts) In a method tying all of this together, we use this code: ChessPiece piece = /* code unimportant ; Chess board = /* code unimportant ; List<Location> dests = piece.getalldestinations(board); What statement is true of the preceding code? (out of scope for CS206 exam, but still something we covered this semester) A. This is an example of inheritance. B. This is an example of polymorphism. C. This code contains an implicit upcast. D. This code will not work; it calls an abstract method. E. This code will not work; it causes a ClassCastException. 21

Using the above methods, our Harry, Ron, and Hermione take the place of a Rook, a Knight, and a Bishop, and they battle it out to cross the room. In the course of the game, Ron tragically sacrifices himself to win. Victorious but shaken, Harry and Hermione pass through the darkened door into the next chamber. There, in the dim light, they start to make out a strange but familiar sight. A voice rings out. TO BE CONTINUED Image credits: Harry Potter logo: http://toysinaction.nl/oscommerce/catalog/images/harry_potter-logo_90894o.jpg Harry Potter font: http://www.mugglenet.com/downloads/fonts/files/lumos.zip Golden snitch: http://www.encyclopedie-hp.org/images/sva/snitch2-sva.gif Hat: http://www.badgersden.com/general_store/garb/hats/hp/lu2230.jpg 22