Problem Solving Techniques Slides

  • Upload
    rathivi

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

  • 8/6/2019 Problem Solving Techniques Slides

    1/69

    PROBLEM SOLVING TECHNIQUES

    1

  • 8/6/2019 Problem Solving Techniques Slides

    2/69

    UNIT I

    INTRODUCTION TO COMPUTER PROBLEM SOLVING

    2

  • 8/6/2019 Problem Solving Techniques Slides

    3/69

    INTRODUCTION

    Problem solving is an intricate process that

    requires,

    Much thought

    Careful planning Logical planning

    Persistence and

    Attention to detail

    3

  • 8/6/2019 Problem Solving Techniques Slides

    4/69

  • 8/6/2019 Problem Solving Techniques Slides

    5/69

    PROGRAMS AND ALGORITHMS

    Algorithm:

    A set of explicit and unambiguous finite steps which, whencarried out for a given set of initial conditions, produce thecorresponding output and terminate in a finite time.

    A solution to a problem that is independent of anyprogramming language.

    Is capable of being implemented as a correct and efficientcomputer program.

    5

    INTRODUCTION

  • 8/6/2019 Problem Solving Techniques Slides

    6/69

    REQUIREMENTS FOR SOLVING PROBLEMS BY

    COMPUTER

    Depth of understanding

    Data organization

    Input / Output: Supply the program with input or data so that

    the program manipulates the data according toits instructions and produces an output whichrepresents the computer solution to the problem.

    6

  • 8/6/2019 Problem Solving Techniques Slides

    7/69

    THE PROBLEM-SOLVING ASPECT

    Problem Definition Phase:

    Understand what it is we are trying to solve

    Work out what must be done rather than how to

    do it Extract from the problem statement a set of

    precisely defined tasks.

    7

  • 8/6/2019 Problem Solving Techniques Slides

    8/69

    THE PROBLEM-SOLVING ASPECT

    Getting started on a problem:

    Many ways to solve most problems

    Many solutions to most problems.

    Difficult to find quickly which paths are fruitlessand which are productive.

    Dont concern with details of the implementationbefore understanding a problem.

    The sooner you start coding your program the

    longer it is going to take

    8

  • 8/6/2019 Problem Solving Techniques Slides

    9/69

    THE PROBLEM-SOLVING ASPECT

    The use of specific examples:

    Pick a specific example of the general problem tosolve

    Try to work out the mechanism to solve thisparticular problem.

    Employ geometrical or schematic diagramsrepresenting certain aspects of the problem.

    Examine the specifications or test cases for theproblem carefully

    Check whether or not the proposed algorithm canmeet those requirements. 9

  • 8/6/2019 Problem Solving Techniques Slides

    10/69

    THE PROBLEM-SOLVING ASPECT

    Similarities among problems:

    See if there are any similarities between the currentproblem and other problems solved in the past.

    More tools and techniques can be brought in tackling aproblem.

    It is wise to solve the problem independently.

    View the problem from a variety of angles upsidedown, backwards, forwards, etc..

    10

  • 8/6/2019 Problem Solving Techniques Slides

    11/69

    THE PROBLEM-SOLVING ASPECT

    Working backwards from the solution:

    Try to work backwards to the starting conditions if in

    some cases we have the solution to the problem.

    Write down the attempts whatever made along thevarious steps and explorations to systematize ourinvestigations and avoid duplication of effort.

    11

  • 8/6/2019 Problem Solving Techniques Slides

    12/69

    THE PROBLEM-SOLVING ASPECT

    General Problem-Solving Strategies:

    Divide-and-conquer strategy:

    The idea behind this strategy is to split the problem into smaller andsmaller sub-problems until the sub-problems are enough to solve.

    Wide application in sorting, searching and selection algorithms.

    Dynamic programming:

    To build a solution to a problem via a sequence of intermediate steps.

    Good solution to a large problem can sometimes be built up from goodor optimal solutions to smaller problems.

    Greedy search, backtracking and branch-and-bound techniques.

    12

  • 8/6/2019 Problem Solving Techniques Slides

    13/69

  • 8/6/2019 Problem Solving Techniques Slides

    14/69

    TOP-DOWN DESIGN

    Breaking a problem into subproblems:

    Before applying top-down design to a problem, do thegroundwork that gives the outlines of a solution.

    The general outline may consist of a single statement or a setof statements.

    Top-down design suggests that,

    Take the general statements one at a time

    Break them into a set of more precisely defined subtasks.Subtasks should describe how the final goal is to be reached.

    Subtasks need to interact with each other and be preciselydefined.

    14

  • 8/6/2019 Problem Solving Techniques Slides

    15/69

    TOP-DOWN DESIGN

    Choice of a suitable data structure:

    All programs operate on data and the way the data is organized canhave a effect on every aspect of the solution.

    Inappropriate choice of data structure leads to inefficient and difficultimplementations.

    Data structures and algorithms are linked to one another.

    A change in data organization can have a influence on the algorithm

    required to solve the problem.

    There are no rules stating for this class of problems this choice of datastructure is appropriate.

    15

  • 8/6/2019 Problem Solving Techniques Slides

    16/69

    WHILE SETTING UP DATA STRUCTURES

    Be aware of

    Can the data structure be easily updated / searched?

    Does the data structure involve the excessive use ofstorage?

    Is it possible to impose some data structure on aproblem that is not initially apparent?

    16

  • 8/6/2019 Problem Solving Techniques Slides

    17/69

    TOP-DOWN DESIGN

    Construction of loops:

    The initial conditions that need to apply before theloop begins to execute.

    The invariant relation that must apply after eachiteration of the loop and

    The conditions under which the iterative processmust terminate.

    17

  • 8/6/2019 Problem Solving Techniques Slides

    18/69

    TOP-DOWN DESIGN

    Establishing initial conditions for loops:

    Set the loop variables to the values that they wouldhave to assume in order to solve the smallest problemassociated with the loop.

    Usually the number of iterations that must be made bya loop are in the range 0

  • 8/6/2019 Problem Solving Techniques Slides

    19/69

    TOP-DOWN DESIGN

    Finding the iterative construct:

    Once we have the condition for solving the smallestproblem the next step is to extend it to the next smallestproblem.

    For e.g. in the summation of n numbers, the solution for

    n=1 is,i=1

    s=a[1]

    This solution for n=1 is built from the solution for n=0using the values for i and s when n=0 and the twoexpressions

    i=i+1

    s=s+a[i] ----------------------> generalized solutionfor n>0

    19

  • 8/6/2019 Problem Solving Techniques Slides

    20/69

    TOP-DOWN DESIGN

    Termination of loops:

    The simplest condition for terminating a loop occurs when itis known in advance how many iterations need to be made.

    for i=1 to n{

    This loop terminates unconditionally after n iterations.

    }

    A second way in which loops can terminate is when some

    conditional expression becomes false.E.g. while (x>0 and x

  • 8/6/2019 Problem Solving Techniques Slides

    21/69

  • 8/6/2019 Problem Solving Techniques Slides

    22/69

  • 8/6/2019 Problem Solving Techniques Slides

    23/69

    IMPLEMENTATION OF ALGORITHMS

    Choice of variable names:

    Choose appropriate variable and constant names tomake programs more meaningful and easier tounderstand.

    This practice make programs more self-documenting.

    Each variable should only have one role in a program.

    A clear definition of all variables and constants at thestart of each procedure can also be very useful.

    23

  • 8/6/2019 Problem Solving Techniques Slides

    24/69

    IMPLEMENTATION OF ALGORITHMS

    Documentation of programs:

    At the start of each modular part, give a brief accuratecomment.

    Write programs with good documentation so that they canbe executed and used by other people unfamiliar with theworkings and input requirements of the program.

    The program must specify during execution exactly whatresponses and their format it requires from the user.

    The program should catch incorrect responses to itsrequests and inform the user in an appropriate manner. 24

  • 8/6/2019 Problem Solving Techniques Slides

    25/69

    IMPLEMENTATION OF ALGORITHMS

    Debugging programs:

    Carry out a number of tests to ensure that the program isbehaving correctly according to its specifications.

    There may be logical errors in the program that is not shown inthe compilation phase.

    To detect logical errors, build into the programs a set of statements that will print out information at strategic points in

    the computation. These statements can be made conditionally executable.

    If debug then /* debug is a boolean variable that is set to true when */

    { /* debugging output is required for the program */

    printf();

    } 25

  • 8/6/2019 Problem Solving Techniques Slides

    26/69

    IMPLEMENTATION OF ALGORITHMS

    Always work the program by hand beforeattempting to execute it.

    Draw up a two-dimensional table consisting of

    steps executed against all the variables used inthe section of the program under consideration.

    Update the variables in the table as each variableis changed when the statements in the program

    section gets executed.

    A good rule when debugging is not to assumeanything.

    26

  • 8/6/2019 Problem Solving Techniques Slides

    27/69

    IMPLEMENTATION OF ALGORITHMS

    Program testing: Design to solve that it will cope with the limiting and unusual

    cases.

    For E.g., Tests for binary search algorithm.

    Will the algorithm handle the search of array of one element? Will the algorithm handle the case where the value sought is

    at an odd or even array location?

    Will it handle the case where all array values are equal?

    Programs should be accompanied by input and output assertions.

    Build into the program mechanisms that informatively respond tothe user when it receives input conditions it was not designed tohandle.

    Design algorithms to be very general so that they will handle awhole class of problems rather than just one specific case.

    27

  • 8/6/2019 Problem Solving Techniques Slides

    28/69

    PROGRAM VERIFICATION

    The application of mathematical proof techniques to establishthat the results obtained by the execution of a program witharbitrary inputs are in accord with formally defined outputspecifications.

    1. Computer model for program execution.

    2. Input assertion specify any constraints that have beenplaced on the values of the input variables used by theprogram.

    3. Output assertion specify symbolically the results that theprogram is expected to produce for input data that satisfiesthe input assertion.

    4. Implications and symbolic execution.

    5. Verification of straight-line program segments.

    6. Verification of program segments with branches / loops /arrays.

    7. Proof of termination.28

  • 8/6/2019 Problem Solving Techniques Slides

    29/69

    THE EFFICIENCY OF ALGORITHMS

    Design algorithms that are economical in the use ofCPU time and memory because of high cost of computing resources.

    Suggestions that are useful in designing efficient

    algorithms. Redundant computations.

    Referencing array elements.

    Inefficiency due to late termination.

    Early detection of desired output conditions.

    Trading storage for efficiency gains.

    29

  • 8/6/2019 Problem Solving Techniques Slides

    30/69

    FUNDAMENTAL ALGORITHMS

    EXCHANGING THE VALUES OF TWO

    VARIABLES

    Problem Statement:

    Given two variables a and b,

    interchange the values of thevariables.

    30

  • 8/6/2019 Problem Solving Techniques Slides

    31/69

  • 8/6/2019 Problem Solving Techniques Slides

    32/69

    ALGORITHM:

    1. Save the value of variable a in variable t.2. Assign to variable a the value of variable b.

    3. Assign to variable b the value of variable a

    stored in variable t.

    32

    EXCHANGING THE VALUES OF TWO VARIABLES

  • 8/6/2019 Problem Solving Techniques Slides

    33/69

    IMPLEMENTATION:

    void exchange (int a, int b)

    {

    int t; //temporary variable

    t=a;

    a=b;

    b=t;

    }

    33

    EXCHANGING THE VALUES OF TWO VARIABLES

    Applications:Used in SORTING

  • 8/6/2019 Problem Solving Techniques Slides

    34/69

    COUNTING

    Problem Statement:

    Given a set of n studentsexamination marks (in the range0 to 100), make a count of numberof students passed theexamination. A pass is awardedfor all marks of 50 and above.

    34

  • 8/6/2019 Problem Solving Techniques Slides

    35/69

    COUNTING

    Example:

    Given following are the marks obtained by

    5 students in a particular subject.

    45,67,89,34,82

    O/P: Number of students passed the subject is 3.

    35

  • 8/6/2019 Problem Solving Techniques Slides

    36/69

    ALGORITHM:

    1. Prompt and read the number of marks to be processed.2. Initialize count to zero.

    3. While there are still marks to be processed repeatedly doa. Read next mark.

    b. If it is a pass then add one to count.

    4. Print total number of passed students.

    36

    COUNTING

  • 8/6/2019 Problem Solving Techniques Slides

    37/69

  • 8/6/2019 Problem Solving Techniques Slides

    38/69

    SUMMATION OF A SET OF N NUMBERS

    Problem Statement:

    Given a set of n numbers,design an algorithm that adds these

    numbers and returns the resultantsum. Assume n is >=0.

    38

  • 8/6/2019 Problem Solving Techniques Slides

    39/69

    SUMMATION OF A SET OF N NUMBERS

    Example:

    Given following are the set of numbers to

    find the resultant sum.

    45,67,89,34,82

    Resultant sum = 45+67+89+34+82 = 317

    39

  • 8/6/2019 Problem Solving Techniques Slides

    40/69

    ALGORITHM:

    1. Prompt and read total numbers to sum.

    2. Initialize sum for zero numbers.3. While less than n numbers have been summed repeatedly do

    a. Read next mark.

    b. Compute current sum by addin

    4. Print total number of passed students.

    40

    SUMMATION OF A SET OF N NUMBERS

  • 8/6/2019 Problem Solving Techniques Slides

    41/69

  • 8/6/2019 Problem Solving Techniques Slides

    42/69

    SUMMATION OF A SET OF N NUMBERS

    The algorithm uses n additions to sum n

    numbers.

    Applications:Average calculations, variance and least

    square calculations.

    42

  • 8/6/2019 Problem Solving Techniques Slides

    43/69

    FACTORIAL COMPUTATION

    Problem Statement:

    Given a number n,compute n factorial (written asn!) where n>=0.

    43

  • 8/6/2019 Problem Solving Techniques Slides

    44/69

    FACTORIAL COMPUTATION

    Example:

    5!= 5*4*3*2*1=120

    0!=1

    1!=1*1In general,

    n!=n*(n-1)! for n>=1

    (or)

    n!=1*2*3**(n-1)*n for n>=1

    44

  • 8/6/2019 Problem Solving Techniques Slides

    45/69

    ALGORITHM:

    1. Establish n, the factorial required where n>=0.2. Set product p for 0! Also set product count to zero.

    3. While less than n products have been calculated repeatedly

    do,

    a. Increment product count.

    b. Compute the ith product p by multiplying I by the mostrecent product.

    4. Return the result n!.

    45

    FACTORIAL COMPUTATION

  • 8/6/2019 Problem Solving Techniques Slides

    46/69

    IMPLEMENTATION:

    /* computes and returns n! for n >= 0 */int nfactorial(int n)

    {int i; /* loop index representing the ith factorial */int factor; /* i! */{assert (n >= 0)}factor = 1;{invariant: factor = i! after the ith iteration and i

  • 8/6/2019 Problem Solving Techniques Slides

    47/69

    FACTORIAL COMPUTATION

    The algorithm uses n multiplications to compute

    n!.

    Possible to express n! in terms of (n/2)! (Similar

    to calculating nth fibonacci number)

    Applications:

    Probability, Statistical and mathematical

    computations.

    47

  • 8/6/2019 Problem Solving Techniques Slides

    48/69

    SINE FUNCTION COMPUTATION

    Problem Statement:

    Design an algorithm to evaluate thefunction sin(x) as defined by the infiniteseries expansion

    sin(x) = x/1! x3/3! + x5/5! x7/7! + .

    48

  • 8/6/2019 Problem Solving Techniques Slides

    49/69

    ALGORITHM:

    1. Set up initial conditions for the first term that cannot becomputed iteratively.

    2. While the absolute value of current term is greater than the

    acceptable error do

    a. Identify the current ith term.

    b. generate current term from its predecessor.c. add current term with the appropriate sign to the

    accumulated sum for the sine function.

    49

    SINE FUNCTION COMPUTATION

    SINE FUNCTION COMPUTATION

  • 8/6/2019 Problem Solving Techniques Slides

    50/69

    IMPLEMENTATION:

    const float error = 1.0e-6;

    float Abs(float x){

    if(x>0.0)

    return x;

    else

    return -x;

    }

    /* function returns sin(x) with an accuracy of

  • 8/6/2019 Problem Solving Techniques Slides

    51/69

    SINE FUNCTION COMPUTATION

    {invariant: after the jth iteration, i=2j+1 and term = (-1)^j * (x^i)/ i! and tsin is

    sum of first (j+1) terms}while(Abs(term) > error) /* generate and accumulate successive terms

    of sine expression */

    {

    i = i + 2;

    term = -term * x2/(i*(i-1));

    tsin = tsin + term;

    }return tsin;

    {assert: tsin~= sine(x) and abs(term)

  • 8/6/2019 Problem Solving Techniques Slides

    52/69

    GENERATION OF THE FIBONACCI SEQUENCE

    Problem Statement:

    Generate and print the first n terms of thefibonacci sequence where n>=1.

    The first few terms are: 0,1,1,2,3,5,8,13.

    Each term beyond the first two is derivedfrom the sum of its two nearest predecessors.

    52

  • 8/6/2019 Problem Solving Techniques Slides

    53/69

    GENERATION OF THE FIBONACCI SEQUENCE

    Example:

    If n=5, the generated fibonacci sequence

    is 0,1,1,2,3

    New term = preceding term + term before

    preceding term

    53

  • 8/6/2019 Problem Solving Techniques Slides

    54/69

    GENERATION OF THE FIBONACCI SEQUENCE

  • 8/6/2019 Problem Solving Techniques Slides

    55/69

    void Fibonacci()

    {int a,b; /* Fibonacci number variables */

    int i; /* number of Fibonacci numbers generated */

    int n; /* number of Fibonacci numbers to be generated */

    a = 0;

    b = 1;

    i = 2;

    printf("Enter the number of Fibonacci numbers to be generated : ");

    scanf("%d",&n);

    {assert( n > 0)}{invariant: after the jth iteration I = 2j+2 and first I fibonacci numbers have been

    generated and a=(i-1)th Fib. No. and b= ith fib. No}

    while(i

  • 8/6/2019 Problem Solving Techniques Slides

    56/69

    GENERATION OF THE FIBONACCI SEQUENCE

    To generate n fibonacci numbers, n steps are required. The algorithm

    works correctly for all values of n >=1

    Throughout the computation, the variables a and b always contain

    the two most recently generated fibonacci numbers.

    Applications:

    Botany, Electrical network theory, sorting

    and searching.

    56

  • 8/6/2019 Problem Solving Techniques Slides

    57/69

    REVERSING THE DIGITS OF AN INTEGER

    Problem Statement:

    Design an algorithm thataccepts a positive integer andreverses the order of its digits.

    57

  • 8/6/2019 Problem Solving Techniques Slides

    58/69

  • 8/6/2019 Problem Solving Techniques Slides

    59/69

    ALGORITHM:

    1. Establish n, the positive integer to be reversed.

    2. Set the initial condition for the reversed integer dreverse.3. While the integer being reversed is greater than zero do,

    a. Use the remainder function to extract the rightmost digitof the number being reversed.

    b. Increase the previous reversed integer representation

    dreverse by a factor of 10 and add to it the most recentlyextracted digit to give the current dreverse value.

    c. Use integer division by 10 to remove the rightmost digit fromthe number being reversed.

    59

    REVERSING THE DIGITS OF AN INTEGER

  • 8/6/2019 Problem Solving Techniques Slides

    60/69

    Dreverse(int n)

    {

    int reverse;

    {assert: n>=0 and n contains k digits a(1), a(2), a(3), ., a(k)}

    reverse=0;

    {invariant: after jth iteration, n=a(1), a(2), a(3), .a(k-j) and reverse = a(k), a(k-1) .a(k-j+1)}

    while (n>0)

    {

    reverse=reverse*10+((n % 10));n=n/10;

    }

    {assert: reverse = a(k), a(k-1),..a(1)}

    printf(Reversed number=%d,reverse);

    }

    The number of steps to reverse the digits in an integer is directlyproportional to the number of digits in the integer.

    Applications:

    Hashing and information retrieval, database applications. 60

    REVERSING THE DIGITS OF AN INTEGERImplementation:

  • 8/6/2019 Problem Solving Techniques Slides

    61/69

    BASE CONVERSION

    Problem Statement:

    Convert a decimal integerto its corresponding octal

    representation.

    61

  • 8/6/2019 Problem Solving Techniques Slides

    62/69

    EXAMPLE:

    The octal representation of decimal 275 is

    423.

    62

    BASE CONVERSION

  • 8/6/2019 Problem Solving Techniques Slides

    63/69

    BASE CONVERSION

  • 8/6/2019 Problem Solving Techniques Slides

    64/69

    void basechange( int n, int newbase)

    {

    int i; /* index for new digit output array */

    int ascii; /* ascii value of current digit */int ndigit; /* current counter of new digits computed*/

    int q; /* current quotient */

    int r; /* current digit for newbase representation*/

    int zero; /* ascii value of zero character*/

    char newrep(100); /* output array */

    {assert: n>0 and 20;i--) printf(%c,newrep[i]);

    }

    64

    Implementation:

  • 8/6/2019 Problem Solving Techniques Slides

    65/69

    Applications:

    Interpretation of stored computer data and

    instructions.

    65

    BASE CONVERSION

  • 8/6/2019 Problem Solving Techniques Slides

    66/69

    CHARACTER TO NUMBER CONVERSION

    Problem Statement:

    Given the characterrepresentation of an integer convert

    it to its conventional decimal format.

    66

  • 8/6/2019 Problem Solving Techniques Slides

    67/69

    CHARACTER TO NUMBER CONVERSION

    Example:

    Character representation 125 when

    converted to decimal format results in

    125.

    67

  • 8/6/2019 Problem Solving Techniques Slides

    68/69

    CHARACTER TO NUMBER CONVERSION

    Algorithm:

    1. Establish the character string for conversion to decimaland its length n.

    2. Initialize decimal value to zero.3. Set base0 value to the ascii or ordinal value of 0.

    4. While less than n characters have been examined do

    a. Convert next character to corresponding decimaldigit.

    b. Shift current decimal value to the left one digit andadd in digit for current character.

    5. Return decimal integer corresponding to input characterrepresentation.

    68

  • 8/6/2019 Problem Solving Techniques Slides

    69/69

    CHARACTER TO NUMBER CONVERSION

    Implementation:

    int chrtodec(char str[],int n)

    {

    int i; /*Index for count of characters converted*/

    int dec /*Used to build converted decimal integer*/

    int base0/*ascii of character 0*/

    {assert: n>=0 and string [1..n] represents a non-negative number}

    dec=0;

    base0=0;

    {invariant: after the ith iteration, dec contains the I leftmostdigits of the string in integer form and i