problem solving (computing)

31
CS101 Introduction to computing Problem Solving (Computing) A. Sahu and S. V .Rao Dept of Comp. Sc. & Engg. Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati 1

Upload: others

Post on 12-Dec-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

CS101 Introduction to computing 

Problem Solving(Computing) 

A. Sahu and S. V .RaoDept of Comp. Sc. & Engg.Dept of Comp. Sc. & Engg.

Indian Institute of Technology Guwahati

1

Outline• Problem Solving : Process involves 

– Definition, Analysis, Solution Approaches,Definition, Analysis, Solution Approaches, Correctness, Programming, Testing 

• Loop invariant and loop terminationLoop invariant and loop termination• Many Problem Solving Examples

7 P bl (S l ti M th d t i )–7 Problems (Solution Method not given)–3 problems (Solution Method given)

Reference : R G Dromey, “How to solve it byReference : R G Dromey,  How to solve it by Computer”, Pearson Education India, 2009 

2

Generic  Problem Solving using Computer 

• Step 1: Problem Definition in Englishp g• Step 2: Solution Approaches

Is any standard method available ? Proven to be– Is any standard method available ? Proven to be correct.

– If yes use that to draw flow chart– If yes, use that to draw flow chart

• Step 3: Flow chart  and Pseudo codei d• Step 4: Write C Code

• Step 5: Compile and Run• Step 6: Test the code for error

3

Steps in Programming : Very Simplified PictureSimplified Picture

• Problem Definition & Analysis• High Level Strategy for a solution• Arriving at an algorithmg g• Verification and analysis of the algorithm• Encoding the algorithm as a programEncoding the algorithm as a program 

(in a programming language like C)• Testing the program• Testing the program

E h i i d h h l lEach step iterative and the whole process also iterative 

Problem Definition & Analysis• Understanding the problem is : Half the solution  ☺☺☺– You appearing for some exam, and you are not able to understand the question

• Can you find solution without understanding the question?  ☺☺☺ ==  > NO

• A precise solution requires a precise definition• This step leads to clear definition of the problem• The definition states WHAT the problem to be solvedsolved

• Rather than HOW the problem to be solved

Problem Definition &  Analysis CntdCntd..

• Analysis done to get a complete and consistent specification

• Specification precisely and• Specification precisely and unambiguously states–Constraints on the inputs–Desired Properties of the outputsDesired Properties of the outputs

High Level Strategy

• This is a crucial and most difficult stepp• Most creative part of the whole processprocess

• No standard recipe for arriving at a strategy

• Compare alternate techniques toCompare alternate techniques to arrive at the best

Analysis of Solution Approaches• Correctness and Efficiency (C & E )

– Algorithm/Approaches are analyzed for  C & Eg pp y– C & E are precise and detailed enough

• Correctness analysisCorrectness analysis  – To ensure the algorithm solves the given problem– Involves a mathematical proof that algorithmInvolves a mathematical proof that algorithm satisfies the specification; termination proofs 

• Efficiency analysis : To determine y y– amount of time or number of operations – amount of memory required for executing the y q galgorithm 

Algorithm • The algorithm is part of the blueprint or plan for 

the computer program, an algorithm is:“An effective procedure for solving a class of problems in a finite number of steps.”E l ith h ld h th f ll i 5• Every algorithm should have the following 5 characteristic features:

Definiteness: Each step must be define precisely– Definiteness: Each step must be define precisely– Effectiveness : its operationsmust be basic 

enough to be able to be done exactly and in finite length of time  

– Termination:must terminate after a finite number of stepsnumber of steps 

– Input and  Output

Programming (coding Approach)• Writing programs in a programming language (in C) is the last step

• This step is called implementation or coding– No doubt it is important and one need to pay attention and care

– But it is somewhat straight forward

Testing the Program• Program is compiled to generate 

– Machine code that can run on a specific machine

• Errors could be introduced – In the programming processIn the programming process – Or by the compiler (suppose to be good ☺☺,  but 

do many optimization)y p )

• Hence it is essential that the generated code – Is run with specific set of inputs to see whether it– Is run with specific set of inputs to see whether it 

produces the right outputs

Testing the Program• Syntax/Grammar errors eliminated in the step• Some logical errors may also be caught in this g y gstep

• Gives an idea about time and spaceGives an idea about time and space requirements for executing the program

Problem Solving Strategies

• Arriving at a strategy and an algorithm is themost crucial and difficult stepthe most crucial and difficult step

• Crucial because behavior of the final code is dependent on thisdependent on this

• Difficult because it is a creative step• Though many standard techniques are available no general recipe to ensure success

Problem Solving Strategies• New problems may require newer strategies

• Problem solving skills can be developed only with experiencey p

• Main emphasis of the course– To expose you to various problem solving– To expose you to various problem solving strategies by way of examples

• The programming languages is for• The programming languages is for concreteness and execution of your ideas

Problem Solving Strategies• Given a Problem P • You may come up many Approaches/ strategies : App1, App2,  App3, App4, Appm

• If we are not able prove the correctness by loop termination and loop invariant of some approaches– We cannot call that Approaches as Algorithm

• Suppose App2 and   App3: We are not able th t f th th A 2prove the correctness for them , then App2 

and   App3 are not algorithms by definitionAl ith f P A 1 A 2 A 3 A 4– Algorithms for P: App1, App2,  App3, App4, Appm

Illustrative Examples : I • Problem: Given a set of students examination marks (range 0 to 100) count the number ofmarks, (range 0 to 100), count the number of students that passed the examination and those passed with distinctionthose passed with distinction–Pass mark: >=50–Distinction mark: >=80

• Study the problem and analyze• Is the problem definition clear?

The Strategygy1. Keep two counters one for pass and the 

other for distinction2. Read the marks one by oney3. Compare each mark with 50 and 80 and 

increase the appropriate countersincrease the appropriate counters4. Print the final results

Flow Chartp_cnt = 0,  d_cnt=0p_cnt = 0,  d_cnt=0

there is next_markthere is next_marktrue

Input mark false

mark > 50mark > 50p_cnt++true

mark > 80mark > 80d_cnt++true false

Output  p_cnt, d_cntfalse

Pseudo Code Input: List of marksO t t t di ti ti tOutput: pass_count, distinction_count

1. Initialize p_count, d_count to zero2. Do while (there is next mark)  ( _ )

1. If next_mark => 50 then increment p_count2 If next mark => 80 then increment d count2. If next_mark > 80 then increment d_count

3. Print p_count, d_count

Observations• The algorithm is a sequence of precise instructions– Involves variables for storing input, intermediate 

and   output data– Uses high level operations and instructions– Data types closer to the problem domain

• What does the algorithm do for marks that do not lie between 0 and 100 ?

• Rewrite the algorithm– Including  above boundary case 

Correctness of the Solution• Is the solution correct?• Show that• Show that 

– if an input satisfies the input constraints – then output produced satisfies required– then output produced satisfies required 

properties• Input Constraintsp

– List of integers lying between 0 and 100• Required Property

– p_count contains the no. of marks >= 50– d_count contains the no. of marks >= 80

• Termination is an implicit requirement 

How to establish correctness• Establish that 

– if input constraint is satisfied thenif  input constraint is satisfied then – the program will terminate producing the output that satisfies the desired propertiesoutput that satisfies the desired properties

• How to establish?– Testing?– How many inputs will convince you?– 5, 10, 100 – in general infinite

Testing establish presence of bugs neverTesting  establish presence of bugs never their absence

Testing a simple programfloat a, b;scan(“%f %f”, &a,&b);i tf(“R lt %f” +b)

• How many test you require to conclude this d i ki tl

printf(“Result=%f”, a+b);

code is working correctly. • A is 32bit, b is 32 bit, number different 

32 32 64options : 2 32*232=264

• Suppose in one second you can do 214 test , Still you will take 250 s=236h=7.8x106 years Testing establish presence of bugs neverTesting  establish presence of bugs never 

their absence

Mathematical ArgumentMathematical Argument• Prove the correctness using mathematical arguments

• Proof of Correctness involves two‐Step• Proof of Correctness involves two‐Step argument– Loop Invariants– Loop Termination

Loop invariantsp• A condition (logical expression) involving program variables– It holds initiallyIt holds initially– If it holds before start of iteration, it holds at the end;at the end; 

– The condition remains invariant under i iiteration

Loop invariantsLoop invariants• Loop invariant for our example

– p_count hold the total number of pass in the marks read so far  

– d_count hold the total number of distinction in the marks read so fardistinction in the marks read so far

Loop invariants holds at every iteration if it holds initiallyLoop invariants holds at every iteration if it holds initially• In particular, it holds at the end• Input constraints imply loop invariant initially

L i i t t th d i li t t diti• Loop invariant at the end, implies output condition

Loop Termination• Non termination is an important source of 

iincorrectness. • Correctness proof includes termination proof• Bound on iteration

– An integer valued expression called bound g pfunction that reduces in each iteration

– When the bound function reaches 0, loop pterminates

• For our example, the bound function is:p ,length of the input list yet to be processed 

Efficiency AnalysisEfficiency Analysis• How many number of operations?

– In each iteration of the loop, constant number of comparisonsp

• Can we improve this?f h b i l h 0 h i– If the number is less than 50, there is no need for comparing it with 80.

• Rewrite the algorithm

C Programint main(){(){

int p_cnt=0,d_cnt=0, mark;int there_is_next_mark=0;do { printf(“Is there next mark..[0/1]\n”);scanf(“%d”, &there_is_next_mark);if(there is next mark==0) break;if(there_is_next_mark 0) break;printf(“Enter mark..\n”);scanf(“%d”, &mark);if(mark<0 || mark >100) return 0;//exit(0)if(mark>50){ p_cnt++;

if (mark>80) d cnt++: }if (mark>80) d_cnt++: }}while(1);printf(“pass_cnt=%d,dist_cnt=%d”, p_cnt, _ _ _d_cnt);

}

Problem Solving Example • Set A  (Solution Method not given)

1 N h f X1. Nth Power of X 2. Square root of a number 3. Factorial of N 4 Reverse a number4. Reverse a number 5. Finding value of unknown by  question 

answersanswers 6. Value of Nth  Fibonacci Number7. GCD to two numbers

30

Problem Solving Example 

• Set B  (Solution Method given)1. Finding values Sin(x) using series sum 2 Value of PI2. Value of PI 3. Finding root of a function Bisection  

Methods

31