1 A Brief Introduction to the Game of Life. 2 Example demonstration ——game of life  Definition  It takes place on an unbounded rectangular grid in which.

Slides:



Advertisements
Similar presentations
Annoucements  Next labs 9 and 10 are paired for everyone. So don’t miss the lab.  There is a review session for the quiz on Monday, November 4, at 8:00.
Advertisements

Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Data Structures Chapter 1 Programming Principles Andreas Savva.
嵌入式操作系统 陈香兰 Fall 系统调用 10/27/09 嵌入式 OS 3/12 系统调用的意义  操作系统为用户态进程与硬件设备进行交互提供 了一组接口 —— 系统调用  把用户从底层的硬件编程中解放出来  极大的提高了系统的安全性  使用户程序具有可移植性.
Viterbi 算法 viterbi 实验要求:见 experiment3.doc – 将 TRUNC_LENGTH 取值为 4 , 8 , 16 , 32 , 64 ,看看程序运行结果会有什么变化并分析原 因。 – 将 NUMSIM 取值为 10 1 , 10.
1 为了更好的揭示随机现象的规律性并 利用数学工具描述其规律, 有必要引入随 机变量来描述随机试验的不同结果 例 电话总机某段时间内接到的电话次数, 可用一个变量 X 来描述 例 检测一件产品可能出现的两个结果, 也可以用一个变量来描述 第五章 随机变量及其分布函数.
Chapter1 PROGRAMMING PRINCIPLES. Problems of Large Programs 1.The patchwork approach --- Disadvantage: if any change must be made, it will have unpredictable.
第 4 章 过程与变量的作用范围. 4.1 Visual Basic 的代码模块 Visual Basic 的应用程序是由过程组成的, 过程代码存放在模块中。 Visual Basic 提供了 三类模块,它们是窗体模块、标准模块和类 模块。 窗体模块 窗体模块是大多数 Visual Basic.
实验三: 用双线性变换法设计 IIR 数字滤波器 一、实验目的 1 熟悉用双线性变换法设计 IIR 数字滤波器的原理与方法。 2 掌握数字滤波器的计算机仿真方法。 3 通过观察对实际心电图信号的滤波作用, 获得数字滤波的感性知 识。
第二章 贝叶斯决策理论 3学时.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
编译原理总结. 基本概念  编译器 、解释器  编译过程 、各过程的功能  编译器在程序执行过程中的作用  编译器的实现途径.
 符号表  标识符的作用: 声明部分:定义了各种对象及对应的属性和 使用规则。 程序体:对所定义的对象进行各种操作。 $ididname IdnameAttributeIR  必要性 Token : 新表-符号表(种类、类型等信息):
PRE-PROGRAMMING PHASE
Basic Elements of C++ Chapter 2.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Simple Program Design Third Edition A Step-by-Step Approach
สาขาวิชาเทคโนโลยี สารสนเทศ คณะเทคโนโลยีสารสนเทศ และการสื่อสาร.
1 Chapter 1 Data structure and Programming Principles.
College of Computer and Information Science Chapter 14 Programming and Languages.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 1 PROGRAMMING PRINCIPLES 1. Introduction : Problems with large programs 2.The Game of Life (a continuing example) 3. Programming style 4. Coding,
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
1 Data Structures CSCI 132, Spring 2014 Lecture 3 Programming Principles and Life Read Ch. 1.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Describe the Program Development Cycle. Program Development Cycle The program development cycle is a series of steps programmers use to build computer.
Kruse/Ryba Ch011 Object Oriented Data Structures Programming Principles Introduction Programming Style Coding, Testing, Further Refinement Program Maintenance.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
1 Data Structures CSCI 132, Spring 2014 Lecture 4 Implementing Life.
Programming Principles Chapter 1. Objectives Discuss the program design process. Introduce the Game of Life. Discuss object oriented design. – Information.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
Problem Solving Techniques. Compiler n Is a computer program whose purpose is to take a description of a desired program coded in a programming language.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
Data Structures and Debugging Dr. Nancy Warter-Perez June 18, 2003.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Chapter 3 Programming Languages Unit 1 The Development of Programming Languages.
项目七: PLC 功能指令应用 带进位循环左移指令 XXXXX. 项目七: PLC 功能指令应用 FX2 系列可编程控制器移位控制指令有移位、循环移位、字移位 及先进先出 FIFO 指令等 10 条指令。 带进位循环右移指令 RCR 带进位循环左移指令 RCL 字右移位指令 WSFR 先入先出读出指令.
1 Ch. 1: Software Development (Read) 5 Phases of Software Life Cycle: Problem Analysis and Specification Design Implementation (Coding) Testing, Execution.
7 生产费用在完工产品与在产 品之间分配的核算. 2 第七章 生产费用在完工产品与在产品之 间的分配  知识点 :  理解在产品的概念  掌握生产费用在完工产品与在产品之间的分 配.
Software Development Problem Analysis and Specification Design Implementation (Coding) Testing, Execution and Debugging Maintenance.
力的合成 力的合成 一、力的合成 二、力的平行四边形 上一页下一页 目 录 退 出. 一、力的合成 O. O. 1. 合力与分力 我们常常用 一个力来代替几个力。如果这个 力单独作用在物体上的效果与原 来几个力共同作用在物体上的效 果完全一样,那么,这一个力就 叫做那几个力的合力,而那几个 力就是这个力的分力。
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Data Structure Introduction Dr. Bernard Chen Ph.D. University of Central Arkansas Fall 2010.
参考文献管理软件. 常见参考文献管理软件 : 中文 : CNKI E-learning (目前免费) NoteExpress NoteFirst 英文: Refworks Endnote (网络版免费) Mendeley……
1 Scope Lifetime Functions (the Sequel) Chapter 8.
CISC105 – General Computer Science Class 4 – 06/14/2006.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
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.
Introduction to Computer Programming Concepts M. Uyguroğlu R. Uyguroğlu.
 Problem Analysis  Coding  Debugging  Testing.
Kruse/Ryba Ch011 Object Oriented Data Structures Programming Principles Introduction Programming Style Coding, Testing, Further Refinement Program Maintenance.
《Visual C++程序设计》 软件与通信工程学院 李 刚 QQ: 上课时间:周二567节 上课地点:荟庐W101
Chapter Topics The Basics of a C++ Program Data Types
Introduction To Repetition The for loop
Basic Elements of C++.
Basic Elements of C++ Chapter 2.
Additional Control Structures
Structured Program
Programming Fundamentals (750113) Ch1. Problem Solving
Test Case Test case Describes an input Description and an expected output Description. Test case ID Section 1: Before execution Section 2: After execution.
Programming Fundamentals (750113) Ch1. Problem Solving
Programming Fundamentals (750113) Ch1. Problem Solving
CHAPTER 6 Testing and Debugging.
Presentation transcript:

1 A Brief Introduction to the Game of Life

2 Example demonstration ——game of life  Definition  It takes place on an unbounded rectangular grid in which each cell can either be occupied by an organism or not.  Occupied cells are called alive; unoccupied cells are called dead.  Which cells are alive or not changes from generation to generation according to the number of neighboring cells that are alive, as follows: Rules for the game of life

3 Rules of the Game of life  1. The neighbors of a given cell are the eight cells that touch it vertically, horizontally, or diagonally. Every cell is either living or dead. (only two states)  2. A living cell stays alive in the next generation if it has either 2 or 3 living neighbors; it dies if it has 0, 1, 4, or more living neighbors. (for a living cell, conditions of still living and die)

4 Rules of the Game of life 3. A dead cell becomes alive in the next generation if it has exactly three neighboring cells, no more or fewer, that are already alive. All other dead cells remain dead in the next generation. (for a dead cell when the state will be change?) 4. All births and deaths take place at exactly the same time.

5 A particular arrangement of living and dead cells in a grid is called a configuration. Applying the preceding rules, an initial configuration changes to another at each generation. Configuration

6 Examples Moribund ( 濒死 ) example  By rule 2 and 3, the living cells will die in the coming generation, and no cells will become alive, so the configuration dies out

7 Stable example  Each of the living cells has a neighbor count of three, and hence remain alive, but the dead cells all have neighbor counts of two or less, and hence none of them becomes alive. Examples --2

8 Alternate examples:  The two configurations continue to alternate from generation to generation. Examples --3

9 Variety( 多样化 ) Through many generation, a simple initial configuration  grow into large configurations,  die out,  reach a state where they do not change  Go through a repeating pattern every few generations. Our goal Write a program that will show how an initial configuration will change from generation to generation.

10 the solution: classes,objects and methods  Set up a Life configuration as an initial arrangement of living and dead cells.  Print the Life configuration.  While the user wants to see further generations:  Update the configuration by applying the rules of the Life game.  Print the current configuration.

11 Review of C++ elements  A class collects data and the methods used to access or change the data.  Such a collection of data and methods is called an object belonging to the given class.  Every C++ class consists of members that represent either variables (called data members) or functions (called methods or member functions). The member functions of a class are normally used to access or alter the data members. Example: For the Life game, Class: Life class Object: a configuration Method: initialize(), update(),print()

12  By relying on its specifications, a client can use a method without needing to know how the data are actually stored or how the methods are actually programmed. This important programming strategy known as information hiding.  Data members and methods available to a client are called public; further private variables and functions may be used in the implementation of the class, but are not available to a client. Convention (约定) Methods of a class are public. Functions in a class are private. Review of C++ elements

13 Life: The Main Program #include “utility.h” //page #include “life.h“//life 类的定义部分 int main( ) // Program to play Conway's game of Life. /*Pre: The user supplies an initial configuration of living cells. Post: The program prints a sequence of pictures showing the changes in the configuration of living cells according to the rules for the game of Life. Uses: The class Life and its methods initialize( ),print( ), and update( ).The functions instructions( ),user_ says_ yes( ). */

14 { Life configuration; instructions( ); configuration.initialize( ); configuration.print( ); cout << "Continue viewing new generations? " << endl; while (user_says_yes( )) { configuration.update( ); configuration.print( ); cout << "Continue viewing new generations? " << endl; }

15 Utility Package(p678) We shall assemble a utility package that contains various declarations and functions that prove useful in a variety of programs, even though these are not related to each other as we might expect if we put them in a class. For example, we shall put declarations to help with error processing in the utility package. Our first function for the utility package obtains a yes-no response from the user: bool user_says_ yes( ) Pre: None. Post: Returns true if the user enters ‘y’ or ‘Y’; returns false if the user enters ‘n’ or ‘N’; otherwise requests new response

16  Clients, that is, user programs with access to a particular class, can declare and manipulate objects of that class. For example:declare a Life object by: Life configuration;  member selection operator We can now apply methods to work with configuration, using the C++ operator. For example, we can print out the data in configuration by writing: configuration.print( );  The specifications of a method, function, or program are statements of precisely what is done. Preconditions state what is required before; postconditions state what has happened when the method, function, or program has finished. Programming Precept Include precise specifications with every program, function, and method that you write. Other C++ elements

17 Programming Style( 自学 page 10-20)  Names (命名) : Guidelines of names: see p11-12  Documentation and Format (文档化和书写格式) o Some commonly accepted guidelines: see p13  Refinement and Modularity (求精和模块化) : o Top-down refinement

18 o As we write the main program,we decide exactly how the work will be divided among them.,how to divide the work? 自学

19 o Data Categories  Input parameters--passed by value or by reference(const)  Output parameters—passed by reference (suggest)  Inout parameters---used for both input and output  Local variables—defined in the function and exist only while the function is being executed.  Global variables----dangerous, cause side effect

20

21 Coding, Testing and Further Refinement Coding (编码) :writing an algorithm in the correct syntax of a computer language like C++ Testing (测试) :running the program on sample data chosen to find errors Further Refinement (进一步细化) :turn to the functions not yet written and repeat these steps

22 Example demonstration ——game of life  Coding Coding 1.Stubs (占位程序) To compile each function and class separately To compile the main program correctly, there must be something in the place of each function that is used, so put in short, dummy functions.——which named stubs the simplest stubs are those that do little or nothing at all: void instruction() {} bool user_says_yes(){ return false;}

23 Coding of game of life 2.Definition of the class Life const int maxrow=20,maxcol=60; //living cells 共有 20 行, 60 列 class Life{// 存放在 *.h 文件中的类体声明 public: void initialize(); // 初始化 living cells 的状态 void print(); // 打印输出当前 living cells 的状态 void update(); // 进行 dead  living 间的转换 private: int grid[maxrow+2][maxcol+2]; // 借助两维数组存放 living cells // 注意:为处理一致,添加了虚拟的 2 行 2 列,放围墙 int neighbor_count(int row,int col); // 统计邻居 cell 的状态 };

24 Stub example2: To check if the class definition is correct, We should supply the following stubs for its methods in life.cpp: void Life :: initialize( ) {} void Life :: print( ) {} void Life :: update( ) {}

25 Instructions void instructions( ) /* Pre: None. Post: Instructions for using the Life program have been printed. */ { cout << "Welcome to Conway’s game of Life." << endl; cout << "This game uses a grid of size " << maxrow << " by " << maxcol << " in which each" << endl; cout << "cell can either be occupied by an organism or not." << endl; cout << "The occupied cells change from generation to generation"<< endl; cout << "according to how many neighboring cells are alive."<< endl; }

26 user_says_yes( ) bool user_says_yes( ) { int c; bool initial_response = true; do { // Loop until an appropriate input is received. if (initial_response) cout << " (y,n)? " << flush; else cout << "Respond with either y or n: " << flush; do { // Ignore white space. c = cin.get( ); } while (c == ‘\n’ || c == ‘ ’ || c == ‘\t’); initial_response = false; } while (c != ‘y‘ && c != ‘Y‘ && c != ‘n‘ && c != ‘N‘); return (c == ‘y‘ || c == ‘Y‘); }

27 Functions and Methods of class Life 3.Counting neighbors:  sentinel (岗哨) (hedge): A sentinel is an extra entry put into a data structures so that boundary conditions need not be treated as a special case. int Life::neighbor_count(int row,int col){ int i,j,count=0; for (i=row-1;i<=row+1;i++) for (j=col-1;j<=col+1;j++) count+=grid[i][j]; // 如果存活,则累加;否则为 0 count-=grid[row][col]; // 去除自己 return count; }

28

29 Functions and Methods of Class Life 4.Updating the grid void Life::update(){ int row,col,new_grid[maxrow+2][maxcol+2]; for (row=1;row<=maxrow;row++) for (col=1;col<=maxcol;col++) switch(neighbor_count(row,col)){// 调用统计函数, 按结果分情况 case 2: new_grid[row][col]=grid[row][col]; break;// 不变 case 3: new_grid[row][col]=1; break; // 激活 default: new_grid[row][col]=0; //dead } for (row=1;row<=maxrow;row++) for (col=1;col<=maxcol;col++) grid[row][col]=new_grid[row][col];// 将临时数组中的数据拷贝回原 grid 数组 }

30 Functions and Methods of Class Life 5.Input and Output:

31 Functions and Methods of Class Life  Input——initialize void Life::initialize(){ int row,col; for (row=0;row<=maxrow+1;row++) for (col=0;col<=maxcol+1;col++) grid[row][col]=0; cout<<“List the coordinates for living cells.”<<endl; cout<<“Terminate the list with the special pair (-1,-1)”<<endl; cin>>row>>col; while (row!=-1||col!=-1){ if (row>=1&&row<=maxrow) if (col>=1&&col<=maxcol) grid[row][col]=1; else cout<<“Column “<<col<<“ is out of range.”<<endl; else cout<<“Row “<<row<<“ is out of range.”<<endl; cin>>row>>col; }

32 Functions and Methods of class Life  Output——print: void Life::print(){ int row,col; cout<<“\nThe current Life configuration is: “<<endl; for (row=1;row<=maxrow;row++){ for (col=1;col<=maxcol;col++) if (grid[row][col]==1) cout<<“ * ”; else cout<<“ ”; cout<<endl; } cout<<endl; }

33 Functions and Methods of Class Life 6.Drivers: Driver is a short auxiliary program whose purpose is to provide the necessary input for the function, and evaluate the result——so that each function can be isolated and studied by itself.

34 Example 1:driver for neighbor_ count(): int main ( ) // driver for neighbor_count( ) /* Pre: None. Post: Verifies that the method neighbor_count ( ) if it returns the correct values. Uses: The class Life and its method initialize( ). */ { Life configuration; configuration.initialize( ); for (row = 1; row <= maxrow; row++) { for (col = 1; col <= maxrow; col++) cout << configuration.neighbor_count(row, col) << " "; cout << endl; }

35 Example 2 :driver for initialize() and print(): Sometimes two functions can be used to check each other. configuration.initialize( ); configuration.print( ); Both methods can be tested by running this driver and making sure that the configuration printed is the same as that given as input.

36 7.Methods for debugging: (self-study) 1). Structured walkthrough 2). Trace tools and snapshots 3). Scaffolding 4). Static analyzer

37 Example demonstration ——game of life 8.Test(self-study) Principles of program Testing: Black-Box Method (黑盒法) (a) Easy values (b) Typical, realistic values (c) Extreme values (d) Illegal values Glass-Box Method (白盒法) : Trace all the paths through the Program,for a single small method, it is an excellent debugging and test method Ticking-Box Method——Don't do anything Just hope for the best!

38 Action: In practice, black-box testing is usually more effective in uncovering errors. One reason is that most subtle programming errors often occur not within a function but in the interface between functions, in misunderstanding of the exact conditions and standards of information interchange between function.

39 Example demonstration ——game of life  Program Maintenance (self-study) For a large and import program, more than half the work comes in the maintenance phase, after it has been completely debugged, tested, and put into use. First step of program maintenance is to begin the continuing process of review, analysis, and evaluation. (for some useful question, see p34)

40 Example demonstration ——game of life  Program Maintenance Review of the Life program problem specification (问题规范) program correctness (程序纠错) user interface (用户接口) modularity and structure (模块化与结构化) documentation (文档) efficiency (效率) Program revision and redevelopment (修订与发布)

41 Pointers and Pitfalls  1. To improve your program, review the logic. Don't optimize code based on a poor algorithm.  2. Never optimize a program until it is correct and working.  3. Don't optimize code unless it is absolutely necessary.  4. Keep your functions short; rarely should any function be more than a page long.  5.Be sure your algorithm is correct before starting to code.  6. Verify the intricate parts of your algorithm.