Introduction to Programming in C

Slides:



Advertisements
Similar presentations
6.830 Lecture 10 Query Optimization 10/6/2014. Selinger Optimizer Algorithm algorithm: compute optimal way to generate every sub-join: size 1, size 2,...
Advertisements

Peter Černo and František Mráz. Introduction Δ -Clearing Restarting Automata: Restricted model of Restarting Automata. In one step (based on a limited.
Dept. of Computer Science & IT, FUUAST Automata Theory 2 Automata Theory VII.
Quit Permutations Combinations Pascal’s triangle Binomial Theorem.
Algorithm Programming Some Topics in Compression Bar-Ilan University תשס"ח by Moshe Fresko.
11 Introduction to Programming in C - Fall 2010 – Erez Sharvit, Amir Menczel 1 Introduction to Programming in C תרגול
Fall 2005 CSE 467/567 1 Formal languages regular expressions regular languages finite state machines.
Jessie Zhao Course page: 1.
1 Milena Mihail Georgia Tech. with Stephen Young, Giorgos Amanatidis, Bradley Green Flexible Models for Complex Networks.
Tree Diagrams. * The tree diagram is an important way of organizing and visualizing outcomes.
Lexical Analysis CSE 340 – Principles of Programming Languages Fall 2015 Adam Doupé Arizona State University
1 CS 552/652 Speech Recognition with Hidden Markov Models Winter 2011 Oregon Health & Science University Center for Spoken Language Understanding John-Paul.
Whole numbers and numeration Math 123 September 17-19, 2008.
1 Language Definitions Lecture # 2. Defining Languages The languages can be defined in different ways, such as Descriptive definition, Recursive definition,
Elementary Combinatorics Combinatorics  Deals with enumeration (counting) techniques and related algebra.  Basis of counting XSet |X|No. of elements.
תרגול 13 חזרה 1. Exam example 8 public class Stam { private char x; public Stam() { this.x = '*'; } public Stam (char c) { this.x = c; } public Stam getStam()
Lecture # 3 Regular Expressions 1. Introduction In computing, a regular expression provides a concise and flexible means to "match" (specify and recognize)
L ECTURE 3 Chapter 4 Regular Expressions. I MPORTANT T ERMS Regular Expressions Regular Languages Finite Representations.
Properties of Addition and Multiplication. Commutative Property In the sum you can add the numbers in any order. a+b = b+a In the product you can multiply.
Introduction to Theory of Automata By: Wasim Ahmad Khan.
1 Milena Mihail Georgia Tech. “with network elements maintaining characteristic profiles” Models and Algorithms for Complex Networks “with categorical.
Counting CSC-2259 Discrete Structures Konstantin Busch - LSU1.
Phrase-structure grammar A phrase-structure grammar is a quadruple G = (V, T, P, S) where V is a finite set of symbols called nonterminals, T is a set.
Regular Grammars Chapter 7. Regular Grammars A regular grammar G is a quadruple (V, , R, S), where: ● V is the rule alphabet, which contains nonterminals.
Regular Grammars Chapter 7 1. Regular Grammars A regular grammar G is a quadruple (V, , R, S), where: ● V is the rule alphabet, which contains nonterminals.
Data Compression Meeting October 25, 2002 Arithmetic Coding.
1 Simplification of Context-Free Grammars Some useful substitution rules. Removing useless productions. Removing -productions. Removing unit-productions.
1 Chapter 6 Simplification of CFGs and Normal Forms.
Figure **: Adjusted average student learning score against unit cost Unit Cost (fcfa) Average adjusted student learning score.
Chapter 19 LL(k) Grammars. 2 LL(k) Parsers n Can be developed using PDAs for parsing CFGs by converting the machines directly into program statements.
Holt McDougal Algebra Multiplying Polynomials Multiply polynomials. Use binomial expansion to expand binomial expressions that are raised to positive.
March 11, 2005 Recursion (Implementation) Satish Dethe
Lecture # Book Introduction to Theory of Computation by Anil Maheshwari Michiel Smid, 2014 “Introduction to computer theory” by Daniel I.A. Cohen.
Lecture # 4.
Lecture 2 Theory of AUTOMATA
Int fact (int n) { If (n == 0) return 1; else return n * fact (n – 1); } 5 void main () { Int Sum; : Sum = fact (5); : } Factorial Program Using Recursion.
1 Strings and Languages Lecture 2-3 Ref. Handout p12-17.
CHAPTER TWO LANGUAGES By Dr Zalmiyah Zakaria.
CSE 589 Applied Algorithms Spring 1999
Theory of Computation Lecture #
Lecture # 2.
Regular Languages, Regular Operations, Closure
CSC-2259 Discrete Structures
Lexical Analysis CSE 340 – Principles of Programming Languages
Text and Other Types, Variables
PROGRAMMING LANGUAGES
Inside of SQL Server Indexes
LANGUAGES Prepared by: Paridah Samsuri Dept. of Software Engineering
Data Types, Type Conversions, Switch-Case, Methods
Combinatorics.
מצביעים והקצאה דינאמית
Introduction to Programming in C
Computer Programming תרגול 6 פונקציות
Computer Programming Summer 2017
Computer Programming תירגול 13 חזרה למבחן.
Computer Programming Fall 2012 תרגול 6 פונקציות
Recap lecture 29 Example of prefixes of a language, Theorem: pref(Q in R) is regular, proof, example, Decidablity, deciding whether two languages are equivalent.
Introduction to Programming in C
Binomial Expansion 2 L.O. All pupils can follow where the binomial expansion comes from All pupils understand binomial notation All pupils can use the.
Combinatorics.
Recursion Department of Computer Science-BGU יום שני 10 דצמבר 2018.
Математици-юбиляри.
Recall Brute Force as a Problem Solving Technique
Combinatorics.
Basic elements of triangle
CSC102 - Discrete Structures (Discrete Mathematics) Set Operations
Practice makes perfect!
Sequences 6/1/2019 7:49 PM Using Recursion Using Recursion.
Recap Lecture 3 RE, Recursive definition of RE, defining languages by RE, { x}*, { x}+, {a+b}*, Language of strings having exactly one aa, Language of.
Enumerating all Permutations
Presentation transcript:

Introduction to Programming in C תרגול 8 1 1 Introduction to C - Fall 2010 - Amir Menczel

רקורסיה תזכורת הגדרה: המונח רקורסיה (recursion) מתאר מצב שבו פונקציה קוראת לעצמה באופן ישיר או באופן עקיף. שימוש: נוח להשתמש בפונקציות רקורסיביות על מנת לפתור בעיות בעלות אופי רקורסיבי. באופן כללי, השיטה תהיה להקטין את מימד הבעיה, לפתור את הבעיה על המימד היותר קטן ולהשתמש בפיתרון שמתקבל על מנת לפתור את הבעיה במימד אחד יותר גבוהה.

תרגיל מס' 1 – abc כתוב פונקציה רקורסיבית אשר חתימתה היא: void abc(char arr[],int lastPlace, int curPlace) המקבלת מערך של char-ים, את אינדקס סוף המערך ומספר שלם שהוא המקום במערך ממנו אנו מעונינים להתחיל במילוי המערך בתווים (בקריאה ראשונה יהיה מס' זה שווה ל- 0). הפונקציה מדפיסה את כל האפשרויות למלא את המערך מהמקום שקיבלה, curPlace, עד המקום lastPlace באותיות a,b,c במילים אחרות, מטרת הפונקציה היא להדפיס את כל האפשרויות ליצור מילה באורך מסוים בעזרת האותיות a,b,c .

תרגיל מס' 1 – abc void abcInvokingFun(char word[],int lengthOfWord){ למשל: עבור התוכנית הבאה: void abcInvokingFun(char word[],int lengthOfWord){ abc(word, lengthOfWord,0); } void main(){ char word[5]; abcInvokingFun(word,3); נקבל את הפלט: aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc

תרגיל מס' 1 – abc כתובתו של תחילת המערך המקום הנוכחי שאנחנו משנים אינדקס סוף המערך void abc(char arr[],int lastPlace, int curPlace) { תנאי העצירה: אם הגענו ל- lastPlace אז שים במקום הנוכחי יש '0\' (הגענו לסוף), הדפס את המחרוזת (מהתחלתה) וחזור. if (curPlace == lastPlace) { arr[curPlace]='\0'; printf("%s\t",arr); כעת אנחנו עובדים על המקום curPlace במערך: הצב בו a, וקרא לפונק' abc (עם כתובת המערך, ואינדקס המקום הבא) אשר תדאג למילוי כל האפשרויות הקימות בשאר המערך. לאחר שחזרת, הצב את b במקום a, ושוב קרא לפונק' עם המקום הבא במערך כפרמטר. כנ"ל לגבי c. return; } arr[curPlace] = 'a'; abc (arr,lastPlace,curPlace+1); arr[curPlace] = 'b'; abc (arr,lastPlace,curPlace+1); arr[curPlace] = 'c'; }

תרגיל מס' 1 – abc נראה את תרשים הקריאות המתקבל מהרצת הדוגמא שלמעלה (בדומה לתרשים הקריאות שראינו בכתה): כל ריבוע מייצג קריאה לפונקציה, כאשר בתוך כל ריבוע מופיע תוכן המערך שהפונקציה מקבלת. ערך הפרמטרcurPlace הוא משותף לכל רמה בתרשים ומצויין בצד ימין. aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc aaa הדפסה: aa? ab? ac? ba? bb? bc? ca? cb? cc? a?? b?? c?? ??? curPlace=0 curPlace=1 curPlace=2 curPlace=3

תרגיל מס' 2 כתבו תוכנית הקולטת עד 20 ערכים שלמים (1- מציין סוף קלט) למערך ומוצאת את הערך המקסימאלי. לשם כך, ניתן לפרק את הבעיה לשתי בעיות קטנות יותר כתבו פונקציה רקורסיבית שקולטת את המערך כתבו פונקציה רקורסיבית שמחזירה את הערך המקסימאלי

תרגיל מס' 2 int Max(int a[], int i,int length){ int max; if (i == length -1) { return a[i]; } max = Max(a, i + 1); return (a[i] > max ? a[i] : max); int main(){ int max,a[MAX_LEN],length; length = GetArray(a, 0); max=Max(a,0, length ); printf(“max=%d\n”max); return 0; int GetArray(int arr[], int i){ int num; if (i > MAX_LEN – 1){ return 0; } scanf("%d", & num); if (num!= -1) { arr[i] = num; return GetArray(arr, i + 1) +1; else {

תרגיל מס' 3 כתוב פונקציה רקורסיבית אשר מקבלת מחרוזת s, תו ch, ומספר שלם n. הפונקציה תחפש את המופע ה- n-י של ch במחרוזת s ותחזיר את האינדקס שלו. דוגמא: בהינתן המחרוזת “abbc”, התו b, והשלם 2 (עבור n) הפונקציה תחזיר 2. התו ‘b’ מופיע בפעם השנייה במחרוזת s באינדקס 2 במחרוזת.

תרגיל מס' 3 int FindNOccurence(char s[], char ch, int n, int index){ if (n == 0) return index -1; if (s[index] == '\0') return -1; if (s[index] == ch) return FindNOccurence (s, ch, n – 1, index + 1); return FindNOccurence(s, ch, n, index + 1); {

תרגיל מס' 4 נתונה הפונקציה הרקורסיבית הבאה: #include <stdio.h> int secret( int n){ If( n<0 ) return 1 + secret ( -1 * n); if ( n<10 ) return 1; return 1 + secret( n/10 ); } מה הערך של secret(-4321) ו- secret(12345) ? מה מבצעת הפונקציה secret עבור פרמטר חיובי ועבור פרמטר שלילי? כתוב פונקציה זו מחדש בצורה לא רקורסיבית.

תרגיל מס' 4 פתרון: סעיף א': 5 בשני המקרים. סעיף א': 5 בשני המקרים. סעיף ב': הפונקציה מחזירה את מס' התווים שמייצגים את הארגומנט. כך למשל הפלט של התוכנית הבאה: void main() { char s[80]; printf("%d\n",secret(-43221)); printf("%d\n",secret(12345)); יהיה: 6 5 }

תרגיל מס' 4 כתוב אותה פונקציה בצורה לא רקורסיבית. פתרון: int iterSecret( int n){ int len=1; if( n<0 ) { n=(-1) * n; len++; } while( n>=10 ) { n/=10; return len;

תרגיל מס' 5 int what(int a, int b){ if(!a && !b) return 1; עיין בפונקציה הבאה: int what(int a, int b){ if(!a && !b) return 1; if(a > b) return a * what(a-1, b); return b * what(a, b-1); } בהנחה שהפונקציה הנ"ל מקבלת שני ערכים אי-שליליים (חיוביים או אפס), סמן את כל התשובות הנכונות (בדף התשובות): הפונקציה נכנסת לרקורסיה אינסופית. הערך המוחזר של הפונקציה תמיד 0. הערך המוחזר של הפונקציה יכול להיות 0. הערך המוחזר של הפונקציה תמיד 1. הערך המוחזר של הפונקציה יכול להיות 1. בקבלת שני ערכים חיוביים a ו- b, אם הערכים לא גדולים מידי,הפונקציה מחזירה את הערך של a! x b!. אף לא אחת מהתשובות לעיל.

פתרון: 5 (למשל כאשר a=0 וגם b=0)

תרגיל מס' 6 Subset Sum problem נתונה סדרת ערכים שלמים (כמערך) arr ומספר שלם S. צ"ל: האם קיימת תת-סדרה במערך כך שסכומה S. למשל עבור: arr 17 1 5 6 7 ו-S=14 התשובה היא כן כי קיימת תת-סדרה במערך שהיא: 7,6,1 וסכומה 14.

תרגיל מס' 6 האלגוריתם: עבור כל איבר i במערך, יש 2 אפשרויות: אפשרות א': כן לוקחים את האיבר ה- i, ומנסים למצוא SubsetSum בגודל S-arr[i] במערך קטן יותר ב-1. אפשרות ב': לא לוקחים את האיבר ה- i , ומנסים למצוא SubsetSum בגודל S במערך קטן יותר ב-1. תנאי העצירה שלנו יהיו: אם קיבלנו באיזשהו שלב S==0 אז נמצא SubsetSum במערך ונחזיר 1. אחרת, אם קיבלנו S<0 או 0==n, אז הבחירות שלקחנו עד עכשיו אינן מובילות לפתרון (אם S<0 אזי עברנו את הסכום המבוקש ואם 0==n אזי עדיין לא הגענו לסכום ואין לרשותנו אברים מתוכם נוכל לבחור) ונחזיר 0.

תרגיל מס' 6 int SubsetSum(int arr[], int idx, int n, int S) { if (S==0) return 1; //This is stopping condition #1. if (S<0 || n==0) return 0; //This is stopping condition #2. return SubsetSum(arr, idx+1, n-1, S-arr[idx]) || SubsetSum(arr, idx+1, n-1, S); } טיפול באפשרות א' טיפול באפשרות ב'

תרגיל מס' 7 שנו את הפונקציה שכתבתם בשאלה הקודמת כך שהיא תחזיר את כמות תתי-הקבוצות של איברי המערך המקיימות שסכומן שווה בדיוק ל-s.

תרגיל מס' 7 int SubsetSum(int arr[], int idx, int n, int S) { if (S==0) return 1; //This is stopping condition #1. if (S<0 || n==0) return 0; //This is stopping condition #2. return SubsetSum(arr, idx+1, n-1, S-arr[idx]) + SubsetSum(arr, idx+1, n-1, S); }

תרגיל מס' 8 נתון מערך דו-מימדי בגודל m*n המכיל מספרים טבעיים קטנים מ-100. מסלול חוקי במערך מתחיל בתא (0,0) ומסתיים בתא (m-1,n-1), כאשר ההתקדמות תלויה בספרת האחדות והעשרות של המס' שבתא הנוכחי. אם בתא (2,3) רשום המס' 13, אז ישנם 2 דרכים להתקדם מתא זה: 1) 1+ בשורות ו 3+ בעמודות. כלומר לתא (3,6). 2) 3+ בשורות ו 1+ בעמודות. כלומר לתא (5,4). אם בתא רשום מס' חד ספרתי, למשל 3, נתייחס אליו כאל 03.

תרגיל מס' 8 (המשך) לדוגמה: מסלול אפשרי הוא המסלול הצבוע בירוק. כתבו פונקציה רקורסיבית המחזירה את מס' המסלולים החוקיים במערך (כמובן שאסור להשתמש בלולאות).

תרגיל מס' 8 (פתרון)

תרגיל מס' 9 כתבו פונקציה רקורסיבית void X(int lines) שמדפיסה את האות X באמצעות כוכביות ב-lines שורות (נניח ש-lines תמיד אי-זוגי). ניתן להשתמש בלולאות. לדוגמא עבור X(9) יודפס:  * * * * * * * * * * *  הכוכבית הראשונה חייבת להופיע בתחילת השורה הראשונה. אין להגדיר פונקציה נוספת.

פתרן תרגיל מס' 9 פתרון: הרעיון הוא להדפיס את השורה הראשונה של X, אחר כך לפתור את תת-הבעיה עבור X ללא השורה הראשונה והאחרונה ואז להדפיס את השורה האחרונה (שהיא זהה לראשונה). ניתן להדגים את סדר הפעולות הכרונולוגי בכל קריאה רקורסיבית באמצעות התרשים הבא:

פתרון תרגיל מס' 9 void X(int lines){ int static blank; int I; for (i=0; i<blank; i++) putchar(' '); putchar('*'); if(lines==1){ puts(""); return; } for (i=0; i<lines-2; i++) puts("*"); blank++; X(lines-2); blank--; for (i=0; i<blank; i++) putchar(' '); }