Implementing the 8-puzzle Design (no corresponding text chapter)

Slides:



Advertisements
Similar presentations
Chapter 5 Implementing a simple class. This chapter discusses n Implementing class definitions. n How to store data in an object and how to write method.
Advertisements

Chapter 4 Constructors and Destructors. Objectives Constructors – introduction and features The zero-argument constructor Parameterized constructors Creating.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Chapter 15: Operator Overloading
Refactoring and Reuse (Chapter 12). The System As It Stands ProblemSolverQueue ActionListActionItemPriorityQueueFrontQueue RearQueue State MaxPriorityQueueMinPriorityQueue.
C++ fundamentals.
1 CSC241: Object Oriented Programming Lecture No 07.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
More About Classes Chapter Instance And Static Members instance variable: a member variable in a class. Each object has its own copy. static variable:
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Pointer Data Type and Pointer Variables
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
OOD Case Study (For parallel treatment, see Chapter 2 of the text)
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Pointer Data Type and Pointer Variables. Objectives: Pointer Data Type and Pointer Variables Pointer Declaration Pointer Operators Initializing Pointer.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
Pointer. What is pointer ? A Pointer is nothing but a variable that contains an address which is a location of another variable in memory. If one variable.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review Part-I.
CPS120: Introduction to Computer Science Functions.
Overview of Previous Lesson(s) Over View .NET Framework is a software framework developed by Microsoft that runs primarily on Microsoft Windows.  It.
Pointers, Variables, and Memory. Variables and Pointers When you declare a variable, memory is allocated to store a value. A pointer can be used to hold.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Operator Overloading Operator Overloading allows a programmer to define new uses of the existing C/C++ operator symbols. –useful for defining common operations.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Pointers. What is pointer l Everything stored in a computer program has a memory address. This is especially true of variables. char c=‘y’; int i=2; According.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14: More About Classes.
SEEM Java – Basic Introduction, Classes and Objects.
DCT1063 Programming 2 CHAPTER 1 POINTERS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Recursion.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
1 CSC 221: Computer Programming I Fall 2005 simple conditionals and expressions  if statements, if-else  increment/decrement, arithmetic assignments.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
1 2/2/05CS250 Introduction to Computer Science II Pointers.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
6 th week Spring 2011 Midterm Review 1. Primitive Types vs. Reference Types Java’s types: primitive types and reference types. Primitive types: boolean,
CCSA 221 Programming in C CHAPTER 11 POINTERS ALHANOUF ALAMR 1.
1 CSC241: Object Oriented Programming Lecture No 08.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
You learned how to declare pointer variables how to store the address of a variable into a pointer variable of the same type as the variable how to manipulate.
Pointers and Dynamic Arrays
More About Objects and Methods
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Java Primer 1: Types, Classes and Operators
2.5 Another Java Application: Adding Integers
Pointers and References
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Stacks.
Presentation transcript:

Implementing the 8-puzzle Design (no corresponding text chapter)

Possible Implementation of StateInfo Class Suppose your StateInfo class for the 8-puzzle looks like: class StateInfo { private:... public:... State blankUp(); State blankDown(); State blankLeft(); State blankRight();... }

solve() Pseudocode Revisited void solve() current = get start state from problem final = get final state from problem alist = get action list from problem count = 0 while current is not final do display current action = get action from user if action is valid then new = apply action to current current = new increment count else issue message display current and count congratulate Recall the pseudocode for SolverInfo::solve() :

Possible Implementation of solve() Suppose the pseudocode in bold were implemented as follows:... String actionName = promptActionName(); if (strcmp(actionName,"up") == 0) newState = currentState->blankUp(); else if (strcmp(actionName,"down") == 0) newState = currentState->blankDown(); else if (strcmp(actionName,"left") == 0) newState = currentState->blankLeft(); else if (strcmp(actionName,"right") == 0) newState = currentState->blankRight(); else cout << "action " << actionName << " is not recognized." << endl;...

Problems With The Implementation  Recall a design goal for this program:  Only the ProblemInfo and StateInfo classes should know any details about the problem domain  The SolverInfo class should be applicable to domains other than the 8-puzzle  Does the solve() method, as implemented, meet this goal? No.  We therefore introduce the classes Action and ActionList to act as a layer of abstraction between the solver and the domain.

A Better Approach  Wrap each of the methods StateInfo::blankUp(), StateInfo::blankDown(), etc., in a new Action object.  Put each of these Action s onto an ActionList object to which the solver has access.  Provide a method in the ActionList class that will search for and return the Action corresponding to the string entered by the user.  Provide a method in the Action class that will execute its tile-moving operation on a given State.

A Better Implementation of solve()... String actionName = promptActionName(); Action action = actionList->findAction(actionName); if (action == NULL) { cout << "action " << actionName << " is not recognized." << endl; } else { State newState = action->execute(currentState);... }... Now there are no references to any details that indicate the domain is the 8-puzzle.

Recall the ActionInfo Class  Data:  Name (up, down, left, right)  Operation to perform the action--What, an operation as data??  Operations:  Create a new action  Execute the action operation ...

Operations As Data in C++ Suppose we want a program calc to behave like this: 64% calc add 25 2 The result is 27 65% calc sub 25 2 The result is 23 66% calc mult 25 2 The result is 50 67% calc div 25 2 The result is 12 68%

Strategy  Develop a class called CalcInfo that has:  Two integer values as data fields  A constructor with two integer arguments  A method calculate with a string argument, either ``add'', ``sub'', ``mult'', or ``div''. This method does the right calculation on its operands based on its argument.  Get the operation and operands from the command line.  Create a CalcInfo object with the operands.  Invoke the calculate method on the object with the operation as argument.

Main Program for calc int main(Integer argc, StringArray operands) { String oper = operands[1]; Integer x = atoi(operands[2]); Integer y = atoi(operands[3]); Calc c = new CalcInfo(x, y); Integer result = c->calculate(oper); cout << "The result is " << result << endl << endl; }

One Implementation of CalcInfo class CalcInfo { private: Integer operand1; Integer operand2; public: CalcInfo(Integer x, Integer y); Integer calculate(String operation); }; CalcInfo::CalcInfo(Integer x, Integer y) { operand1 = x; operand2 = y; }...

One Implementation of CalcInfo (cont'd)... Integer CalcInfo::calculate(String operation) { if (strcmp(operation, "add") == 0) return (operand1 + operand2); else if (strcmp(operation, "sub") == 0) return (operand1 - operand2); else if (strcmp(operation, "mult") == 0) return (operand1 * operand2); else if (strcmp(operation, "div") == 0) return (operand1 / operand2); else return 0; }

CalcInfo Modification Suppose we want to remove the arithmetic details from CalcInfo, to be handled by another class: Integer CalcInfo::calculate(ArithFun fun) { <Apply fun to the operands and return the result> }  This requires:  Being able to treat functions as arguments  Being able to return functions as function values

A New Class: ArithmeticInfo This class will contain the functions (methods) for doing arithmetic that will be passed to the CalcInfo::calculate method: class ArithmeticInfo { public: static Integer add (Integer a, Integer b); static Integer sub (Integer a, Integer b); static Integer mult (Integer a, Integer b); static Integer div (Integer a, Integer b); ArithFun getFun(String oper); };

Notes on Class ArithmeticInfo " The arithmetic methods are static because they are associated with the whole class and not class instances:  A nonstatic method is called using the obj->method(...) syntax, but  In this case there is no obj involved, because the method is passed to another object, where it is called as if it were a straight C function.  The ArithmeticInfo::getFun(...) method determines the right static method to pass, given a string parameter. It is not static because we are going to ask an ArithmeticInfo object to invoke it.

ArithmeticInfo::getFun Method ArithFun ArithmeticInfo::getFun(String oper) { if (strcmp(oper,"add") == 0) return add; else if (strcmp(oper,"sub") == 0) return sub; else if (strcmp(oper,"mult") == 0) return mult; else // assume must be "div" return div; } Note that we are returning a static method (function) name. So what is the type ArithFun ?

Pointer to void ( void * ) In C/C++  add, sub, etc., are function names, and thus address places in memory. " An address in C/C++ is just a pointer.  To indicate a pointer to a function as the return type for ArithmeticInfo::getFun(), we use an all- encompassing type called pointer to void, or void *  void * means pointer to anything, including pointer to integer, pointer to class object, or pointer to function (static method)  To simplify: typedef void * ArithFun;

New Main Program for calc int main(Integer argc, StringArray operands) { String oper = operands[1]; Arithmetic a = new ArithmeticInfo(); ArithFun f = a->getFun(oper); Integer x = atoi(operands[2]); Integer y = atoi(operands[3]); Calc c = new CalcInfo(x, y); Integer result = c->calculate(f); cout << "The result is " << result << endl << endl; } Now we just need to change CalcInfo::calculate to accept a function as an argument, and then apply it.

Functions Passed as Arguments in C/C++ Integer CalcInfo::calculate(ArithFun fun) { <Apply fun to the operands and return the result> }  The argument fun is of type void * " We must cast it to the proper type before using it: 1. Declare a local variable f of the proper type, 2. Cast fun to f, 3. Apply f to the operands and return the result.

Functions Passed as Arguments in C/C++ (cont'd) " Q: So what is the ``proper type''?  A: A function with two Integer arguments that returns an Integer result:  Integer (*) (Integer, Integer)  This is just a type. It can be read as: ``Pointer to a function that takes two integer arguments and returns an integer as a result''.  To declare a variable f of this type:  Integer (*f) (Integer, Integer)

Final Version of CalcInfo::calculate Integer CalcInfo::calculate(ArithFun fun) { Integer (*f) (Integer, Integer); f = (Integer (*) (Integer, Integer))fun; return (*f)(operand1, operand2); } Note that f is a pointer to the function, so *f must be used to refer to the function itself. Also, the parentheses (*f) are necessary since the function operator f(..) has higher precedence than the indirection operator *.

Recall Possible Implementation of StateInfo Class class StateInfo { private:... public:... State blankUp(); State blankDown(); State blankLeft(); State blankRight();... }

New Implementation of StateInfo  The tile-moving methods must be made static, since they will be passed to the ActionInfo constructor, and  They must have an argument of type State, since they are static. class StateInfo { private:... public:... static State blankUp(State s); static State blankDown(State s); static State blankLeft(State s); static State blankRight(State s);... }

Recall the ActionInfo Class (yet again)  Data:  Name (up, down, left, right)  Operation to perform the action  Operations:  Create a new action  Execute the action operation ...

An ActionInfo Class Declaration " Q: What is the type of the action operation?  A: Look at the signatures of the static tile- moving methods in StateInfo :  State (*) (State, State) class ActionInfo { private: String name; State (*actionFun) (State state); public: ActionInfo(String n, State (*fun) (State state)); State execute(State state); String getName(); };

ActionInfo Class Constructor ActionInfo::ActionInfo(String n, State (*fun) (State state)) { name = n; actionFun = fun; } Q: Who calls the ActionInfo constructor?

Recall The Problem Class Problem -startState: State -finalState: State -actionList: ActionList +Problem(startTileNums: StringArray) +getStartState(): State +getFinalState(): State +getActionList(): ActionList -createActionList(): void Each action is stored in the ProblemInfo object's ActionList data variable.

The ActionListInfo Class  An ActionListInfo object is just a collection of ActionInfo objects.  In this design, it is created by the ProblemInfo class for use by the solver. " The solver gets the action list from the problem and uses it to find the action matching the user's input.

Recall the Implementation of solve()... String actionName = promptActionName(); Action action = actionList->findAction(actionName); if (action == NULL) { cout << "action " << actionName << " is not recognized." << endl; } else { State newState = action->execute(currentState);... }...

Executing the Action State ActionInfo::execute(State state) { return (*actionFun)(state); } When the Action object is found, it applies its stored, static, tile-moving method to the current state: However, note that the ActionInfo class knows nothing about the details of the state-changing methods it executes. For all it knows, it could be executing actions in domains other than the 8-puzzle.