Computational Problem Solving PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Chapter 9

Computational Thinking and Problem Solving


Computational problem solving is not programming alone. It is a process that involves four
phases namely,

– Analyzing the problem

– Designing a solution to a problem

– Implementing the solution

– Testing the solution

In problem analysis phase, one has to analyze the problem clearly. The input data should be
analyzed and the expected output should also be defined. Then a solution should be
designed. In designing a solution, the types of data should be identified, how the data is
represented and structured is to be figured out and then an algorithm should be worked
out for solving the problem. Once the data representation and algorithm are finalized, the
algorithm can be implemented using a programming language. Then, the program is tested
for a selected set of problem instances. If any errors are detected, they are corrected and
then tested again.

9.1 Problem Analysis

Initially, the problem should be analyzed clearly. As an example, consider the Man,
Cabbage, Goat, Wolf [MCGW] problem. A man stays on the east side of a river with a
cabbage, goat and a wolf. He has to go to the other bank of the river carrying his
possessions. He has a small boat which can accommodate only one of his possessions along
with him. If he leaves the wolf and goat together, the wolf will eat the goat. If he leaves the
goat and the cabbage together, the goat will eat the cabbage. He has to find a solution to
carry all his possessions to the other bank. Given this problem, the problem has to be
analyzed for a solution. One way of finding a solution to this problem is to try all
possibilities and get a solution. This approach of finding a solution is called as the Brute
Force Approach. The problem is analyzed to identify the input data and the expected
output. The input data is the four elements, Man, Cabbage, Goat and Wolf on the East side of
the river. The expected output is Man, Cabbage, Goat and Wolf on the West side of the river.
Having analyzed input and output data, let us move on to the next phase of problem
solving.
Problem analysis involves the process of defining the problem. It involves the analysis of
the problem and generating appropriate response patterns for its solution. The four steps
in defining a problem are

i. Data collection and Requirements Gathering: In this phase, the data required for the
solution is collected and the missing gaps are filled in.

ii. Domain Knowledge: The domain knowledge is obtained by consultation with people who
are familiar with the problem domain. Ex. If a banking software is developed, it is
important to understand the functionalities by consulting with the bank employees.

iii. Viewing the Problem first hand: As far as possible, every detail about the problem
should be obtained as first hand information from the client.

iv. Confirming all the findings

9.1.1 Problem Solving: A Software Perspective

Software development also follows a similar style as the general problem solving.

9.1.2 Stakeholders of a Software

Customer / Client: A client is the one who places the request for software to be developed.

Software Developer: The developer team usually consists of a team to build the software.

User: The end user is the one who will use the software finally.

In software development, the software analysis is equivalent to the problem definition and
design+implementation is equivalent to the problem solution.

In software projects the problem definition starts with the requirement analysis. Analysis
needs the customer and developer interaction to prepare a legal agreement. The
requirement document records what is to be built and not how it is to be built. Successful
design and implementation requires an adequate analysis.

9.1.3 Types of Requirements

There are two major requirements for a problem in software domain.

1. Functional Requirements: These requirements specify the specific tasks or the


functionalities the software should perform.

2. Non-functional Requirements: These requirements define the other characteristics and


constraints related to the software.
In general, the functional requirements include

• Input
• Processing
• Output
• Error handling
The non-functional requirements include

• Reliability
• Safety
• Security
• Performance
• Delivery
• Help Facilities

Example 1: A Counter Application

Purpose: To count items (up and down)

Required components:

– A display
– Set/Reset button
– Up button
– Down button
– Number buttons (from 0 to 9)
– Close Button

Functional Requirements

Button Functionality Description


Name
B1 Display  The display should display the current value of
the timer/counter.
B2 Set/Reset  Pressing the Reset button should display zero or
the initial value that is being set, in the display.
B3 Up  Pressing the up button should increment the
value in the display by 1.
 If the value on display is the maximum limit,
pressing this button has no effect.

B4 Down  Pressing the down button should decrement the


value in the display by 1.
 If the value on display is zero, pressing this button
has no effect.

B5 Close  Pressing the close button should close the counter


window
B6 … B15 Number buttons  Pressing a number button should display its value
on the display; If the display already has some
digits, pressing the number button should append
its value to the digit on the display.

Example 2:

Media Player application

An application that would play a video file with required buttons for the user to play, pause,
stop the video and for raising and lowering the volume.

Functional Requirements

Button Functionality Description


Name
B1 Play • Clicking the play button should start playing the
video.
• If the video is paused, it should resume at the point
of pausing.
• It should play in a new window.
• The pause button should display pause image when
the video is playing.
B2 Pause • Clicking the pause button causes the video to pause
at the current play location.
• This button should be disabled when the video is not
being played.
• Clicking the pause button causes the pause/play
button to function as a play button, displaying a play
button image
B3 Raise volume  Clicking the raise volume button while the volume is
less than
maximum level causes the volume to increase by 1
point
 Clicking the raise volume button while volume is at
the maximum
level doesnothing.
B4 Lower  Clicking the lower volume button while the volume
volume is greater than
silent level causes the volume to decrease by 1 point
 Clicking the lower volume button while volume is at
silent level does nothing.

Once the functional requirements are gathered, the requirements should be validated, to
check whether they are correct, consistent or complete. Correctness means that customers,
users, and developers understand in the specified requirements in the same way. So, to
check correctness, good functional requirement can be translated into a logical proposition.
One example of converting the requirement V2(pause) to logical expression is as follows:

– “If the video has already finished playing, then this button has no effect”.

– F= the video has finished playing.

– N = no change kind of action.

The expression is F implies N (F  N)

The requirements should be validated for consistency also. Consistency means no two
functions contradict each another. For example, consider adding a new function V5 to
restart with the description “When the video is playing and reaches the end, it immediately
restarts playing with the play/pause button functioning as a play button.” This would
contradict V1(play) specification that play/pause button should function as a pause button
when videos are playing.

The requirements should also be verified for completeness. Completeness takes careful
consideration to be certain that every possible scenario has been considered and explained
in one or more requirement. The two ways to incorporate completeness includes:

• Manual checking

• Adding more functions

Another way to formally ensure completeness is to check all possible combination of


situations by constructing State-activity table.
9.2 Designing a Solution to the Problem

Solution design to a problem consists of two important activities. One is the data
representation and the other one is the algorithm design. The representation should
capture all the relevant aspects of the problem and the algorithm should be designed in
such a way that it solves the problem using that representation.

9.2.1 Data Representation

Appropriate representation of data is a relevant aspect of computer science. Data can be


represented in various ways. For example, if you have simple problems with less number of
data, you can choose variables of appropriate data types for representing the data. Data can
be represented as numbers, characters, Booleans. It may also be represented using lists,
tables, or a combination of data types (structure, class).

For example, consider the problem of finding the simple interest. You can represent the
input data principal amount using an integer variable, number of years using another
integer variable and rate of interest using a floating point variable. The output value can be
stored in a floating point variable. Choosing independent variables for representation
would be appropriate if the problem involves only a few data.

If you have a problem of finding the day of the week in which a date falls, the required data
can be represented as follows: The date can be represented using a date data type like, 25-
May-2017. The day of week of the first day of the month can be represented using a string
variable like ‘Mon’.

When the problem has a collection of data of the same data type, a one dimensional list
called as an array would be the appropriate representation. For example, in the Man, Cow,
Goat, Cabbage problem, the data can be represented as follows. The elements can be stored
in one list of string data type as [M, C, G, W] and their initial states can be stored using
another list of character data type as [E, E, E, E] to denote the east bank. The final state of
the elements can be represented as [M, C, G, W] and [W,W,W,W].

Similarly, if you have a problem in which you have to represent the seasons of a year, you
can use a string list like

[Summer, Spring, Autumn, Winter]

The colors of a rainbow can be represented using a list of character data type like,

[V, I, B, G, Y, O, R]
The marks of a student in five subjects can be represented using a list of integer data type
like,

[75, 67, 59, 67, 69]

Complex problems with more dimensions of data of the same data type they can be
represented using multidimensional list or multidimensional arrays. Two dimensional
arrays are also called as tables or matrices. For example, matrices can be represented using
two dimensional lists.

Ex.

1 2 4

4 5 6

3 8 7

The data for a travelling salesman problem can be represented using a list of lists. Ex.

[ [‘Atlanta’, [‘Boston’, 1110], [‘Chicago’, 718], [‘Los Angeles’, 2175], [‘New York’, 888],

[‘San Francisco’, 2473] ],

[‘Boston’, [‘Chicago’, 992], [‘Los Angeles’, 2991], [‘New York’, 215], [‘San Francisco’, 3106] ],

[‘Chicago’, [‘Los Angeles’, 2015], [‘New York’, 791], [‘San Francisco’, 2131] ],

[‘Los Angeles’, [‘New York’, 2790], [‘San Francisco’, 381] ],

[‘New York’, [‘San Francisco’, 2901] ] ]

Similarly, for chess problem, the data can be represented using a table or two dimensional
list.

If the problem consists of multiple data of different data types, the data can be represented
using complex data types like structures. For example, if you want to represent a data for
an object like a book, it can be represented using a structure:

struct book

bookId number, bookTitle string, author string, no_of_pages number, price number

}
9.2.2 Algorithm Design

Once the data in a problem is represented, the solution can be designed systematically. The
step by step solution to a problem is called as an algorithm.

9.3 Implementing the Solution

Once the algorithm, is designed, an appropriate programming language is selected and the
algorithm is implemented using the programming language.

9.4 Testing

Programming errors are pervasive, persistent and inevitable. Software testing is an


essential part of software development. Therefore, the developed program should be tested
with sample data sets.

9.5 Elements of Computational Thinking

In essence, Computational thinking is the thought process involved in formulating a


problem and expressing its solutions in such a way that a computer can effectively carry
out. Computational thinking involves some techniques that make the solution to a problem
simpler and effective. Such techniques can be called as the elements or key techniques or
cornerstones of computational thinking. The important elements in computational thinking
are:

• Decomposition: Breaking down data, processes, or problems into smaller,


manageable parts

• Abstraction: Hiding irrelevant complexities and exposing the relevant details alone.

• Logical reasoning/ Pattern Recognition: Observing patterns, trends, and


regularities in data and identifying the general principles that generate these
patterns. It involves looking for similarities among and within the problems

• Algorithm Design: Developing the step by step instructions for solving this and
similar problems

9.5.1 Problem Decomposition

The process of breaking down a complex problem or system into smaller sub problems
with more manageable parts is known as Problem Decomposition. Decomposition helps to
solve complex problems and manage large projects. Large problems can be tackled with
“divide and conquer”. Decompose the problem so that, each sub problem is at (roughly) the
same level of detail. Each sub problem can be solved independently. The solutions to the
sub problems can be combined or integrated to solve the original larger problem. This
approach of solving a problem is known as top down approach or modular programming.

Ex. 1 Making Pizza

Ex. 2 Organizing a school trip

This involves tasks such as arranging staff, booking coaches, booking hotels, getting
consent letters, checking weather, checking resources etc. Each task can be assigned to a
different student or to different student teams.

Ex. 3 Planning course curriculum

Typically this would be decomposed as years and subjects, further decomposed into terms,
units of work and individual lessons or activities. Notice how the project is tackled by a
team working together, and how important it is for the parts to integrate properly.

Ex. 4 Binary Search


A comparison with the linear search shows that the number of steps is more and the search
is slower in the case of linear research.

Ex. 5 Creating an App


To decompose this task, you would need to know the answer to a series of smaller
problems:

• What kind of app you want to create

• What your app will look like

• Who the target audience for your app is

• What your graphics will look like

• What audio you will include

• What software you will use to build your app

• How the user will navigate your app

• How you will test your app

• Where you will sell your app

This list has broken down the complex problem of creating an app into much simpler
problems that can now be worked out. You may also be able to get other people to help you
with different individual parts of the app. For example, you may have a friend who can
create the graphics, while another will be your tester.

Why is Decomposition Important?

If a problem is not decomposed, it is much harder to solve. Dealing with many different
stages all at once is much more difficult than breaking a problem down into a number of
smaller problems and solving each one, one at a time. Breaking the problem down into
smaller parts means that each smaller problem can be examined in more detail. Similarly,
trying to understand how a complex system works is easier using decomposition.

Advantages of Decomposition

– Different people can work on different sub problems /Modules.

– Parallelization may be possible.

– Maintenance is easier.

Disadvantages of Decomposition

– The solutions to the sub problems might not combine to solve the original
problem.
– Poorly understood problems are hard to decompose.

9.5.2 Abstraction

To drive a car - we don’t need to know how the car works under the hood. An abstraction is
anything that allows us to concentrate on important characteristics while deemphasizing
less important, perhaps distracting, details. Focusing on relevant things and hiding the
irrelevant things is known as abstraction. Abstraction is the process of making an easier to
understand version of a complex system by focusing only on the key information.
Abstraction helps in reducing the complexity of systems being considered. Abstraction
allows controlled exposure to details as a series of layers. Computer scientists learn to
focus on the most important issues through abstraction. An abstraction is the distinction
between an entity’s external properties and its internal representation when perceived by
a third party (observer) who wants to use that entity. Abstraction creates a ‘component’ by
ignoring their internal representation. Abstraction allows us to combine similar
components at the same level and to build upon components at lower levels to create
higher order components.

Types of Abstraction

Control abstraction: Abstraction of action (code) is called control abstraction. It involves


use of subprograms.

Ex. Library functions like sqrt(), pow(), floor()

Data abstraction : Abstraction or hiding of data is known as data abstraction. Data


abstraction is also known as data hiding.

Ex. Classes with private data members

Advantages of Abstraction

 Abstraction enhances the internal implementation without affecting outside world.

 Every user will get his own view of the data according to his requirements and will
not get confused with unnecessary data.

 Abstraction provides ability to simulate real-world event much more effectively.

9.5.3 Logical Reasoning or Pattern Recognition


Programming is an activity that often relies upon knowledge of patterns. Therefore, logical
reasoning is the basis for software development. There are two types of logical reasoning
or pattern recognition.

– Deductive Reasoning

– Inductive Reasoning

Deductive Reasoning

Arriving at a conclusion for a specific instance from a general rule or pattern is known as
deductive reasoning. Deductive reasoning is used for solving many problems.

Case 1: Sequential tasks

Sequential task or sequential logic involves the ordering of tasks one after the other (Line
by line execution).

Example 1: Sending an Email message

1. Specify recipient’s address

2. Send a message

Here step 1 and step 2 cannot be interchanged

Example 2: Sequencing of instructions

1. priceWithTax  0

2. itemCost  100

3. priceWithTax  itemCost + itemCost * 0.055

4. priceWithTax  105.5

Changing the order of instructions will result in wrong output

Case 2: Cause-Effect Relationships

Functional requirements of a good problem definition are English forms of logical


statements. For example, If…then => Implies. Most of the computer programs are a
collection of cause-effect relationships. A cause-effect relationship consists of a logical
condition (the cause) that forces the program to perform some task (the effect); C  E

Examples
– The program controlling an online website must choose when to bill a
customer.

 IF the user has struck the Confirm Purchase button, THEN initiate
billing procedures.

 C B

– The program in your digital camera chooses how long to leave the shutter
open when taking a picture.

 IF the camera sensor detects adequate exposure, THEN close the


camera shutter.

 SC

– The program controlling your portable music player chooses which song to
play next.

 IF a song has just finished playing, THEN begin playing the next song
in the playlist.

 FN

Cause-Effect Scenarios [A few more examples]

Cause Effect
Username and password have been Check if username password
entered combination is valid
User clicks the close button of a window Remove the closed window from the
display
Laptop battery is below 10% Popup a window warning user for low
power
A new email message arrives at the Ring a bell to notify the user
inbox

Cause – effect relationship is used to apply general rules for a specific situation. Therefore,
it is an application of deductive reasoning.

Case 3: Identifying algorithmic patterns

Ex. Swapping

1. Store the value of the first variable in a temporary variable. [temp=x]


2. Store the value of the second variable to the first variable. [x=y]

3. Transfer the contents of the temporary variable to the second variable [y=temp]

Case 3: Repetition or Iterations

Pattern of repeating something n times.

Ex. Sum of the digits of a number

r =n%10

s=s+r

n=n/10

Repeat the above lines of code while n>0

Other Deductive Patterns

Other deductive patterns include the following patterns:

• Patterns for successful software testing

• Patterns to provide better software security

• Patterns of different software performance

Inductive Reasoning

Making generalized decision after observing or witnessing, repeated specific instances is


called inductive reasoning. A general rule is derived based on a specific pattern. The
general conclusion that is formed based on a specific pattern is known as a conjecture.

Examples

9.4 Algorithm Design


A step by step solution to a problem is known as an algorithm. An algorithm consists of a
sequence of steps to solve a given problem. An algorithm should be self-contained. The
steps should not be ambiguous. It should produce an outcome when executed. Algorithms
may be designed to perform one or multiple tasks. Algorithms are written in plain natural
language with some specific terminology. Algorithms can be designed in various ways.
Based on the methods, algorithms can be of different types as follows.

9.4.1 Direct Calculation Method

If the problem is a simple problem for which the solution can be found by the application of
a formula, the solution can be found out using the direct calculation method.

Ex. Finding the area of a circle

area = 3.14 * r * r

Converting temperature from Celsius to Fahrenheit.

F = 9/5*C + 32

Day of week problem

For example, if 01-May-2017 falls on Monday, what day is 25-May-2017?

Algorithm:

– Find 25 mod 7 (=4)


– Day of the week of 25-May-2017 is 4 days from Monday which is Thursday.

9.4.2 Brute Force Approach

For problems like the MCGW problem, the algorithm can be found by Brute Force
approach. In this approach, the solution is found out by trying out all possible solutions and
then choosing the best solution from the list of possible solutions.

Ex. Solution to MCGW problem

Initial state: [M, C, G, W] [E, E, E, E]

Final or Goal state: [M, C, G, W] [W, W, W, W]

State 2: [M, C, G, W] [W, E, W, E]

State 3: [M, C, G, W] [E, E, W, E]

State 4: [M, C, G, W] [W, W, W, E]


State 5: [M, C, G, W] [E, W, E, E]

State 6: [M, C, G, W] [W, W, E, W]

State 7: [M, C, G, W] [E, W, E, W]

State 8: [M, C, G, W] [W, W, W, W]

9.4.3 Using Standard algorithms

For problems where standard algorithms exist, they can be used for solving them.

Ex.

Travelling Salesman problem

Sorting an array

Chess problem

9.4.4 User defined Algorithms

For problems, that do not have standard algorithms, new algorithms can be designed by
the programmers.

9.4.5 Heuristic Algorithms

Algorithms that work well in general but are not guaranteed to give the correct result for
each specific problem are known as heuristic algorithms. Such algorithms find a solution
out of all possible ones, but they do not guarantee that the best would be found. Therefore
such algorithms are considered to be approximate and not accurate algorithms. These
algorithms arrive at fast solutions and may find a solution that is close to the best solution.
They always give a good solution but not the best. They are most often employed when
approximate solutions are sufficient and the exact solutions are computationally complex
and expensive.

Ex. Genetic Algorithms, Particle swarm optimization

9.6 Representation of Solutions to Problems

i. Algorithm
The solution to a problem can be represented as step by step instructions in
plain natural language. This is known as an algorithm.
ii. Flowchart
The pictorial representation of the solution (algorithm) is known as a flowchart
iii. Pseudocode
Representing the solution using some specific keywords is called as a
pseudocode.
iv. Program
Implementing the solution in a programming language is known as a program.

9.7 Essential Characteristics of an Algorithm

i. Input
An algorithm should have an input. The input may be a static or a dynamic one.
Static inputs are provided to the program before execution whereas dynamic
inputs are provided during runtime. Input refers to the data that is to be
transformed during the computation to produce the output.
ii. Output
The data or information that is resulting from the computation is called as the
output.
iii. Definiteness
An algorithm should specify the clear sequence of the events. It should describe
the details of each step including how to handle errors.
iv. Effectiveness
An algorithm should contain feasible instructions. The instructions should not be
ambiguous.
v. Finiteness
An algorithm must eventually stop.

9.8 FlowChart

Flowchart is the pictorial representation of an algorithm. A flowchart uses standard


symbols for representing the solution to a problem.

Standard Flowchart Symbols

Flowchart Symbol Meaning


The oval symbol or terminator symbol is
used for representing Start or Stop

The parallelogram symbol is used for input


and output

The rectangle symbol is used for process.


This is the symbol used for an equation or
formula or an assignment.
The rhombus symbol is used for decision
making.

A labelled circle is used as a connector. This


is used to connect different parts of a
flowchart

An arrow represents the flow of instructions


in a flow chart

This symbol represents a document

This is the symbol for manual input

If a flowchart spans across multiple pages,


this symbol can be used to connect the flow
chart parts across multiple pages.

This symbol is used to denote delay in a


process
This symbol denotes input from a magnetic
disk

9.8.1 Flowchart Structures

9.8.1.1 Sequential Logic

Sequential logic denotes the series of actions performed in a sequence.

Example 1
Example 2
9.8.1.2 Selection

Selecting one of two possible actions based on a particular condition is called selection.
This logic is used when the solution to a problem involves a decision making.

Example 1

Example 2
9.8.1.3 Iteration

If a few tasks have to be repeated in a solution, then the logic is known as iteration logic.
Loop structures are used for solving iteration. A loop tests a condition and if it is satisfied,
performs an action. Then it tests the Iteration structure condition again. If the condition is
still satisfied, the action is repeated. This is repeated until the condition is not satisfied.

Example 1
Example 2
9.8.2 Advantages of Flowcharts

• Communication: Flowcharts are better way of communicating the logic of a system.

• Effective Analysis: With the help of flowchart, problems can be analyzed in more
effective ways.

• Proper Documentation: Program flowcharts serve as a good documentation, which


is needed for various purposes.

• Efficient Coding: Flowcharts act as a guide or blueprint during system analysis and
program development phase.

• Efficient Program Maintenance: Maintenance of operating program becomes easy


with the help of flowchart.

• Proper Debugging: Flowchart helps in debugging process.

You might also like