Chapter 8 Loops while loop syntax while ;... end;.

Slides:



Advertisements
Similar presentations
Lecture 2: Basic Information Theory TSBK01 Image Coding and Data Compression Jörgen Ahlberg Div. of Sensor Technology Swedish Defence Research Agency (FOI)
Advertisements

MATH 224 – Discrete Mathematics
Michael Alves, Patrick Dugan, Robert Daniels, Carlos Vicuna
MATLAB Examples. CS 1112 MATLAB Examples Find the number of positive numbers in a vector x = input( 'Enter a vector: ' ); count = 0; for ii = 1:length(x),
CSC 331: Algorithm Analysis Divide-and-Conquer Algorithms.
Multiplication Rule. A tree structure is a useful tool for keeping systematic track of all possibilities in situations in which events happen in order.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
1 ICS 353 Design and Analysis of Algorithms Spring Semester (062) King Fahd University of Petroleum & Minerals Information & Computer Science.
Lecture 2 Aug goals: Introduction to recursion examples of recursive programs.
Complexity Analysis (Part I)
Lecture 4 Sept 8 Complete Chapter 3 exercises Chapter 4.
Lecture 12 Oct 15 Recursion – more examples Chapter 8 problems and solutions Cell arrays, Chapter 10.
Algorithm Design Techniques: Induction Chapter 5 (Except Section 5.6)
Chapter 8 Loops while loop syntax while ;... end;.
Algorithm Analysis CS 201 Fundamental Structures of Computer Science.
Chapter 8 Loops while loop syntax while ;... end;.
 Last lesson  Arrays for implementing collection classes  Performance analysis (review)  Today  Performance analysis  Logarithm.
Concept of Basic Time Complexity Problem size (Input size) Time complexity analysis.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Lecture 2: Basic Information Theory Thinh Nguyen Oregon State University.
Copyright © Cengage Learning. All rights reserved. CHAPTER 11 ANALYSIS OF ALGORITHM EFFICIENCY ANALYSIS OF ALGORITHM EFFICIENCY.
Lecture 4 Sept 7 Chapter 4. Chapter 4 – arrays, collections and indexing This chapter discusses the basic calculations involving rectangular collections.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Analysis of Algorithms COMP171 Fall Analysis of Algorithms / Slide 2 Introduction * What is Algorithm? n a clearly specified set of simple instructions.
Information Theory and Security
Hamming Codes 11/17/04. History In the late 1940’s Richard Hamming recognized that the further evolution of computers required greater reliability, in.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
1 9/11/2015 MATH 224 – Discrete Mathematics Iterative version Recursive version Normally i is initialized to 0 and j to n–1 for an array of size n. Recursive.
Chapter 3: The Fundamentals: Algorithms, the Integers, and Matrices
1 Decrease-and-Conquer Approach Lecture 06 ITS033 – Programming & Algorithms Asst. Prof. Dr. Bunyarit Uyyanonvara IT Program, Image and Vision Computing.
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Analysis of Algorithms
Lecture 4 on Data Structure Array. Prepared by, Jesmin Akhter, Lecturer, IIT, JU Searching : Linear search Searching refers to the operation of finding.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Data Structures and Algorithms Introduction to Algorithms M. B. Fayek CUFE 2006.
CSC 211 Data Structures Lecture 13
Prof. Amr Goneid, AUC1 Analysis & Design of Algorithms (CSCE 321) Prof. Amr Goneid Department of Computer Science, AUC Part 8. Greedy Algorithms.
Lecture 2 Jan Goals: Introduction to recursion Examples of recursive programs Reading: Chapter 1 of the text.
Data Structure Introduction.
CS 361 – Chapters 8-9 Sorting algorithms –Selection, insertion, bubble, “swap” –Merge, quick, stooge –Counting, bucket, radix How to select the n-th largest/smallest.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Algorithm Analysis. What is an algorithm ? A clearly specifiable set of instructions –to solve a problem Given a problem –decide that the algorithm is.
Young CS 331 D&A of Algo. Topic: Divide and Conquer1 Divide-and-Conquer General idea: Divide a problem into subprograms of the same kind; solve subprograms.
Lecture 13 Oct 15, 2012 cell array (review) Ch 4 recursion (Ch 12)
1 Chapter 2 Algorithm Analysis All sections. 2 Complexity Analysis Measures efficiency (time and memory) of algorithms and programs –Can be used for the.
Analysis of Algorithms & Recurrence Relations. Recursive Algorithms Definition –An algorithm that calls itself Components of a recursive algorithm 1.Base.
Chapter 2: Algorithm Discovery and Design Invitation to Computer Science.
1 Chapter 2 Algorithm Analysis Reading: Chapter 2.
Chapter 11. Chapter Summary  Introduction to trees (11.1)  Application of trees (11.2)  Tree traversal (11.3)  Spanning trees (11.4)
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
chap10 Chapter 10 Recursion chap10 2 Recursive Function recursive function The recursive function is a kind of function that calls.
Chapter 2 Algorithm Analysis
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Decrease-and-Conquer Approach
Algorithm Analysis CSE 2011 Winter September 2018.
13 Text Processing Hongfei Yan June 1, 2016.
CS 213: Data Structures and Algorithms
Analysis & Design of Algorithms (CSCE 321)
Describing algorithms in pseudo code
Topic: Divide and Conquer
CS 201 Fundamental Structures of Computer Science
Divide and Conquer Algorithms Part I
And now for something completely different . . .
Lecture 6 - Recursion.
Presentation transcript:

Chapter 8 Loops while loop syntax while ;... end;

Example 1: We wrote a function insert that inserts A(k) in the array A(1:k – 1). Now we will write the function insertionsort to call insert iteratively. function insert(A, k) % assume k > 1 and A(1:k-1)is sorted temp = A(k); j = k-1; while (j > 0) if A(j) > temp A(j+1) = A(j); j = j – 1; else break; end; A(j+1) = temp;

Insertion sorting function B = insertionSort(A) j = 2; while (j <= length(A)) B = insert(A, j); j = j + 1; end; >> B = [ ]; >> B = insertionSort(B); >> B B =

for loop syntax for j = 1:20 end

Simulating the outcome of a probability game Players A and B play the following game. A fair coin is tossed until one of the two patterns HTH or THT occurs. If the first pattern occurs, A wins else B wins. What is the probability that A wins the game? There are two ways to solve this problem: use Markov chain (can find the answer exactly) simulation (simulate the game a large number of times and record the number of wins by each player)

Simulation based solution Outer loop: repeat the game a large number of times, say Inner loop: each iteration represents one game. Outline of solution: countA = 0; countB = 0; for j = 1: while the game is not over toss coin once; update the last three bits; end; update the winner count; end;

We will write three functions: toss()  produces 1 or 2 with probability 0.5 tossgame()  produces 1 (2) if A (B) is the winner of one randomly simulated game repeatTossGame(n)  repeat the tossgame n times, find a = the number of times A wins and output the ratio a/n

Project – entropy computation The concept of entropy is fundamental to information and coding theory – which deals with efficient ways to add redundancy to the data so that the receiver can recover the message even if some of data is corrupted by the channel. Information theory was developed by Claude Shannon. Watch movie about Shannon in UCTV.

probability distribution of individual letters The basic idea of information theory is that if the input has less randomness, it can be more easily predicted and hence it can be compressed to greater degree. Suppose there are k distinct symbols in a text. Let P(j-th symbol) = p j. Entropy is defined as: E = –  j  p j log p j Goal is to compute the entropy of a given text.

Example: Given a three-letter alphabet containing E, Z and _ with frequencies as follows: E Z _ Entropy is given by: E = -0.5 log – 0.25 log – 0.25 log Using matlab, we can compute E as: >> p = [ ] p = >> -sum(p.*log2(p)) ans = >>

Project: Write a program in Matlab that computes the entropy of English. Step 1: collect a corpus of text. count the frequency of letters for the corpus. text will be stored in multiple files program should calculate the frequency of letters across all the files. Step 2: compute entropy from the frequency table.

Recursive functions Before we conclude this chapter, we will discuss recursive functions, those that can call themselves. We have examples of functions that call other functions, e.g. insertionsort calling insert etc. If f(n) is defined in terms of f(n – 1), as for example, in the case of factorial, why not let f call itself? n! = n x (n – 1)! Or in matlab: fact(n) = n.* fact(n – 1)

Rules for recursive functions 1. there should be exit from recursion. (i.e., there should be some conditional branch path in which there is no recursive call). Such cases are called the base cases. 2. recursive calls should make towards base case (usually by calling itself with smaller input values). 3. Recursion may be more time or memory consuming so should be careful with their use.

Example 1: Write a recursive function to compute n! function out = fact(n) if n <= 1 out = 1; else out = n.* fact(n-1); end;

Example 2: Write a recursive function in Matlab to perform binary search. Assume array A is sorted in ascending order. Search(A, low, high, x) will return the largest t such that A(t) <= x. Pre-condition: A(low) <= x <= A(high) Thus low <= t <= high. Initially, low = 1, high = size(A)

Recursive binary search program function out = search(A, low, high, x) % returns the largest t s.t. A(t) <= x where low <= t <= high % A is assumed to be sorted if high - low == 1 if A(high) == x out = high; else out = low; end; else mid = floor((low + high)/2); if A(mid) == x out = mid; elseif A(mid) < x out = search(A, mid + 1, high, x); else out = search(A, low, mid - 1, x); end;

Exercise 8.1. >> repeat([2 3; 3 1; 4 2] ans = [ ]

Exercise 8.1. >> repeat([2 3; 3 1; 4 2] ans = [ ]

Exercise 8.1. >> repeat([2 3; 3 1; 4 2] ans = [ ] function out = repeat1(m) out = []; [r, c] = size(m); for i = 1 : r %Go through each row for j = 1 : m(i, 2) %Repeat the number of times specified in the second column out(end + 1) = m(i, 1); end

Exercise 8.4. Write a function myfind, that mimics the behavior of the built-in function find. That is, it takes as input a boolean vector of 1’s and 0’s.

function out = myfind(A, x) out = []; for j = 1:length(A) if A(j) == x out = [out, j]; end;

Exercise 8.8 Write a function intoBits to take an integer number as input and output a string of 0’s and 1’s representing the number in base 2.

Exercise 8.11 Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A.

Exercise 8.11 Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A.

Exercise 8.11 Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A.

Exercise 8.11 Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A. function res = minAll(m) [r, c] = size(m); res = m(1, 1); %Set up the first temporary minimum for i = 1 : r %Going through each row for j = 1 : c %Going throuch each column if res > m(i, j) %Updating if necessary res = m(i, j) end

Exercise 8.11 Write functions minAll, minCol and minRow that find the overall minimum, column minima and row minima of a matrix A. function res = minRow(m) [r, c] = size(m); res = zeros(1, r); %Set up res for i = 1 : r %Going through each row res(i) = m(i, 1); %Set up the first temporary minimum for row i for j = 2 : c %Going throuch each column if res(i) > m(i, j) %Updating if necessary res(i) = m(i, j); end