数据结构与程序设计C++描述(Kruse著)高等教育出版社_课后答案.

合集下载

数据结构(c语言版)课后习题答案完整版

数据结构(c语言版)课后习题答案完整版

数据结构(c语言版)课后习题答案完整版数据结构(C语言版)课后习题答案完整版一、数据结构概述数据结构是计算机科学中一个重要的概念,用来组织和存储数据,使之可以高效地访问和操作。

在C语言中,我们可以使用不同的数据结构来解决各种问题。

本文将提供完整版本的C语言数据结构的课后习题答案。

二、顺序表1. 顺序表的定义和基本操作顺序表是一种线性表,其中的元素在物理内存中连续地存储。

在C 语言中,我们可以通过定义结构体和使用指针来实现顺序表。

以下是顺序表的一些基本操作的答案:(1)初始化顺序表```ctypedef struct{int data[MAX_SIZE];int length;} SeqList;void InitList(SeqList *L){L->length = 0;}```(2)插入元素到顺序表中```cbool Insert(SeqList *L, int pos, int elem){if(L->length == MAX_SIZE){return false; // 顺序表已满}if(pos < 1 || pos > L->length + 1){return false; // 位置不合法}for(int i = L->length; i >= pos; i--){L->data[i] = L->data[i-1]; // 向后移动元素 }L->data[pos-1] = elem;L->length++;return true;}```(3)删除顺序表中的元素```cbool Delete(SeqList *L, int pos){if(pos < 1 || pos > L->length){return false; // 位置不合法}for(int i = pos; i < L->length; i++){L->data[i-1] = L->data[i]; // 向前移动元素 }L->length--;return true;}```(4)查找顺序表中的元素```cint Search(SeqList L, int elem){for(int i = 0; i < L.length; i++){if(L.data[i] == elem){return i + 1; // 找到元素,返回位置 }}return -1; // 未找到元素}```2. 顺序表习题解答(1)逆置顺序表```cvoid Reverse(SeqList *L){for(int i = 0; i < L->length / 2; i++){int temp = L->data[i];L->data[i] = L->data[L->length - 1 - i]; L->data[L->length - 1 - i] = temp;}}```(2)顺序表元素去重```cvoid RemoveDuplicates(SeqList *L){for(int i = 0; i < L->length; i++){for(int j = i + 1; j < L->length; j++){if(L->data[i] == L->data[j]){Delete(L, j + 1);j--;}}}}```三、链表1. 单链表单链表是一种常见的链式存储结构,每个节点包含数据和指向下一个节点的指针。

数据结构---C语言描述-(耿国华)-高等教育出版社出版-课后习题答案

数据结构---C语言描述-(耿国华)-高等教育出版社出版-课后习题答案

第一章习题答案2、××√3、(1)包含改变量定义的最小范围(2)数据抽象、信息隐蔽(3)数据对象、对象间的关系、一组处理数据的操作(4)指针类型(5)集合结构、线性结构、树形结构、图状结构(6)顺序存储、非顺序存储(7)一对一、一对多、多对多(8)一系列的操作(9)有限性、输入、可行性4、(1)A(2)C(3)C5、语句频度为1+(1+2)+(1+2+3)+…+(1+2+3+…+n)第二章习题答案1、(1)一半,插入、删除的位置(2)顺序和链式,显示,隐式(3)一定,不一定(4)头指针,头结点的指针域,其前驱的指针域2、(1)A(2)A:E、AB:H、L、I、E、AC:F、MD:L、J、A、G或J、A、G(3)D(4)D(5)C(6)A、C3、头指针:指向整个链表首地址的指针,标示着整个单链表的开始。

头结点:为了操作方便,可以在单链表的第一个结点之前附设一个结点,该结点的数据域可以存储一些关于线性表长度的附加信息,也可以什么都不存。

首元素结点:线性表中的第一个结点成为首元素结点。

4、算法如下:int Linser(SeqList *L,int X){ int i=0,k;if(L->last>=MAXSIZE-1){ printf(“表已满无法插入”);return(0);}while(i<=L->last&&L->elem[i]<X)i++;for(k=L->last;k>=I;k--)L->elem[k+1]=L->elem[k];L->elem[i]=X;L->last++;return(1);}5、算法如下:#define OK 1#define ERROR 0Int LDel(Seqlist *L,int i,int k){ int j;if(i<1||(i+k)>(L->last+2)){ printf(“输入的i,k值不合法”);return ERROR;}if((i+k)==(L->last+2)){ L->last=i-2;ruturn OK;}else{for(j=i+k-1;j<=L->last;j++)elem[j-k]=elem[j];L->last=L->last-k;return OK;}}6、算法如下:#define OK 1#define ERROR 0Int Delet(LInkList L,int mink,int maxk){ Node *p,*q;p=L;while(p->next!=NULL)p=p->next;if(mink<maxk||(L->next->data>=mink)||(p->data<=maxk)){ printf(“参数不合法”);return ERROR;}else{ p=L;while(p->next-data<=mink)p=p->next;while(q->data<maxk){ p->next=q->next;free(q);q=p->next;}return OK;}}9、算法如下:int Dele(Node *S){ Node *p;P=s->next;If(p= =s){printf(“只有一个结点,不删除”);return 0;}else{if((p->next= =s){s->next=s;free(p);return 1;}Else{ while(p->next->next!=s)P=p->next;P->next=s;Free(p); return 1;}}}第三章习题答案2、(1)3、栈有顺序栈和链栈两种存储结构。

数据结构---C语言的描述_课后大部分习题答案

数据结构---C语言的描述_课后大部分习题答案

耿国华《数据结构》程序算法课后答案第二章线性表2.4 设线性表存于a(1:arrsize)的前elenum 个分量中且递增有序。

试写一算法,将X 插入到线性表的适当位置上,以保持线性表的有序性。

Status Insert_SqList(SqList &va,int x)//把x 插入递增有序表va 中{if(va.length+1>va.listsize) return ERROR;va.length++;for(i=va.length-1;va.elem[i]>x&&i>=0;i--)va.elem[i+1]=va.elem[i];va.elem[i+1]=x;return OK;}//Insert_SqList2.6 已知线性表中的元素(整数)以值递增有序排列,并以单链表作存储结构。

试写一高效算法,删除表中所有大于mink且小于maxk的元素(若表中存在这样的元素),分析你的算法的时间复杂度(注意:mink和maxk是给定的两个参变量,它们的值为任意的整数)。

Status Delete_Between(Linklist &L,int mink,int maxk)//删除元素递增排列的链表L中值大于mink 且小于maxk 的所有元素{p=L;while(p->next->data<=mink) p=p->next; //p 是最后一个不大于mink 的元素if(p->next) //如果还有比mink 更大的元素{q=p->next;while(q->data<maxk) q=q->next; //q 是第一个不小于maxk 的元素p->next=q;}}//Delete_Between2.7 试分别以不同的存储结构实现线性表的就地逆置算法,即在原表的存储空间将线性表(a, a ..., a )逆置为(a, a ,..., a )。

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案【篇一:数据结构(c语言版)课后习题答案完整版】选择题:ccbdca6.试分析下面各程序段的时间复杂度。

(1)o(1)(2)o(m*n)(3)o(n2)(4)o(log3n)(5)因为x++共执行了n-1+n-2+??+1= n(n-1)/2,所以执行时间为o(n2)(6)o(n)第2章线性表1.选择题babadbcabdcddac 2.算法设计题(6)设计一个算法,通过一趟遍历在单链表中确定值最大的结点。

elemtype max (linklist l ){if(l-next==null) return null;pmax=l-next; //假定第一个结点中数据具有最大值 p=l-next-next; while(p != null ){//如果下一个结点存在if(p-data pmax-data) pmax=p;p=p-next; }return pmax-data;(7)设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。

void inverse(linklist l) { // 逆置带头结点的单链表 l p=l-next; l-next=null; while ( p) {q=p-next; // q指向*p的后继p-next=l-next;l-next=p; // *p插入在头结点之后p = q; }}(10)已知长度为n的线性表a采用顺序存储结构,请写一时间复杂度为o(n)、空间复杂度为o(1)的算法,该算法删除线性表中所有值为item的数据元素。

[题目分析] 在顺序存储的线性表上删除元素,通常要涉及到一系列元素的移动(删第i个元素,第i+1至第n个元素要依次前移)。

本题要求删除线性表中所有值为item的数据元素,并未要求元素间的相对位置不变。

因此可以考虑设头尾两个指针(i=1,j=n),从两端向中间移动,凡遇到值item的数据元素时,直接将右端元素左移至值为item的数据元素位置。

《C语言程序设计》课后习题参考答案

《C语言程序设计》课后习题参考答案

高等院校计算机基础教育规划教材《C++程序设计》课后习题参考答案――武汉大学出版社习题1参考答案一、选择题1. A2. D二、填空题1. BASIC、FORTRAN、AL_GOL60和COBOL2. 83. 关键字4. 编辑、编译、链接和运行三、简答题1.答:(1)C语言具有结构化的控制语句。

C语言提供了结构化程序所必需的基本控制语句,实现了对逻辑流的有效控制。

(2)C语言具有丰富的数据结构类型。

C语言除提供整型、实型、字符型等基本数据类型外,还提供了用基本数据类型构造出的各种复杂的数据结构,如数组、结构、联合等。

C语言还提供了与地址密切相关的指针类型。

此外,用户还可以根据需要自定义数据类型。

(3)C语言具有丰富的运算符。

C语言提供了多达34种运算符,丰富的数据类型与丰富的运算符相结合,使C语言的表达力更具灵活性,同时也提高了执行效率。

(4)C语言简洁、紧凑,使用方便、灵活,程序书写自由,有9种控制语句。

(5)C语言既具有高级语言的功能,又具有低级语言的许多功能,通常被称为中级计算机语言。

它既是成功的系统描述语言,又是通用的程序设计语言。

(6)C语言与汇编语言相比,可移植性好。

(7)功能强大。

C语言具有低级语言的一些功能,所以,生成目标代码质量高,程序执行效率高。

现在许多系统软件都用C语言来描述,可以大大提高了编程效率。

2.答:运行一个C语言程序,一般需要经过如下几个步骤:①上机输入并编辑源程序;②编译源程序;③与库函数连接;④生成可执行目标程序;⑤运行目标程序。

3.答:(1)操作系统的设计与实现。

C语言是一种应用非常广泛的结构化高级程序设计语言,既适合编写应用软件,又适合编写系统软件。

(2)工业控制。

由于C语言具有简洁、灵活、代码效率高、能进行位操作等优点,C语言大量应用在单板机、单片机上,以及嵌入式领域等。

(3)图形图像处理。

C语言在内存管理和进程控制方面有丰富的指令,而且它能提供快速运行的代码,因而C语言适合进行图形程序设计。

数据结构C语言版(第2版)严蔚敏人民邮电出版社课后习题答案之欧阳育创编

数据结构C语言版(第2版)严蔚敏人民邮电出版社课后习题答案之欧阳育创编

数据结构(C语言版)(第2版)课后习题答案李冬梅2015.3目录第1章绪论1第2章线性表6第3章栈和队列18第4章串、数组和广义表36第5章树和二叉树47第6章图60第7章查找75第8章排序89第1章绪论1.简述下列概念:数据、数据元素、数据项、数据对象、数据结构、逻辑结构、存储结构、抽象数据类型。

答案:数据:是客观事物的符号表示,指所有能输入到计算机中并被计算机程序处理的符号的总称。

如数学计算中用到的整数和实数,文本编辑所用到的字符串,多媒体程序处理的图形、图像、声音、动画等通过特殊编码定义后的数据。

数据元素:是数据的基本单位,在计算机中通常作为一个整体进行考虑和处理。

在有些情况下,数据元素也称为元素、结点、记录等。

数据元素用于完整地描述一个对象,如一个学生记录,树中棋盘的一个格局(状态)、图中的一个顶点等。

数据项:是组成数据元素的、有独立含义的、不可分割的最小单位。

例如,学生基本信息表中的学号、姓名、性别等都是数据项。

数据对象:是性质相同的数据元素的集合,是数据的一个子集。

例如:整数数据对象是集合N={0,±1,±2,…},字母字符数据对象是集合C={‘A’,‘B’,…,‘Z’,‘a’,‘b’,…,‘z’},学生基本信息表也可是一个数据对象。

数据结构:是相互之间存在一种或多种特定关系的数据元素的集合。

换句话说,数据结构是带“结构”的数据元素的集合,“结构”就是指数据元素之间存在的关系。

逻辑结构:从逻辑关系上描述数据,它与数据的存储无关,是独立于计算机的。

因此,数据的逻辑结构可以看作是从具体问题抽象出来的数学模型。

存储结构:数据对象在计算机中的存储表示,也称为物理结构。

抽象数据类型:由用户定义的,表示应用问题的数学模型,以及定义在这个模型上的一组操作的总称。

具体包括三部分:数据对象、数据对象上关系的集合和对数据对象的基本操作的集合。

2.试举一个数据结构的例子,叙述其逻辑结构和存储结构两方面的含义和相互关系。

数据结构---C语言的描述_课后大部分习题答案

数据结构---C语言的描述_课后大部分习题答案

第一章答案1.3计算下列程序中x=x+1的语句频度for(i=1;i<=n;i++)for(j=1;j<=i;j++)for(k=1;k<=j;k++)x=x+1;【解答】x=x+1的语句频度为:T(n)=1+(1+2)+(1+2+3)+……+(1+2+……+n)=n(n+1)(n+2)/61. 4试编写算法,求p n(x)=a0+a1x+a2x2+…….+a n x n的值p n(x0),并确定算法中每一语句的执行次数和整个算法的时间复杂度,要求时间复杂度尽可能小,规定算法中不能使用求幂函数。

注意:本题中的输入为a i(i=0,1,…n)、x和n,输出为P n(x0)。

算法的输入和输出采用下列方法(1)通过参数表中的参数显式传递(2)通过全局变量隐式传递。

讨论两种方法的优缺点,并在算法中以你认为较好的一种实现输入输出。

【解答】(1)通过参数表中的参数显式传递优点:当没有调用函数时,不占用内存,调用结束后形参被释放,实参维持,函数通用性强,移置性强。

缺点:形参须与实参对应,且返回值数量有限。

(2)通过全局变量隐式传递优点:减少实参与形参的个数,从而减少内存空间以及传递数据时的时间消耗缺点:函数通用性降低,移植性差算法如下:通过全局变量隐式传递参数PolyValue(){ int i,n;float x,a[],p;printf(“\nn=”);scanf(“%f”,&n);printf(“\nx=”);scanf(“%f”,&x);for(i=0;i<n;i++)scanf(“%f ”,&a[i]); /*执行次数:n次*/p=a[0];for(i=1;i<=n;i++){ p=p+a[i]*x; /*执行次数:n次*/x=x*x;}printf(“%f”,p);}算法的时间复杂度:T(n)=O(n)通过参数表中的参数显式传递float PolyValue(float a[ ], float x, int n){float p,s;int i;p=x;s=a[0];for(i=1;i<=n;i++){s=s+a[i]*p; /*执行次数:n次*/p=p*x;}return(p);}算法的时间复杂度:T(n)=O(n)第二章答案约瑟夫环问题约瑟夫问题的一种描述为:编号1,2,…,n的n个人按顺时针方向围坐一圈,每个人持有一个密码(正整数)。

算法与数据结构C语言版课后习题答案(机械工业出版社)第1章绪论习题参考答案

算法与数据结构C语言版课后习题答案(机械工业出版社)第1章绪论习题参考答案

第1章概论习题参考答案一、基础知识题1.简述下列概念数据,数据元素,数据类型,数据结构,逻辑结构,存储结构,算法。

【解答】数据就是信息得载体,就是描述客观事物得数、字符,以及所有能输入到计算机中并被计算机程序识别与处理得符号得集合。

数据元素就是数据得基本单位。

在不同得条件下,数据元素又可称为元素、结点、顶点、记录等。

数据类型就是对数据得取值范围、数据元素之间得结构以及允许施加操作得一种总体描述。

每一种计算机程序设计语言都定义有自己得数据类型。

“数据结构”这一术语有两种含义,一就是作为一门课程得名称;二就是作为一个科学得概念。

作为科学概念,目前尚无公认定义,一般认为,讨论数据结构要包括三个方面,一就是数据得逻辑结构,二就是数据得存储结构,三就是对数据进行得操作(运算)。

而数据类型就是值得集合与操作得集合,可以瞧作就是已实现了得数据结构,后者就是前者得一种简化情况。

数据得逻辑结构反映数据元素之间得逻辑关系(即数据元素之间得关联方式或“邻接关系”),数据得存储结构就是数据结构在计算机中得表示,包括数据元素得表示及其关系得表示、数据得运算就是对数据定义得一组操作,运算就是定义在逻辑结构上得,与存储结构无关,而运算得实现则依赖于存储结构。

数据结构在计算机中得表示称为物理结构,又称存储结构。

就是逻辑结构在存储器中得映像,包括数据元素得表示与关系得表示。

逻辑结构与计算机无关。

算法就是对特定问题求解步骤得一种描述,就是指令得有限序列。

其中每一条指令表示一个或多个操作。

一个算法应该具有下列特性:有穷性、确定性、可行性、输入与输出。

2。

数据得逻辑结构分哪几种,为什么说逻辑结构就是数据组织得主要方面?【解答】数据得逻辑结构分为线性结构与非线性结构。

(也可以分为集合、线性结构、树形结构与图形即网状结构)、逻辑结构就是数据组织得某种“本质性"得东西:(1)逻辑结构与数据元素本身得形式、内容无关、(2)逻辑结构与数据元素得相对位置无关。

《C语言程序设计》 课后习题答案 高等教育出版社

《C语言程序设计》 课后习题答案 高等教育出版社

《C语言程序设计》课后习题答案高等教育出版社《C语言程序设计》课后习题答案高等教育出版社第一章:C语言概述1. C语言的特点C语言是一种以处理底层任务和系统编程为目标的高级编程语言。

其特点包括语法简洁、执行效率高、可移植性强等。

第二章:C语言基本数据类型1. C语言中的基本数据类型C语言中的基本数据类型包括整型、字符型、浮点型等。

整型可以进一步细分为有符号整型和无符号整型。

第三章:C语言运算符1. C语言中的运算符C语言中常见的运算符包括算术运算符、赋值运算符、关系运算符、逻辑运算符等。

这些运算符用于执行各种数学和逻辑操作。

第四章:C语言控制语句1. C语言中的条件语句C语言提供了if语句和switch语句来实现条件判断。

if语句用于执行基于布尔表达式的条件分支,而switch语句用于根据不同的值执行不同的代码块。

第五章:C语言函数1. C语言中的函数定义和调用函数是C语言中的基本模块,用于封装可重用的代码。

函数定义包括函数返回类型、函数名、参数列表和函数体等部分。

第六章:C语言数组1. C语言中的数组定义和使用数组是一组相同类型的数据元素的集合。

C语言中可以使用数组来存储和操作大量数据。

第七章:C语言指针1. C语言中的指针概念指针是一种变量,它存储了内存地址。

通过指针,可以直接访问和修改对应内存地址中的数据。

第八章:C语言字符串1. C语言中的字符串操作字符串是由一系列字符组成的数据类型。

C语言通过字符数组来表示和操作字符串。

第九章:C语言结构体1. C语言中的结构体定义和使用结构体是一种自定义的复合数据类型,它可以包含多个不同类型的成员变量。

第十章:C语言文件操作1. C语言中的文件读写操作文件操作是一种重要的数据输入和输出方式。

C语言提供了一系列函数来实现文件的读写操作。

总结:通过解答以上习题,我们可以更好地掌握C语言的各个方面,提升我们的编程能力和解决问题的能力。

希望本文对读者有所帮助。

数据结构与算法分析—c语言描述 课后答案

数据结构与算法分析—c语言描述 课后答案
Data Structures and Algorithm Analysis in C (second edition)
Solutions Manual
Mark Allen Weiss Florida International University
Preface Included in this manual are answers to most of the exercises in the textbook Data Structures and Algorithm Analysis in C, second edition, published by Addison-Wesley. These answers reflect the state of the book in the first printing. Specifically omitted are likely programming assignments and any question whose solution is pointed to by a reference at the end of the chapter. Solutions vary in degree of completeness; generally, minor details are left to the reader. For clarity, programs are meant to be pseudo-C rather than completely perfect code. Errors can be reported to weiss@fi. Thanks to Grigori Schwarz and Brian Harvey for pointing out errors in previous incarnations of this manual.

数据结构c 版课后习题解析

数据结构c  版课后习题解析
(6)算法的描述方法通常有()、()、()和()四种,其中,()被称为算法语言。
【解答】自然语言,程序设计语言,流程图,伪代码,伪代码
(7)在一般情况下,一个算法的时间复杂度是()的函数。
【解答】问题规模
(8)设待处理问题的规模为n,若一个算法的时间复杂度为一个常数,则表示成数量级的形式为(),若为2n*log25n+ 8n,则表示成数量级的形式为()。
1.知识结构图
本章的知识结构如图2-1所示,其中第二层的椭圆代表本章的学习主线。
2. 学习要点
本章虽然讨论的是线性表,但涉及的许多问题都具有一定的普遍性,因此,本章是本课程的重点之一,也是其它后续章节的重要基础。
对于本章的学习要从两条明线、一条暗线出发。两条明线是线性表的逻辑结构和存储结构,一条暗线是算法(即基本操作的实现)。注意线性表的ADT定义、顺序表类定义和单链表类定义三者之间的关系;注意在不同的存储结构下,相同操作的不同实现算法;注意对顺序表和链表从时间性能和空间性能等方面进行综合对比,在实际应用中能为线性表选择或设计合适的存储结构。
【分析】操作示意图如图2-9所示:
⑺一个具有n个结点的单链表,在指针p所指结点后插入一个新结点的时间复杂度为();在给定值为x的结点后插入一个新结点的时间复杂度为()。
【解答】Ο(1),Ο(n)
【分析】在p所指结点后插入一个新结点只需修改指针,所以时间复杂度为Ο(1);而在给定值为x的结点后插入一个新结点需要先查找值为x的结点,所以时间复杂度为Ο(n)。
(5)可以用()定义一个完整的数据结构。
A数据元素B数据对象C数据关系D抽象数据类型
【解答】D
【分析】抽象数据类型是一个数据结构以及定义在该结构上的一组操作的总称。

数据结构(c语言版)课后习题答案完整版资料

数据结构(c语言版)课后习题答案完整版资料

第1章绪论5.选择题:CCBDCA6.试分析下面各程序段的时间复杂度。

(1)O(1)(2)O(m*n)(3)O(n2)(4)O(log3n)(5)因为x++共执行了n-1+n-2+……+1= n(n-1)/2,所以执行时间为O(n2)(6)O(n)第2章线性表1.选择题babadbcabdcddac2.算法设计题(6)设计一个算法,通过一趟遍历在单链表中确定值最大的结点。

ElemType Max (LinkList L ){if(L->next==NULL) return NULL;pmax=L->next; //假定第一个结点中数据具有最大值p=L->next->next;while(p != NULL ){//如果下一个结点存在if(p->data > pmax->data) pmax=p;p=p->next;}return pmax->data;(7)设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。

void inverse(LinkList &L) {// 逆置带头结点的单链表 Lp=L->next; L->next=NULL;while ( p) {q=p->next; // q指向*p的后继p->next=L->next;L->next=p; // *p插入在头结点之后p = q;}}(10)已知长度为n的线性表A采用顺序存储结构,请写一时间复杂度为O(n)、空间复杂度为O(1)的算法,该算法删除线性表中所有值为item的数据元素。

[题目分析] 在顺序存储的线性表上删除元素,通常要涉及到一系列元素的移动(删第i个元素,第i+1至第n个元素要依次前移)。

本题要求删除线性表中所有值为item的数据元素,并未要求元素间的相对位置不变。

因此可以考虑设头尾两个指针(i=1,j=n),从两端向中间移动,凡遇到值item的数据元素时,直接将右端元素左移至值为item的数据元素位置。

数据结构及应用算法教程参考答案

数据结构及应用算法教程参考答案

第1章绪论1.1 简述下列术语:数据,数据元素、数据对象、数据结构、存储结构、数据类型和抽象数据类型。

解:数据是对客观事物的符号表示。

在计算机科学中是指所有能输入到计算机中并被计算机程序处理的符号的总称。

数据元素是数据的基本单位,在计算机程序中通常作为一个整体进行考虑和处理。

数据对象是性质相同的数据元素的集合,是数据的一个子集。

数据结构是相互之间存在一种或多种特定关系的数据元素的集合。

存储结构是数据结构在计算机中的表示。

数据类型是一个值的集合和定义在这个值集上的一组操作的总称。

抽象数据类型是指一个数学模型以及定义在该模型上的一组操作。

是对一般数据类型的扩展。

1.2 试描述数据结构和抽象数据类型的概念与程序设计语言中数据类型概念的区别。

解:抽象数据类型包含一般数据类型的概念,但含义比一般数据类型更广、更抽象。

一般数据类型由具体语言系统内部定义,直接提供给编程者定义用户数据,因此称它们为预定义数据类型。

抽象数据类型通常由编程者定义,包括定义它所使用的数据和在这些数据上所进行的操作。

在定义抽象数据类型中的数据部分和操作部分时,要求只定义到数据的逻辑结构和操作说明,不考虑数据的存储结构和操作的具体实现,这样抽象层次更高,更能为其他用户提供良好的使用接口。

1.3 设有数据结构(D,R),其中,,试按图论中图的画法惯例画出其逻辑结构图。

解:1.4 试仿照三元组的抽象数据类型分别写出抽象数据类型复数和有理数的定义(有理数是其分子、分母均为自然数且分母不为零的分数)。

解:ADT Complex{数据对象:D={r,i|r,i为实数}数据关系:R={<r,i>}基本操作:InitComplex(&C,re,im)操作结果:构造一个复数C,其实部和虚部分别为re和imDestroyCmoplex(&C)操作结果:销毁复数CGet(C,k,&e)操作结果:用e返回复数C的第k元的值Put(&C,k,e)操作结果:改变复数C的第k元的值为eIsAscending(C)操作结果:如果复数C的两个元素按升序排列,则返回1,否则返回0IsDescending(C)操作结果:如果复数C的两个元素按降序排列,则返回1,否则返回0Max(C,&e)操作结果:用e返回复数C的两个元素中值较大的一个Min(C,&e)操作结果:用e返回复数C的两个元素中值较小的一个}ADT ComplexADT RationalNumber{数据对象:D={s,m|s,m为自然数,且m不为0}数据关系:R={<s,m>}基本操作:InitRationalNumber(&R,s,m)操作结果:构造一个有理数R,其分子和分母分别为s和mDestroyRationalNumber(&R)操作结果:销毁有理数RGet(R,k,&e)操作结果:用e返回有理数R的第k元的值Put(&R,k,e)操作结果:改变有理数R的第k元的值为eIsAscending(R)操作结果:若有理数R的两个元素按升序排列,则返回1,否则返回0IsDescending(R)操作结果:若有理数R的两个元素按降序排列,则返回1,否则返回0Max(R,&e)操作结果:用e返回有理数R的两个元素中值较大的一个Min(R,&e)操作结果:用e返回有理数R的两个元素中值较小的一个}ADT RationalNumber1.5 试画出与下列程序段等价的框图。

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案

数据结构与算法分析c语言描述中文答案【篇一:数据结构(c语言版)课后习题答案完整版】选择题:ccbdca6.试分析下面各程序段的时间复杂度。

(1)o(1)(2)o(m*n)(3)o(n2)(4)o(log3n)(5)因为x++共执行了n-1+n-2+??+1= n(n-1)/2,所以执行时间为o(n2)(6)o(n)第2章线性表1.选择题babadbcabdcddac 2.算法设计题(6)设计一个算法,通过一趟遍历在单链表中确定值最大的结点。

elemtype max (linklist l ){if(l-next==null) return null;pmax=l-next; //假定第一个结点中数据具有最大值 p=l-next-next; while(p != null ){//如果下一个结点存在if(p-data pmax-data) pmax=p;p=p-next; }return pmax-data;(7)设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。

void inverse(linklist l) { // 逆置带头结点的单链表 l p=l-next; l-next=null; while ( p) {q=p-next; // q指向*p的后继p-next=l-next;l-next=p; // *p插入在头结点之后p = q; }}(10)已知长度为n的线性表a采用顺序存储结构,请写一时间复杂度为o(n)、空间复杂度为o(1)的算法,该算法删除线性表中所有值为item的数据元素。

[题目分析] 在顺序存储的线性表上删除元素,通常要涉及到一系列元素的移动(删第i个元素,第i+1至第n个元素要依次前移)。

本题要求删除线性表中所有值为item的数据元素,并未要求元素间的相对位置不变。

因此可以考虑设头尾两个指针(i=1,j=n),从两端向中间移动,凡遇到值item的数据元素时,直接将右端元素左移至值为item的数据元素位置。

数据结构与算法分析C版答案

数据结构与算法分析C版答案

Data Structures and Algorithm 习题答案Preface ii1 Data Structures and Algorithms 12 Mathematical Preliminaries 53 Algorithm Analysis 174 Lists, Stacks, and Queues 235 Binary Trees 326 General Trees 407 Internal Sorting 468 File Processing and External Sorting 549Searching 5810 Indexing 6411 Graphs 6912 Lists and Arrays Revisited 7613 Advanced Tree Structures 82iii Contents14 Analysis Techniques 8815 Limits to Computation 94PrefaceContained herein are the solutions to all exercises from the textbook A Practical Introduction to Data Structures and Algorithm Analysis, 2nd edition.For most of the problems requiring an algorithm I have given actual code. Ina few cases I have presented pseudocode. Please be aware that the code presented in this manual has not actually been compiled and tested. While I believe the algorithmsto be essentially correct, there may be errors in syntax as well as semantics. Most importantly, these solutions provide a guide to the instructor as to the intendedanswer, rather than usable programs.1Data Structures and AlgorithmsInstructor’s note: Unlike the other chapters, many of the questions in this chapter are not really suitable for graded work. The questions are mainly intended to get students thinking about data structures issues.This question does not have a specific right answer, provided the student keeps to the spirit of the question. Students may have trouble with the concept of “operations.”This exercise asks the student to expand on their concept of an integer representation.A good answer is described by Project , where a singly-linkedlist is suggested. The most straightforward implementation stores each digitin its own list node, with digits stored in reverse order. Addition and multiplicationare implemented by what amounts to grade-school arithmetic. Foraddition, simply march down in parallel through the two lists representingthe operands, at each digit appending to a new list the appropriate partial sum and bringing forward a carry bit as necessary. For multiplication, combine the addition function with a new function that multiplies a single digitby an integer. Exponentiation can be done either by repeated multiplication (not really practical) or by the traditional Θ(log n)-time algorithm based on the binary representation of the exponent. Discovering this faster algorithm will be beyond the reach of most students, so should not be required.A sample ADT for character strings might look as follows (with the normal interpretation of the function names assumed).Chap. 1 Data Structures and AlgorithmsSomeIn C++, this is 1for s1<s2; 0 for s1=s2;int strcmp(String s1, String s2)One’s compliment stores the binary representation of positive numbers, and stores the binary representation of a negative number with the bits inverted. Two’s compliment is the same, except t hat a negative number has its bits inverted and then one is added (for reasons of efficiency in hardware implementation).This representation is the physical implementation of an ADTdefined by the normal arithmetic operations, declarations, and other support given by the programming language for integers.An ADT for two-dimensional arrays might look as follows.Matrix add(Matrix M1, Matrix M2);Matrix multiply(Matrix M1, Matrix M2);Matrix transpose(Matrix M1);void setvalue(Matrix M1, int row, int col, int val);int getvalue(Matrix M1, int row, int col);List getrow(Matrix M1, int row);One implementation for the sparse matrix is described in Section Another implementationis a hash table whose search key is a concatenation of the matrix coordinates.Every problem certainly does not have an algorithm. As discussed in Chapter 15,there are a number of reasons why this might be the case. Some problems don’t have a sufficiently clear definition. Some problems, such as the halting problem, are non-computable. For some problems, such as one typically studied by artificial intelligence researchers, we simply don’t know a solution.We must assume that by “algorithm” we mean something composed of steps areof a nature that they can be performed by a computer. If so, than any algorithm can be expressed in C++. In particular, if an algorithm can be expressed in any other computer programming language, then it can be expressed in C++, since all (sufficiently general) computer programming languages compute the same set of functions.The primitive operations are (1) adding new words to the dictionary and (2) searching the dictionary for a given word. Typically, dictionary access involves some sort of pre-processing of the word to arrive at the “root” of the word.A twenty page document (single spaced) is likely to contain about 20,000 words. A user may be willing to wait a few seconds between individual “hits” of mis-spelled words, or perhaps up to a minute for the whole document to be processed. This means that a check for an individual word can take about 10-20 ms. Users will typically insert individual words into the dictionary interactively, so this process cantake a couple of seconds. Thus, search must be much more efficient than insertion.The user should be able to find a city based on a variety of attributes (name, location,perhaps characteristics such as population size). The user should also be able to insertand delete cities. These are the fundamental operations of any database system: search, insertion and deletion.A reasonable database has a time constraint that will satisfy the patience of a typicaluser. For an insert, delete, or exact match query, a few seconds is satisfactory. If thedatabase is meant to support range queries and mass deletions, the entire operation may be allowed to take longer, perhaps on the order of a minute. However, the time spent to process individual cities within the range must be appropriately reduced. Inpractice, the data representation will need to be such that it accommodates efficient processing to meet these time constraints. In particular, it may be necessary to supportoperations that process range queries efficiently by processing all cities in the range as a batch, rather than as a series of operations on individual cities.Students at this level are likely already familiar with binary search. Thus, theyshould typically respond with sequential search and binary search. Binary search should be described as better since it typically needs to make fewer comparisons (and thus is likely to be much faster).The answer to this question is discussed in Chapter 8. Typical measures of cost will be number of comparisons and number of swaps. Tests should include running timings on sorted, reverse sorted, and random lists of various sizes.Chap. 1 Data Structures and AlgorithmsThe first part is easy with the hint, but the second part is rather difficult to do withouta stack.a) bool checkstring(string S) {int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’) count++;if (S[i] == ’)’) {if (count == 0) return FALSE;count--;}}if (count == 0) return TRUE;else return FALSE;}b) int checkstring(String Str) {Stack S;int count = 0;for (int i=0; i<length(S); i++)if (S[i] == ’(’)(i);if (S[i] == ’)’) {if ()) return i;();}}if ()) return -1;else return ();}Answers to this question are discussed in Section .This is somewhat different from writing sorting algorithms for a computer, since person’s “working space” is typically limited, as is their ability to physically manipulatethe pieces of paper. Nonetheless, many of the common sorting algorithms have their analogs to solutions for this problem. Most typical answers will be insertion sort, variations on mergesort, and variations on binsort.Answers to this question are discussed in Chapter 8.2Mathematical Preliminaries(a) Not reflexive if the set has any members. One could argue it is symmetric, antisymmetric, and transitive, since no element violate any ofthe rules.(b)Not reflexive (for any female). Not symmetric (consider a brother andsister). Not antisymmetric (consider two brothers). Transitive (for any3 brothers).(c)Not reflexive. Not symmetric, and is antisymmetric. Not transitive(only goes one level).(d)Not reflexive (for nearly all numbers). Symmetric since a+ b= b+ a,so not antisymmetric. Transitive, but vacuously so (there can be nodistinct a, b,and cwhere aRband bRc).(e)Reflexive. Symmetric, so not antisymmetric. Transitive (but sort of vacuous).(f)Reflexive – check all the cases. Since it is only true when x= y,itis technically symmetric and antisymmetric, but rather vacuous. Likewise,it is technically transitive, but vacuous.In general, prove that something is an equivalence relation by proving that it is reflexive, symmetric, and transitive.(a)This is an equivalence that effectively splits the integers into odd andeven sets. It is reflexive (x+ xis even for any integer x), symmetric(since x+ y= y+ x) and transitive (since you are always adding twoodd or even numbers for any satisfactory a, b,and c).(b)This is not an equivalence. To begin with, it is not reflexive for any integer.(c)This is an equivalence that divides the non-zero rational numbers into positive and negative. It is reflexive since x˙x>0. It is symmetric sincexy˙= yx˙. It is transitive since any two members of the given classsatisfy the relationship.5Chap. 2 Mathematical Preliminaries(d)This is not an equivalance relation since it is not symmetric. For example, a=1and b=2.(e)This is an eqivalance relation that divides the rationals based on their fractional values. It is reflexive since for all a,=0. It is symmetricsince if=xthen=.x. It is transitive since any two rationalswith the same fractional value will yeild an integer.(f)This is not an equivalance relation since it is not transitive. For example, 4.2=2and 2.0=2,but 4.0=4.A relation is a partial ordering if it is antisymmetric and transitive. (a)Not a partial ordering because it is not transitive.(b)Is a partial ordering bacause it is antisymmetric (if ais an ancestor ofb, then bcannot be an ancestor of a) and transitive (since the ancestorof an ancestor is an ancestor).(c)Is a partial ordering bacause it is antisymmetric (if ais older than b,then bcannot be older than a) and transitive (since if ais older than band bis older than c, ais older than c).(d)Not a partial ordering, since it is not antisymmetric for any pair of sisters.(e)Not a partial ordering because it is not antisymmetric.(f)This is a partial ordering. It is antisymmetric (no violations exist) and transitive (no violations exist).A total ordering can be viewed as a permuation of the elements. Since there are n!permuations of nelements, there must be n!total orderings.This proposed ADT is inspired by the list ADT of Chapter 4.void clear();void insert(int);void remove(int);void sizeof();bool isEmpty();bool isInSet(int);This proposed ADT is inspired by the list ADT of Chapter 4. Note that whileit is similiar to the operations proposed for Question , the behaviour is somewhat different.void clear();void insert(int);void remove(int);void sizeof();7bool isEmpty();long ifact(int n) {The iterative version requires careful examination to understand whatit does, or to have confidence that it works as claimed.(b)Fibr is so much slower than Fibi because Fibr re-computes thebulk of the series twice to get the two values to add. What is muchworse, the recursive calls to compute the subexpressions also re-computethe bulk of the series, and do so recursively. The result is an exponential explosion. In contrast, Fibicomputes each value in the seriesexactly once, and so its running time is proportional to n.void GenTOH(int n, POLE goal, POLE t1, POLE t2,POLE* curr) {if (curr[n] == goal) Put others on t1.GenTOH(n-1, t1, goal, t2, curr);move(t2, goal);GenTOH(n-1, goal, t1, t2, curr); In theory, this series approaches, but never reaches,0, so it will go on forever. In practice, the value should become computationally indistinguishable from zero, and terminate. However, this is terrible programming practice.Chap. 2 Mathematical Preliminariesvoid allpermute(int array[], int n, int currpos) {if (currpos == (n-1)} {printout(array);return;}for (int i=currpos; i<n; i++) {swap(array, currpos, i);allpermute(array, n, currpos+1);swap(array, currpos, i); The idea is the print out theelements at the indicated bit positions within the set. If we do this for values in the range 0 to 2n.1, we will get the entire powerset.void powerset(int n) {for (int i=0; i<ipow(2, n); i++) {for (int j=0; j<n; j++)if (bitposition(n, j) == 1) cout << j << " ";cout << endl;}Proof: Assume that there is a largest prime number. Call it Pn,the nthlargest prime number, and label all of the primes in order P1 =2, P2 =3,and so on. Now, consider the number Cformed by multiplying all of the nprime numbers together. The value C+1is not divisible by any of the nprime numbers. C+1is a prime number larger than Pn, a contradiction.Thus, we conclude that there is no largest prime number. .Note: This problem is harder than most sophomore level students can handle.√Proof: The proof is by contradiction. Assume that 2is rational. By definition, there exist integers pand qsuch that√p2=,qwhere pand qhave no common factors (that is, the fraction p/qis in lowestterms). By squaring both sides and doing some simple algebraic manipulation, we get2p2=2q222q= pSince p2 must be even, pmust be even. Thus,9222q=4(p)222q=2(p)2This implies that q2 is also even. Thus, pand qare both even, which contra√dicts the requirement that pand qhave no common factors. Thus, 2mustbe irrational. .The leftmost summation sums the integers from 1 to n. The second summation merely reverses this order, summing the numbers from n.1+1=ndown to n.n+1=1. The third summation has a variable substitution ofi, with a corresponding substitution in the summation bounds. Thus,it is also the summation of n.0=nto n.(n.1)=1.Proof:(a) Base case.For n=1, 12 = [2(1)3 +3(1)2 +1]/6=1. Thus, theformula is correct for the base case.(b) Induction Hypothesis.2(n.1)3 +3(n.1)2 +(n.1)i2 =.6i=1(c) Induction Step.i2 i2 +n2=i=1 i=12(n.1)3 +3(n.1)2 +(n.1)2=+n62n3 .6n2 +6n.2+3n2 .6n+3+n.1 2=+n62n3 +3n2 +n=.6Thus, the theorem is proved by mathematical induction. .Proof:(a) Base case.For n=1, 1/2=1.1/2=1/2. Thus, the formula iscorrect for the base case.(b) Induction Hypothesis.11=1..2i=1Chap. 2 Mathematical Preliminaries(c) Induction Step.1 11=+iin222i=1 i=111=1.+n221=1..n2Thus, the theorem is proved by mathematical induction. . Proof:(a) Base case. For n=0, 20 =21 .1=1. Thus, the formula is correctfor the base case.(b) Induction Hypothesis.2i=2n.1.i=0(c) Induction Step.2i=2i+2ni=0 i=0n=2n.1+2n+1 .1=2.Thus, the theorem is proved by mathematical induction. .The closed form solution is 3n+, which I deduced by noting that 3F (n).2n+1 .3F(n)=2F(n)=3. Now, to verify that this is correct, use mathematical induction as follows.For the base case, F(1)=3= .2The induction hypothesis is that =(3n.3)/2.i=1So,3i=3i+3ni=1 i=13n.3n= +32n+1 .33= .2Thus, the theorem is proved by mathematical induction.11nTheorem (2i)=n2 +n.i=1(a) Proof: We know from Example that the sum of the first noddnumbers is ith even number is simply one greater than the ithodd number. Since we are adding nsuch numbers, the sum must be n greater, or n2 +n. .(b) Proof: Base case: n=1yields 2=12 +1, which is true.Induction Hypothesis:2i=(n.1)2 +(n.1).i=1Induction Step: The sum of the first neven numbers is simply the sum of the first n.1even numbers plus the nth even number.2i=( 2i)+2ni=1 i=1=(n.1)2 +(n.1)+2n=(n2 .2n+1)+(n.1)+2n= n2 .n+2n= n2 +n.nThus, by mathematical induction, 2i=n2 +n. .i=1Proof:52Base case. For n=1,Fib(1) = 1 <n=2,Fib(2) = 1 <(5).3Thus, the formula is correct for the base case.Induction Hypothesis. For all positive integers i<n,5 iFib(i)<().3Induction Step. Fib(n)=Fib(n.1)+Fib(n.2)and, by the InductionHypothesis, Fib(n.1)<(5) and Fib(n.3355Fib(n) <() +()3355 5<() +()333Chap. 2 Mathematical Preliminaries85= ()3355<()2()33n5= .3Thus, the theorem is proved by mathematical induction. .Proof:12(1+1)23 =(a) Base case. For n=1, 1=1. Thus, the formula is correct4for the base case.(b) Induction Hypothesis.22(n.1)ni3 = .4i=0(c) Induction Step.n2(n.1)n2i33=+n4i=02n4 .2n3 +n3=+n4n4 +2n3 +n2=4n2(n2 +2n+2)=42n2(n+1)=4Thus, the theorem is proved by mathematical induction..(a) Proof: By contradiction. Assume that the theorem is false. Then, each pigeonhole contains at most 1 pigeon. Since there are nholes, there isroom for only npigeons. This contradicts the fact that a total of n+1pigeons are within the nholes. Thus, the theorem must be correct. .(b) Proof:i. Base case.For one pigeon hole and two pigeons, there must betwo pigeons in the hole.ii. Induction Hypothesis.For npigeons in n.1holes, some holemust contain at least two pigeons.13iii. Induction Step. Consider the case where n+1pigeons are in nholes. Eliminate one hole at random. If it contains one pigeon, eliminate it as well, and by the induction hypothesis some otherhole must contain at least two pigeons. If it contains no pigeons, then again by the induction hypothesis some other hole must contain at least two pigeons (with an extra pigeon yet to be placed). Ifit contains more than one pigeon, then it fits the requirements of the theorem directly..(a)When we add the nth line, we create nnew regions. But, we startwith one region even when there are no lines. Thus, the recurrence is F(n)=F(n.1)+n+1.(b) This is equivalent to the summation F(n)=1+ i=1 ni.(c) This is close to a summation we already know (equation .Base case: T(n.1)=1=1(1+1)/2.Induction hypothesis: T(n.1)=(n.1)(n)/2.Induction step:T(n)= T(n.1)+n=(n.1)(n)/2+n= n(n+1)/2.Thus, the theorem is proved by mathematical induction.If we expand the recurrence, we getT(n)=2T(n.1)+1=2(2T(n.2)+1)+1)=4T(n.2+2+1.Expanding again yieldsT(n)=8T(n.3)+4+2+1.From this, we can deduce a pattern and hypothesize that the recurrence is equivalent tonT(n)= .12i=2n.1.i=0To prove this formula is in fact the proper closed form solution, we use mathematical induction.Base case: T(1)=21 .1=1.14Chap. 2 Mathematical PreliminariesInduction hypothesis: T(n.1)= .1.Induction step:T(n)=2T(n.1)+1= 2 .1) + 1=2n.1.Thus, as proved by mathematical induction, this formula is indeed the correctclosed form solution for the recurrence.(a)The probability is for each choice.(b)The average number of “1” bits is n/2, since each position hasproba bility of being “1.”(c)The leftmost “1” will be the leftmost bit (call it position 0) with probability ; in position 1 with probability , and so on. The numberof positions we must examine is 1 in the case where the leftmost “1” isin position 0; 2 when it is in position 1, and so on. Thus, the expectedcost is the value of the summationni.2ii=1The closed form for this summation is 2 .n+2, or just less than two.2nThus, we expect to visit on average just less than two positions. (Studentsat this point will probably not be able to solve this summation,and it is not given in the book.)There are at least two ways to approach this problem. One is to estimate the volume directly. The second is to generate volume as a function of weight. This is especially easy if using the metric system, assuming that the human body is roughly the density of water. So a 50 Kilo person has a volumeslightly less than 50 liters; a 160 pound person has a volume slightly less than 20 gallons.(a) Image representations vary considerably, so the answer will vary as a result. One example answer is: Consider VGA standard size, full-color(24 bit) images, which is 3 ×640 ×480, or just less than 1 Mbyte perimage. The full database requires some 30-35 CDs.(b)Since we needed 30-35 CDs before, compressing by a factor of 10 isnot sufficient to get the database onto one CD.[Note that if the student picked a smaller format, such as estimating thesize of a “typical” gif image, the result might well fit onto a single CD.](I saw this problem in John Bentley’s Programming Pearls.) Approach 1:The model is Depth X Width X Flow where Depth and Width are in milesand Flow is in miles/day. The Mississippi river at its mouth is about 1/4 mile wide and 100 feet (1/50 mile) deep, with a flow of around 15 miles/hour =360 miles/day. Thus, the flow is about 2 cubic miles/day.Approach 2: What goes out must equal what goes in. The model is Area XRainfall where Area is in square miles and Rainfall is in (linear) miles/day. The Mississipi watershed is about 1000 X 1000 miles, and the average rainfalis about 40 inches/year ≈.1 inches/day ≈.000002 miles/day (2 X .Thus, the flow is about 2 cubic miles/day.Note that the student should NOT be providing answers that look like theywere done using a calculator. This is supposed to be an exercise in estimation! The amount of the mortgage is irrelevant, since this is a question about rates. However, to give some numbers to help you visualize the problem, pick a$100,000 mortgage. The up-front charge would be $1,000, and the savingswould be 1/4% each payment over the life of the mortgage. The monthlycharge will be on the remaining principle, being the highest at first and gradually reducing over time. But, that has little effect for the first few years.At the grossest approximation, you paid 1% to start and will save 1/4% each year, requiring 4 years. To be more precise, 8% of $100,000 is $8,000, while7 3/4% is $7,750 (for the first year), with a little less interest paid (and therefore saved) in following years. This will require a payback period of slightlyover 4 years to save $1000. If the money had been invested, then in 5 yearsthe investment would be worth about $1300 (at 5would be close to 5 1/2years.Disk drive seek time is somewhere around 10 milliseconds or a little lessin 2000. RAM memory requires around 50 nanoseconds – much less thana microsecond. Given that there are about 30 million seconds in a year, a machine capable of executing at 100 MIPS would execute about 3 billionbillion (3 .1018) instructions in a year.Typical books have around 500 pages/inch of thickness, so one million pages requires 2000 inches or 150-200 feet of bookshelf. This would be in excess of 50 typical shelves, or 10-20 bookshelves. It is within the realm of possibility that an individual home has this many books, but it is rather unusual.A typical page has around 400 words (best way to derive this is to estimatethe number of words/line and lines/page), and the book has around 500 pages,so the total is around 200,000 words.16Chap. 2 Mathematical PreliminariesAn hour has 3600 seconds, so one million seconds is a bit less than 300 hours.A good estimater will notice that 3600 is about 10% greater than 3333, so the actual number of hours is about 10% less than 300, or close to 270. (The real value is just under 278). Of course, this is just over 11 days.Well over 100,000, depending on what you wish to classify as a city or town. The real question is what technique the student uses.(a) The time required is 1 minute for the first mile, then 60/59 minutesfor the second mile, and so on until the last mile requires 60/1=60minutes. The result is the following summation.60 6060/i=60 1/i=60H60.i=1 i=1(b)This is actually quite easy. The man will never reach his destination,since his speed approaches zero as he approaches the end of the journey.3Algorithm AnalysisNote that nis a positive integer.5nlog nis most efficient for n=1.2nis most efficient when 2 ≤n≤4.10nis most efficient for all n>5. 20nand 2nare never moreefficient than the other choices.Both log3 nand log2 nwill have value 0 when n=1.Otherwise, 2 is the most efficient expression for all n>1.2/32 3n2 log3nlog2 nn20n4nn!.(a)n+6 inputs (an additive amount, independent of n).(b)8ninputs (a multiplicative factor).(c)64ninputs.100n.10n.√About (actually, 3 100n).n+6.(a)These questions are quite hard. If f(n)=2n= x, then f(2n)=22n=2(2n)2 = x.(b)The answer is 2(nlog2 3). Extending from part (a), we need some way tomake the growth rate even higher. In particular, we seek some way tolog2 3 =make the exponent go up by a factor of 3. Note that, if f(n)= n)=2log2 3log2 3 =3x y, then f(2nn. So, we combine this observationwith part (a) to get the desired answer.First, we need to find constants cand nosuch that 1 ≤c×1 for n>n0.This is true for any positive value c<1 and any positive value of n0 (since nplays no role in the equation).Next, we need to find constants cand n0 such that 1 ≤c×nfor n>n0.This is true for, say, c=1 and n0 =1.1718Chap. 3 Algorithm AnalysisOther values for n0 and care possible than what is given here.(a)The upper bound is O(n) for n0 >0 and c= c1. The lower bound isΩ(n) for n0 >0 and c= c1.(b)The upper bound is O(n3) for n0 >c3 and c= c2 +1. The lowerbound is Ω(n3) for n0 >c3 and c= c2.(c)The upper bound is O(nlog n) for n0 >c5 and c= c4 +1. The lowerbound is Ω(nlog n) for n0 >c5 and c= c4.(d)The upper bound is O(2n) for n0 >c7100 and c= c6 +lower bound is Ω(2n) for n0 >c7100 and c= c6. (100 is used forconvenience to insure that 2n>n6)(a) f(n)=Θ(g(n)) since log n2 = 2 log n.(b)f(n) is in Ω(g(n)) since ncgrows faster than log ncfor any c.(c)f(n) is in Ω(g(n)). Dividing both sides by log n, we see that log n grows faster than 1.(d)f(n) is in Ω(g(n)). If we take both f(n) and g(n) as exponents for 2,2we get 2non one side and 2log2 n=(2log n)2 = n2 on the other, and ngrows slower than 2n.(e)f(n) is in Ω(g(n)). Dividing both sides by log nand throwing awaythe low order terms, we see that ngrows faster than 1.(f)f(n)=Θ(g(n)) since log 10 and 10 are both constants.2(g)f(n) is in Ω(g(n)) since 2ngrows faster than 10n.(h)f(n) is in O(g(n)). 3n=, and if we divide both sides by 2n,we see thatgrows faster than 1.(a) This fragment is Θ(1).(b)This fragment is Θ(n) since the outer loop is executed a constant number。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Programming Principles 11.2 THE GAME OF LIFEExercises 1.2Determine by hand calculation what will happen to each of the configurations shown in Figure 1.1 overthe course of five generations. [Suggestion: Set up the Life configuration on a checkerboard. Use one color of checkers for living cells in the current generation and a second color to mark those that will be born or die in the next generation.]Answer(a)Figure remains stable.(b)(c)(d)Figure is stable.12 Chapter 1 _ Programming Principles(e)(f)Figure repeats itself.(g)(h)(i)Figure repeats itself.(j)(k)(l)Figure repeats itself.Section 1.3 _ Programming Style 31.3 PROGRAMMING STYLEExercises 1.3E1. What classes would you define in implementing the following projects? What methods would your classespossess?(a) A program to store telephone numbers.Answer The program could use classes called Phone_book and Person. The methods for aPhone_bookobject would include look_up_name, add_person, remove_person. The methods for a Person object would include Look_up_number. Additional methods to initialize and print objects ofboth classes would also be useful.(b) A program to play Monopoly.Answer The program could use classes called Game_board, Property, Bank, Player, and Dice. In additionto initialization and printing methods for all classes, the following methods would be useful. The class Game_board needs methods next_card and operate_jail. The class Property needs methods change_owner, look_up_owner, rent, build, mortgage, and unmortgage. The class Bank needs methods pay and collect. The class Player needs methods roll_dice, move_location, buy_property and pay_rent. The class Dice needs a method roll.(c) A program to play tic-tac-toe.Answer The program could use classes called Game_board and Square. The classes need initialization and printing methods. The class Game_board would also need methods make_move andis_game_over. The class Square would need methods is_occupied, occupied_by, and occupy. (d) A program to model the build up of queues of cars waiting at a busy intersection with a traffic light. Answer The program could use classes Car, Traffic_light, and Queue. The classes would all need initializationand printing methods. The class Traffic_light would need additional methods change_statusand status. The class Queue would need additional methods add_car and remove_car.E2. Rewrite the following class definition, which is supposed to model a deck of playing cards, so that itconforms to our principles of style.class a { // a deck of cardsint X; thing Y1[52]; /* X is the location of the top card in the deck. Y1 lists the cards. */ public:a( );void Shuffle( ); // Shuffle randomly arranges the cards.thing d( ); // deals the top card off the deck};Answerclass Card_deck {Card deck[52];int top_card;public:Card_deck( );void Shuffle( );Card deal( );};4 Chapter 1 _ Programming PrinciplesE3. Given the declarationsint a[n][n], i, j;where n is a constant, determine what the following statement does, and rewrite the statement to accomplishthe same effect in a less tricky way.for (i = 0; i < n; i..)for (j = 0; j < n; j..)a[i][j] = ((i . 1)/(j . 1)) * ((j . 1)/(i . 1));Answer This statement initializes the array a with all 0’s except for 1’s down the main diagonal. A less tricky way to accomplish this initialization is:for (i = 0; i < n; i..)for (j = 0; j < n; j..)if (i == j) a[i][j] = 1;else a[i][j] = 0;E4. Rewrite the following function so that it accomplishes the same result in a less tricky way.void does_something(int &first, int &second){first = second −first;second = second −first;first = second . first;}Answer The function interchanges the values of its parameters:void swap(int &first, int &second)/* Pre: The integers first and second have been initialized.Post: The values of first and second have been switched. */{int temp = first;first = second;second = temp;}E5. Determine what each of the following functions does. Rewrite each function with meaningful variablenames, with better format, and without unnecessary variables and statements.(a) int calculate(int apple, int orange){ int peach, lemon;peach = 0; lemon = 0; if (apple < orange)peach = orange; else if (orange <= apple)peach = apple; else { peach = 17;lemon = 19; }return(peach);}Answer The function calculate returns the larger of its two parameters.int larger(int a, int b)/* Pre: The integers a and b have been initialized.Post: The value of the larger of a and b is returned. */{if (a < b) return b;return a;}Section 1.3 _ Programming Style 5(b) For this part assume the declaration typedef float vector[max];float figure (vector vector1){ int loop1, loop4; float loop2, loop3;loop1 = 0; loop2 = vector1[loop1]; loop3 = 0.0;loop4 = loop1; for (loop4 = 0;loop4 < max; loop4..) { loop1 = loop1 . 1;loop2 = vector1[loop1 −1];loop3 = loop2 . loop3; } loop1 = loop1 −1;loop2 = loop1 . 1;return(loop2 = loop3/loop2); }Answer The function figure obtains the mean of an array of floating point numbers. float mean(vector v)/* Pre: The vector v contains max floating point values.Post: The mean of the values in v is returned. */{float total = 0.0;for (int i = 0; i < max; i..)total += v[i];return total/((float) max);}(c) int question(int &a17, int &stuff){ int another, yetanother, stillonemore;another = yetanother; stillonemore = a17;yetanother = stuff; another = stillonemore;a17 = yetanother; stillonemore = yetanother;stuff = another; another = yetanother;yetanother = stuff; }Answer The function question interchanges the values of its parameters.void swap(int &first, int &second)/* Pre: The integers first and second have been initialized.Post: The values of first and second have been switched. */{int temp = first;first = second;second = temp;}(d) int mystery(int apple, int orange, int peach){ if (apple > orange) if (apple > peach) if(peach > orange) return(peach); else if (apple < orange)return(apple); else return(orange); else return(apple); elseif (peach > apple) if (peach > orange) return(orange); elsereturn(peach); else return(apple); }Answer The function mystery returns the middle value of its three parameters.6 Chapter 1 _ Programming Principlesint median(int a, int b, int c)/* Pre: None.Post: Returns the middle value of the three integers a, b, c. */{if (a > b)if (c > a) return a; // c > a > belse if (c > b) return c; // a >= c > belse return b; // a > b >= celseif (c > b) return b; // c > b >= aelse if (c > a) return c; // b >= c > aelse return a; // b >= a >= c}E6. The following statement is designed to check the relative sizes of three integers, which you may assumeto be different from each other:if (x < z) if (x < y) if (y < z) c = 1; else c = 2; elseif (y < z) c = 3; else c = 4; else if (x < y)if (x < z) c = 5; else c = 6; else if (y < z) c = 7; elseif (z < x) if (z < y) c = 8; else c = 9; else c = 10;(a) Rewrite this statement in a form that is easier to read.Answerif (x < z)if (x < y) // x < z and x < yif (y < z) c = 1; // x < y < zelse c = 2; // x < z <= yelse // y <= x < zif (y < z) c = 3; // y <= x < zelse c = 4; // impossibleelse // z <= xif (x < y) // z <= x < yif (x < z) c = 5; // impossibleelse c = 6; // z <= x < yelse // z <= x and y <= xif (y < z) c = 7; // y < z <= x// z <= y <= xif (z < x) // z <= y <= x, z < xif (z < y) c = 8; // z < y <= xelse c = 9; // z == y < x, impossibleelse c = 10; // y <= z == x, impossible(b) Since there are only six possible orderings for the three integers, only six of the ten cases can actuallyoccur. Find those that can never occur, and eliminate the redundant checks.Answer The impossible cases are shown in the remarks for the preceding program segment. After their removal we have:if (x < z)if (x < y) // x < z and x < yif (y < z) c = 1; // x < y < zelse c = 2; // x < z <= yelse c = 3; // y <= x < zelse // z <= xif (x < y) c = 6; // z <= x < yelse // z <= x and y <= xif (y < z) c = 7; // y < z <= xelse c = 8; // z <= y <= xSection 1.3 _ Programming Style 7(c) Write a simpler, shorter statement that accomplishes the same result.Answerif ((x < y) && (y < z)) c = 1;else if ((x < z) && (z < y)) c = 2;else if ((y < x) && (x < z)) c = 3;else if ((z < x) && (x < y)) c = 6;else if ((y < z) && (z < x)) c = 7;else c = 8;E7. The following C++ function calculates the cube root of a floating-point number (by the Newton approximation),using the fact that, if y is one approximation to the cube root of x, thenz . 2y . x=y23cube roots is a closer approximation.float function fcn(float stuff){ float april, tim, tiny, shadow, tom, tam, square; int flag;tim = stuff; tam = stuff; tiny = 0.00001;if (stuff != 0) do {shadow = tim . tim; square = tim * tim;tom = (shadow . stuff/square); april = tom/3.0;if (april*april * april −tam > −tiny) if (april*april*april −tam< tiny) flag = 1; else flag = 0; else flag = 0;if (flag == 0) tim = april; else tim = tam; } while (flag != 1);if (stuff == 0) return(stuff); else return(april); }(a) Rewrite this function with meaningful variable names, without the extra variables that contributenothingto the understanding, with a better layout, and without the redundant and useless statements. Answer After some study it can be seen that both stuff and tam play the role of the quantity x in the formula, tim plays the role of y, and tom and april both play the role of z. The object tiny is asmall constant which serves as a tolerance to stop the loop. The variable shadow is nothing but2y and square is y2 . The complicated two-line if statement checks whether the absolute valuejz3 − xj is less than the tolerance, and the boolean flag is used then only to terminate the loop. Changing all these variables to their mathematical forms and eliminating the redundant ones gives:const double tolerance = 0.00001;double cube_root(double x) // Find cube root of x by Newton method{double y, z;y = z = x;if (x != 0.0)do {z = (y . y . x/(y * y))/3.0;y = z;} while (z * z * z −x > tolerance || x −z * z * z > tolerance);return z;}(b) Write a function for calculating the cube root of x directly from the mathematical formula, by startingwith the assignment y = x and then repeatingy = (2 * y . (x/(y * y)))/3until abs(y * y * y −x) < 0.00001.8 Chapter 1 _ Programming PrinciplesAnswer const double tolerance = 0.00001;double formula(double x) // Find cube root of x directly from formula{double y = x;if (x != 0.0)do {y = (y . y . x/(y * y))/3.0;} while (y * y * y −x > tolerance || x −y * y * y > tolerance);return y;}(c) Which of these tasks is easier?Answer It is often easier to write a program fromscratch than it is to decipher and rewrite a poorly writtenprogram.E8. The mean of a sequence of numbers is their sum divided by the count of numbers in the sequence. Thestatistics (population) variance of the sequence is the mean of the squares of all numbers in thesequence, minusthe square of the mean of the numbers in the sequence. The standard deviation is the square root of the variance. Write a well-structured C++ function to calculate the standard deviation of a sequence of n floating-point numbers, where n is a constant and the numbers are in an array indexed from 0 to n−1, which is a parameter to the function. Use, then write, subsidiary functions to calculate the mean and variance.Answer #include <math.h>double variance(double v[], int n);double standard_deviation(double v[], int n) // Standard deviation of v[]{return sqrt(variance(v, n));}This function uses a subsidiary function to calculate the variance.double mean(double v[], int n);double variance(double v[], int n)// Find the variance for n numbers in v[]{int i;double temp;double sum_squares = 0.;for (i = 0; i < n; i..)sum_squares += v[i] * v[i];temp = mean(v, n);return sum_squares/n −temp * temp;}This function in turn requires another function to calculate the mean.double mean(double v[], int n) // Find the mean of an array of n numbers{int i;double sum = 0.0;for (i = 0; i < n; i..)sum += v[i];return sum/n;}Section 1.3 _ Programming Style 9E9. Design a program that will plot a given set of points on a graph. The input to the program will be a textfile, each line of which contains two numbers that are the x and y coordinates of a point to be plotted. The program will use a function to plot one such pair of coordinates. The details of the function involve plotting the specificmethod of plotting and cannot be written since they depend on the requirements of the plottingequipment, which we do not know. Before plotting the points the program needs to know the maximum and minimum values of x and y that appear in its input file. The program should therefore use another function bounds that will read the whole file and determine these four maxima and minima. Afterward,another function is used to draw and label the axes; then the file can be reset and the individual points plotted.(a) Write the main program, not including the functions.Answer #include <fstream.h>#include "calls.h"#include "bounds.c"#include "draw.c"int main(int argc, char *argv[])// Read coordinates from file and plot coordinate pairs.{ifstream file(argv[1]);if (file == 0) {cout << "Can not open input points file" << endl;cout << "Usage:\n\t plotter input_points " << endl;exit(1);}double xmax, xmin; // bounds for x valuesdouble ymax, ymin; // bounds for y valuesdouble x, y; // x, y values to plotbounds(file, xmax, xmin, ymax, ymin);draw_axes(xmax, xmin, ymax, ymin);file.seekg(0, ios :: beg); // reset to beginning of filewhile (!file.eof( )) {file >> x >> y;plot(x, y);}}(b) Write the function bounds.Answer void bounds(ifstream &file, double &xmax, double &xmin,double &ymax, double &ymin)// determine maximum and minimum values for x and y{double x, y;file >> x >> y;xmax = xmin = x;ymax = ymin = y;while (!file.eof( )) {file >> x >> y;if (x < xmin)xmin = x;if (x > xmax)xmax = x;if (y < ymin)ymin = y;10 Chapter 1 _ Programming Principlesif (y > ymax)ymax = y;}}(c) Write the preconditions and postconditions for the remaining functions together with appropriate documentationshowing their purposes and their requirements.Answer void draw_axes(double xmax, double xmin,double ymax, double ymin)/* Pre: The parameters xmin, xmax, ymin, and xmax give bounds for the x and y co-ordinates. Post: Draws and labels axes according to the given bounds. */{}void plot(double x, double y)/* Pre: The parameters x and y give co-ordinates of a point.Post: The point is plotted to the ouput graph. */{}1.4 CODING, TESTING, AND FURTHER REFINEMENT Exercises 1.4E1. If you suspected that the Life program contained errors, where would be a good place to insert scaffoldinginto the main program? What information should be printed out?Answer Since much of the program’s work is done in neighbor_count, a good place would be within the loops of the update method, just before the switch statement. The values of row, col, and neighbor_count could be printed.E2. Take your solution to Section 1.3, Exercise E9 (designing a program to plot a set of points), and indicategood places to insert scaffolding if needed.Answer Suitable places might be after draw_axes (printing its four parameters) and (with a very small test file to plot) after the call to plot (printing the coordinates of the point just plotted).E3. Find suitable black-box test data for each of the following:(a) A function that returns the largest of its three parameters, which are floating-point numbers. Answereasy values: .1; 2; 3., .2; 3; 1., .3; 2; 1..typical values: .0; 0:5;−9:6., .1:3; 3:5; 0:4., .−2:1;−3:5;−1:6..extreme values: .0; 0; 0., .0; 1; 1., .1; 0; 1., .0; 0; 1.(b) A function that returns the square root of a floating-point number.Answereasy values: 1, 4, 9, 16.typical values: 0.4836, 56.7, 9762.34.extreme value: 0.0.illegal values: −0.4353, −9.Section 1.4 _ Coding, Testing, and Further Refinement 11(c) A function that returns the least common multiple of its two parameters, which must be positive integers.(The least common multiple is the smallest integer that is a multiple of both parameters. Examples: The least common multiple of 4 and 6 is 12, of 3 and 9 is 9, and of 5 and 7 is 35.)Answereasy values: .3; 4., .4; 8., .7; 3..typical values: .7; 8., .189; 433., .1081; 1173..illegal values: .7;−6., .0; 5., .0; 0., .−1;−1..(d) A function that sorts three integers, given as its parameters, into ascending order.Answereasy values: .5; 3; 2., .2; 3; 5., .3; 5; 2., .5; 2; 3., .−1;−2;−3.extreme values: .1; 1; 1., .1; 2; 1., .1; 1; 2..typical values: .487;−390; 20., .0; 589; 333..(e) A function that sorts an array a containing n integers indexed from 0 to n −1 into ascending order, where a and n are both parameters.Answer For the number n of entries to be sorted choose values such as 2, 3, 4 (easy values), 0, 1, maximumsize of a (extreme values), and −1 (illegal value). Test with all entries of a the same value, the entries already in ascending order, the entries in descending order, and the entries in randomorder.E4. Find suitable glass-box test data for each of the following:(a) The statementif (a < b) if (c > d) x = 1; else if (c == d) x = 2;else x = 3; else if (a == b) x = 4; else if (c == d) x = 5;else x = 6;Answer Choose values for a and b, such as .1; 2., .2; 1., and .1; 1., so that each of a < b, a > b, and a == b holds true. Choose three similar pairs of values for c and d, giving nine sets of test data.(b) The Life method neighbor_count(row, col).Answer Set row in turn to 1, maxrow, and any intermediate value, as well as 0 and maxrow . 1 (as illegalvalues). Choose col similarly. For each of the legal (row, col) pairs set up the Life object so thatthe number of living neighbors of (row, col) is each possible value between 0 and 8. Finally, makethe cell at (row, col) itself either living or dead. (This process gives 98 sets of test data, provided maxrow and maxrow are each at least 3.)Programming Projects 1.4P1. Enter the Life program of this chapter on your computer and make sure that it works correctly. Answer The complete program is implemented in the life subdirectory for Chapter 1.#include "../../c/utility.h"#include "life.h"#include "../../c/utility.cpp"#include "life.cpp"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 forthe game of Life.Uses: The class Life and its methods initialize(), print(), andupdate(); the functions instructions(), user_says_yes().*/12 Chapter 1 _ Programming Principles{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;}}const int maxrow = 20, maxcol = 60; // grid dimensionsclass Life {public:void initialize();void print();void update();private:int grid[maxrow + 2][maxcol + 2]; // Allow two extra rows and columns. int neighbor_count(int row, int col);};void Life::print()/*Pre: The Life object contains a configuration.Post: The configuration is written for the user.*/{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;}int Life::neighbor_count(int row, int col)/*Pre: The Life object contains a configuration, and the coordinates row and col define a cell inside its hedge.Post: The number of living neighbors of the specified cell is returned. */{int i, j;int count = 0;for (i = row - 1; i <= row + 1; i++)for (j = col - 1; j <= col + 1; j++)count += grid[i][j]; // Increase the count if neighbor is alive.count -= grid[row][col]; // A cell is not its own neighbor.return count;}Section 1.4 _ Coding, Testing, and Further Refinement 13void Life::update()/*Pre: The Life object contains a configuration.Post: The Life object contains the next generation of configuration. */{int row, col;int 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]; // Status stays the same. break;case 3:new_grid[row][col] = 1; // Cell is now alive.break;default:new_grid[row][col] = 0; // Cell is now dead.}for (row = 1; row <= maxrow; row++)for (col = 1; col <= maxcol; col++)grid[row][col] = new_grid[row][col];}void Life::initialize()/*Pre: None.Post: The Life object contains a configuration specified by the user.*/{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 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;elsecout << "Column " << col << " is out of range." << endl;elsecout << "Row " << row << " is out of range." << endl;cin >> row >> col;}}void instructions()/*Pre: None.Post: Instructions for using the Life program have been printed.*/14 Chapter 1 _ Programming Principles{cout << "Welcome to Conway's game of Life." << endl;cout << "This game uses a grid of size "<< maxrow << " by " << maxcol << " in which" << endl;cout << "each cell can either be occupied by an organism or not." << endl;cout << "The occupied cells change from generation to generation" << endl;cout << "according to the number of neighboring cells which are alive."<< endl;}P2. Test the Life program with the examples shown in Figure 1.1.Answer See the solution to the exercise in Section 1.2.P3. Run the Life program with the initial configurations shown in Figure 1.4. Several of these go throughmany changes before reaching a configuration that remains the same or has predictable behavior. Answer This is a demonstration to be performed by computer.1.5 PROGRAM MAINTENANCEExercises 1.5E1. Sometimes the user might wish to run the Life game on a grid smaller than 20_60. Determine how it ispossible to make maxrow and maxcol into variables that the user can set when the program is run. Try to make as few changes in the program as possible.Answer The integers maxrow and maxcol should become data members of the class Life. The method initialize, must now ask for input of the two data members maxrow and maxcol. Upper boundsof 20 and 60 for these integers should be stored in new constants called maxrowbound and maxcolbound. The amended file life.h now takes the form.const int maxrowbound = 20, maxcolbound = 60;// bounds on grid dimensionsclass Life {public:void initialize( );void print( );void update( );private:int maxrow, maxcol;int grid[maxrowbound . 2][maxcolbound . 2];// allows for two extra rows and columnsint neighbor_count(int row, int col);};As noted above, the method initialize needs minor modifications.E2. One idea for speeding up the function Life :: neighbor_count(row, col) is to delete the hedge (the extrarows and columns that are always dead) from the arrays grid and new_grid. Then, when a cell is on the boundary, neighbor_count will look at fewer than the eight neighboring cells, since some of these are outside the bounds of the grid. To do this, the function will need to determine whether or not the cell(row, col) is on the boundary, but this can be done outside the nested loops, by determining, before the loops commence, the lower and upper bounds for the loops. If, for example, row is as small as allowed, then the lower bound for the row loop is row; otherwise, it is row −1. Determine, in terms of the size of the grid, approximately how many statements are executed by the original version of neighbor_count and by the new version. Are the changes proposed in this exercise worth making?Section 1.5 _ Program Maintenance 15Answer We need four if statements at the beginning of neighbor_count to determine whether (row, col) is on the boundary. This gives a total of 4 _ maxrow _ maxcol extra statements. If the cell is inthe first or last row or column, but not in a corner, then the nested loops would iterate 3 fewertimes. There are 2_maxrow.2_maxcol−8 such positions. With the cell in one of the 4 cornerpositions, the nested loops would iterate 5 fewer times. Hence the total number of statementssaved is−4 _ maxrow _ maxcol . .2 _ maxrow . 2 _ maxcol −8..20:Thus this proposed change actually costs additional work, except for very small values of maxrow and maxcol.The modified function could be coded as follows.int Life :: neighbor_count(int row, int col)/* Pre: The Life object contains a configuration, and the coordinates row and col define a cell inside its hedge.Post: The number of living neighbors of the specified cell is returned. */{int i, j;int count = 0;int rowlow = row −1, rowhigh = row . 1,collow = col −1, colhigh = col . 1;if (row == 1) rowlow..;if (row == maxrow) rowhigh−−;if (col == 1) collow..;if (col == maxcol) colhigh−−;for (i = rowlow; i <= rowhigh; i..)for (j = collow; j <= colhigh; j..)count += grid[i][j]; // Increase the count if neighbor is alivecount −= grid[row][col]; // Reduce count, since cell is not its own neighborreturn count;}Programming Projects 1.5P1. Modify the Life function initialize so that it sets up the initial Life :: grid configuration by accepting occupied positions as a sequence of blanks and x’s in appropriate rows, rather than requiring the occupiedpositions to be entered as numerical coordinate pairs.Answer The following program includes all the changes for projects P1–P6. The changes required for Projects P7 and P8 are system dependent and have not been implemented.#include "../../c/utility.h"#include "life.h"#include "../../c/utility.cpp"#include "life.cpp"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 inthe configuration of living cells according to the rules forthe game of Life.Uses: The class Life and methods initialize(), print(), and update();。

相关文档
最新文档