CH 07 Programming with Recursion
Recursive Call
Recursion
Some Definition
戻り値
Example
Factorial
int Factorial(int num) {
if (num == 1)
return 1;
else
return Factorial(num - 1);
}
Combination
int Combination(int n, int k) {
if (k == 1)
return n;
else if (k == n)
return 1;
else
return Combination(n-1, k) + Combination(k-1, n-1);
}
ValueInList
関数
bool ValueInList(ListType list, int value, int startIndex) {
if(list->info[startIndex] == value)
return true;
else if (startIndex == list.length - 1)
return false;
else
return ValueInList(list, startIndex - 1);
}
RevPrint
int RevPrint(NodeType* listPtr) {
if(listPrt != NULL):
RevPrint(listPtr->next);
std::cout << listPtr->info << std::endl;
}
BinarySearch
bool BinarySearch(int info[], int item, int start, int end) {
int mid = (start + end) / 2;
if (start > end)
return false;
else if (info[mid] == item)
return true;
else {
if (info[mid] > item)
BinarySearch(info, item, start, mid - 1);
else
BinarySearch(info, item, mid + 1, end);
}
}
Runtime Stack Activation Record
Function Call
void h() {
f();
}
void g() {
f();
}
したがって、
Stack Activation Frame
call fcall gg()f()f()
Activation Record Instance
functionActivation Record InastanceReturn valuef()Local variableParameterReturn Addreaa
Direction of Recursion
Tail Recursion
bool ValueInList(ListType list, int value, int startIndex) {
if(list->info[startIndex] == value)
return true;
else if (startIndex == list.length - 1)
return false;
else
return ValueInList(list, startIndex - 1);
}
bool ValueInList(ListType list, int value, int startIndex) {
bool found = false;
while (!found) {
if (list->info[startIndex] == value)
found = true;
else
startIndex++;
return found;
}
}
Reverse Recursion
行動の前に
int RevPrint(NodeType* listPtr) {
if(listPrt != NULL):
RevPrint(listPtr->next);
std::cout << listPtr->info << std::endl;
}
int RevPrint(NodeType* listPtr) {
StackType<ItemType> stack;
listPtr = listData;
while (listPtr != NULL) {
stack.push(listPtr->info);
listPtr = listPtr->next;
}
while (!stack.IsEmpty()) {
std::cout << stack.top() << std::endl;
stack.pop();
}
}
Additional Algorithm
Quick Sort Algorithm
int Split(int values[], int first, int last) {
int pivot, temp;
int low, high;
low = first + 1;
high = last;
pivot = values[first];
while (low < high) {
while (low <= last && values[low] < pivot)
low++;
while (high >= first && values[high] > pivot)
high--;
if (low < high) {
temp = values[low];
values[low] = values[high];
values[high] = temp;
}
}
temp = values[first];
values[first] = values[high];
values[high] = temp;
return high;
}
void QuickSort(int values[], int first, int last) {
if (first < last) {
int splitPoint = Split(values, first, last);
QuickSort(values, first, splitPoint - 1);
QuickSord(values, splitPoint + 1, last);
}
}
Sorted List InserItem
template<class ItemType>
void Insert(NodeType<ItemType>* location, ItemType item) {
if ((location == NULL) || (item < location->info) {
NodeType<ItemType>* temp = location;
location = new NodeType<ItemType>;
location->info = item;
location->next = temp;
}
else
Insert(locaion->next, item);
}
template<class ItemType>
void SortedType::InsertItem(ItemType item) {
Insert(listData, item);
}
Sorted List DeleteItem
template<class ItemType>
void Delete(NodeType<ItemType>* location, ItemType item) {
if (location->info == item) {
NodeType<ItemType>* temp = locaion;
location = location->next;
delete temp;
}
else
Delete(location->next, item);
}
template<class ItemType>
void SortedType::DeleteItem(ItemType item) {
Delete(listData, item);
}
LAB
Fibonacci
int Fibonacci(int n) {
if (n == 0 || n == 1)
return n;
else
return Fibonacci(n - 2) + Fibonacci(n - 1);
}
int Fibonacci(int n) {
if (n == 0 || n == 1)
return n;
int result;
int num1 = 0;
int num2 = 1;
for (int i = 1; i < n; i++) {
result = num1 + num2;
num1 = num2;
num2 = result;
}
return result;
}
SqurRoot
#include <iostream>
#include <cmath>
using namespace std;
float SqrRoot(float number, float approx, float tol) {
if (fabs(approx * approx - number) <= tol)
return approx;
else
return SqrRoot(number, (approx * approx + number) / (2 * approx), tol);
}
#include <iostream>
#include <cmath>
using namespace std;
float SqrRoot(float number, float approx, float tol) {
while (fabs(approx * approx - number) > tol) {
approx = (approx * approx + number) / (2 * approx);
}
return approx;
}
NumPath
2 Dメッシュ(1、1)から(N、N)までの移動可能パス数
従って、(r,c)~(n,n)への経路数(r+1,c)~(n,n)への(r,c++1)~(n,n)の合計はである.
現在位置のrまたはcがnである場合(
数量は
#include <iostream>
using namespace std;
int NumPaths(int row, int col, int n) {
if ((row == n) || (col == n))
return 1;
else
return NumPaths(row + 1, col, n) + NumPaths(row, col + 1, n);
}
#include <iostream>
using namespace std;
int NumPaths(int row, int col, int n) {
if ((row == n) || (col == n))
return 1;
else
return NumPaths(row + 1, col, n) + NumPaths(row, col + 1, n);
}
#define MAXROWS 50
#define MAXCOLS 50
int mat[MAXROWS][MAXCOLS];
int NumPathsMatrix(int row, int col, int n) {
if (mat[row][col] == -1) {
if (row == col) {
mat[row][col] = 0;
return 0;
}
else if ((row == n) || (col == n)) {
mat[row][col] = 1;
return 1;
}
else {
mat[row][col] = NumPaths(row + 1, col, n) + NumPaths(row, col + 1, n);
return mat[row][col];
}
}
}
MinLoc
#include <iostream>
#include <new>
using namespace std;
template<class ItemType>
NodeType<ItemType>* UnsortedType<ItemType>::MinLoc(NodeType<ItemType>* location) {
if (location == NULL)
return NULL;
else if (location->next == NULL)
return location;
else {
NodeType<ItemType>* minPtr = MinLoc(location->next);
if (location->info < minPtr->info)
minPtr = location;
return minPtr;
}
}
#include <iostream>
#include <new>
using namespace std;
template<class ItemType>
NodeType<ItemType>* UnsortedType<ItemType>::Sort(NodeType<ItemType>* location) {
NodeType<ItemType>* min;
ItemType temp;
if (location != NULL) {
min = MinLoc(location, location);
temp = min->info;
min->info = location->info;
location->info = temp;
Sort(location->next)
}
}
PP
Binary Search
13 is not in the list
20 is in the list
def binary_search(info, item, fromLocation, toLocation):
if fromLocation > toLocation:
return False
else:
midPoint = int((fromLocation + toLocation) / 2)
if item < info[midPoint]:
return binary_search(info, item, fromLocation, midPoint-1)
elif item == info[midPoint]:
return True
else:
return binary_search(info, item, midPoint+1, toLocation)
from BinSearch import *
if __name__ == '__main__':
arr = [1,3, 5, 6, 7, 10, 17, 20]
item = 13
if binary_search(arr, item, 0, len(arr) - 1) == True:
print(f'{item} is in the list.')
else:
print(f'{item} is not in the list.')
item = 20
if binary_search(arr, item, 0, len(arr) - 1) == True:
print(f'{item} is in the list.')
else:
print(f'{item} is not in the list.')
Combination
C(10, 3): 120
C(5, 1): 5
C(45, 6): 8145060
def combinations(group, members):
if(members == 1):
return group
elif (members == group):
return 1
else:
return(combinations(group-1, members-1) + combinations(group-1, members))
from ComBin import *
if __name__ == '__main__':
print(f"C(10,3) : {combinations(10, 3)}")
print(f"C(5,1) : {combinations(5, 1)}")
print(f"C(45,6) : {combinations(45, 6)}")
Factorial
7! : 120
17! : 355687428096000
50! : 30414093201713378043612608166064768844377641568960512000000000000
def factorial(number):
if (number == 1):
return 1
else:
return number*factorial(number-1)
from Factorial import *
if __name__ == '__main__':
print(f'7! : {factorial(5)}')
print(f'17! : {factorial(17)}')
print(f'50! : {factorial(50)}')
QuickSort
Before
[9, 8, 7, 6, 5, 4, 3, 2, 1]
After
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Before
[1, 8, 5, 7, 3, 2, 6, 4, 9]
After
[1, 2, 3, 4, 5, 6, 7, 8, 9]
def split(values, first, last):
splitvalue = values[first]
saveFirst = first
onCorrectside = True
first += 1
while(first <= last):
while(onCorrectside):
if(values[first]>splitvalue):
onCorrectside = False
else:
first += 1
onCorrectside = (first <= last)
onCorrectside = (first <= last)
while(onCorrectside):
if(values[last] < splitvalue):
onCorrectside = False
else:
last -= 1
onCorrectside = (first <= last)
if(first <= last):
values[first], values[last] = values[last], values[first]
first += 1
last -= 1
splitPoint = last
values[saveFirst], values[splitPoint] = values[splitPoint], values[saveFirst]
return splitPoint
def quick_sort(values, first, last):
if(first < last):
splitPoint = split(values, first, last)
quick_sort(values, first,splitPoint-1 )
quick_sort(values, splitPoint+1, last)
return values
from QuickSort1 import *
if __name__ == '__main__':
arr01 = [9, 8, 7, 6, 5, 4, 3, 2, 1]
arr02 = [1, 8, 5, 7, 3, 2, 6, 4, 9]
print("Before")
print(arr01)
print("After")
print(quick_sort(arr01, 0, len(arr01) - 1))
print("\nBefore")
print(arr02)
print("After")
print(quick_sort(arr02, 0, len(arr02) - 1))
Reference
この問題について(CH 07 Programming with Recursion), 我々は、より多くの情報をここで見つけました https://velog.io/@morion002/CH-07-Programming-with-Recursionテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol