CSLTR Week03
CSLTR Week03
STRATEGY
Fundamentals of programming – Cơ sở lập trình
Advisor: Trương Toàn Thịnh
1
ALGORITHM
Conception
Description
Analysis
Example
2
CONCEPTION
Before modern computer, we solve the practical
problems ourselves
Problems having big data, high precision with
real time we cannot solve ourselves
Appearance of electronic computer is a necessary
thing with ‘As quick as a flash’ by nature
We need to model practice problems into data
structures
We instruct computer how to solve the practical
problems
Method of dealing with practical problems is
called algorithm 3
CONCEPTION
Some algorithm standards
◦ Limitation: finish execution after amount of
processing–steps
◦ Determination: Each processing–step must be
apparent
◦ Existence of input data: Algorithm needs a valid
input data
◦ Existence of output data: give a expected result
corresponding to valid input data
◦ Efficiency: Each processing–step must have
limited – deterministic time
◦ 4
CONCEPTION
Describe algorithm
◦ Natural language
◦ Flow – chart
◦ Pseudo – code
◦ High – level programming language
Implement algorithm
◦ Turn algorithms into executable form
◦ Using programming languages to realize the
algorithm’s processing–steps
◦ This transformation is called algorithm
implementation 5
DESCRIPTION
Example: find the largest number in array
including n elements: a0, a1, a2, …, an.
Using natural language to describe our
solution (algorithm)
◦ Advantage: Easy to express
◦ Drawback: Polysemy in natural language
easily causes misunderstanding
◦ Suitable for simple short algorithm
◦ Need to use more symbol and various methods
to efficiently enhance algorithm description
6
DESCRIPTION
Using natural language to describe our
solution (algorithm)
◦ Step 1: Let lc the first number in array
◦ Step 2: If there is no number in array, then go
to step 4
◦ Step 3: If the next number is greater than lc,
then we assign this number to lc. Return to
Step 2
◦ Step 4: lc is the largest number in array
7
DESCRIPTION
Example: consider array 4 2 8 9
◦ Step 1: lc 4
◦ Step 2: Still, there are 3 numbers
◦ Step 3: See if 2 > lc, so don’t assign 2 to lc. Return to
step 2
◦ Step 2: Still, there are 2 numbers
◦ Step 3: See if 8 > lc, so assign lc 8. Return to step
2
◦ Step 2: Still there is one number
◦ Step 3: See if 9 > lc, so assign lc 9. Return to step
2
◦ Step 2: There is no number in array, then go to step 4
8
DESCRIPTION
Example: find the largest number in array
including n elements: a0, a1, a2, …, an.
Using programming language to describe
algorithm
◦ Advantage: run immediately
◦ Drawback: need to understand programming
language in use
◦ Maybe make a ‘workaround’ to express some
simple idea in algorithm
◦ Maybe cause algorithm description lose its
simplicity and fail to express the nature 9
DESCRIPTION
Using programming language to describe
algorithm
int FindTheLargestNumber(int a[], int n){
int i, max;
max = a[0];
for(i = 0; i < n; i++){
if(max < a[i])
max = a[i];
}
return max;
} 10
DESCRIPTION
Using flow–chart to describe algorithm
◦ Advantage: easy to understand
◦ Drawback: only suitable for simple short
algorithms
a0, …, an-1
max = a0
i=1
S i<n
Đ
max<ai S i=i+1
Đ
max = ai
max 11
DESCRIPTION
Using pseudo–code to describe algorithm
◦ Using syntax of some popular programming
languages
◦ Maybe using more mathematical symbols
max a0
i1
while(i < n) do
if(max < ai) then
max ai;
end if
end while
write max; 12
ANALYSIS
Check if algorithms do what they need to
do (expected things we want)
Check if our algorithm is better or worse
than others
Algorithm has two properties
◦ Correctness
◦ Complexity
Time complexity
Space complexity
13
ANALYSIS
Correctness
◦ Algorithm must give valid results corresponding to valid input
values
◦ Proving our algorithm to be correct with ALL input values is not
simple
◦ Maybe using induction in some cases
Time complexity
◦ With the same working condition, the first algorithm giving valid
results is better than the others
◦ With multi-purpose computers, it is difficult to force CPU to run
at full capacity to compare among algorithms
Xét dãy số fibonacci
F0 = 0, F1 = 1
Fn = Fn-1 + Fn-2 nếu n 2
14
ANALYSIS
Algorithm computing Fn of fibonacci
F0 = 0, F1 = 1
Fn = Fn-1 + Fn-2 nếu n 2
Algorithm 1:
Input: n
If n 1 then result = n
Else
a = 0, b = 1
for each k = 2 n do
c=a+b
a=b
b=c
end for
result = c
End if
15
Write result
ANALYSIS
Algorithm computing Fn of fibonacci
F0 = 0, F1 = 1
Fn = Fn-1 + Fn-2 nếu n 2
Algorithm 2:
Input: n
If n 1 then result = n
Else
A = Tính Fibo(n – 1)
B = Tính Fibo(n – 2)
result = A + B
End if
Write result
16
ANALYSIS
Time comparison between two algorithms
Comparison
N Algorithm 1 Algorithm 2
40 41 ns 1048 s
60 61 ns 1s
80 81 ns 18 m
100 101 ns 13 d
120 121 ns 36 y
160 161 ns 3.8 107 y
200 201 ns 4 1013 y
17
ANALYSIS
Space complexity
◦ Consider the consumption of system resources
(RAM, CPU…)
◦ Consider data structures to process and
represent data
Example: two swap algorithms
temp a; a a + b;
ab b a – b;
b temp a a – b;
floor n
1 i 1 2
2
2i 1 n 2i
i 1 log 2 n i
i log 2 n 1 23
SOME BASIC TECHNIQUE
Sentinel technique
◦ lc a0
◦ while(i < n) do
if(<điều kiện lc & ai>) then lc ai
i++;
◦ end while
◦ write lc
Flag technique
◦ kt true
◦ while(i < n) do
if(<ai>) then kt false
i++;
◦ end while 24
BRANCHING STRATEGY
Decision table
Date problem
Payments on electricity/water
Recursion for branching programming
Replacing branching strategy
Exercise
25
DECISION TABLE
Clearly describe all paths of process
Prepare a decision table before writing code
Present decision table in text
Careful analyze possible logic cases
Decision table sense:
◦ Logically analyze all branching – cases
◦ Help to easily implement
◦ Minimize any mistakes or logic errors
◦ Play a role of building source code’s test cases
26
DECISION TABLE
Example:
consider pow(x, y), st x, y > 0
Comment:
◦ If even order: we know 8 doesn’t exist
◦ If odd order: we know 3 8 = -2
Easily produce a decision table
x 0: compute n x by calling pow(x, 1.0/n)
n odd
x < 0: n
x = - n x , by calling –pow(-x, 1.0/n)
x 0: compute n x by calling pow(x, 1.0/n)
n even
x < 0: n x does not exist
27
DECISION TABLE
Improved decision table
x0 Compute n
x by calling pow(x, 1.0/n)
n odd n
x=- n
x by calling –pow(-x, 1.0/n)
x<0
n even n
x doesn’t exist
Code
void main(){
double n, x, kq;
printf(“Nhap n: ”); scanf(“%lf”, &n);
printf(“Nhap x: ”); scanf(“%lf”, &x);
if(x >= 0) kq = pow(x, 1.0/n);
else {
if(n % 2 == 1) kq = -pow(-x, 1.0/n);
else printf(“Không ton tai\n”);
}}
28
DATE PROBLEM
Leap year problem:
◦ Common year: 365 days
◦ Leap year: 366 days
◦ Rule of leap year
If Year % 4 0 then not leap year
If Year % 4 = 0 & % 100 0 then leap year
If Year % 100 = 0 & % 400 0 then not leap year
If Year % 400 = 0 then leap year
29
DATE PROBLEM
Leap year problem:
Not leap year
year % 100 = 0
Not leap year
year % 400 0
30
DATE PROBLEM
Leap year problem:
Lines Description
1 int checkLeapYear(int y){
2 if(y < 1900 || y > 10000) return -1
3 else{
4 if(y % 4 != 0) return 0;
5 else{
6 if(y % 100 != 0) return 1;
7 else{
8 if(y % 400 == 0) return 1;
9 else return 0;
10 }
11 }
12 } 31
DATE PROBLEM
Leap year problem: Can be reduce ‘else’
portion
Lines Description
1 int checkLeapYear(int y){
2 if(y < 1900 || y > 10000) return -1
3 else if(y % 4 != 0) return 0;
4 else if(y % 100 != 0) return 1;
5 else if(y % 400 == 0) return 1;
6 else return 0;
7 }
32
DATE PROBLEM
Leap problem:
◦ A year is:
Leap: year % 400 = 0 or (% 4 = 0 and % 100 0)
Not leap: in remaining cases
◦ Code
Lines Description
1 int checkLeapYear(int y){
2 if(y < 1900 || y > 10000) return -1
3 else if((y % 4 == 0 && y%100!=0) || (y%400==0)) return 1;
4 else return 0;
5 }
33
DATE PROBLEM
The days of month
◦ Months: 1, 3, 5, 7, 8, 10, 12 have 31 days
◦ Months: 4, 6, 9, 11 have 30 days
◦ February in common year: 28 days
◦ February in leap year: 29 days
Decision table
Year [1900, 10000] Month [1, 12] Not process
Month {1, 3, 5, 7, 8, 10, 12} 31 days
Month {4, 6, 9, 11} 30 days
Leap year 29 days
Month = 2
Common year 28 days
34
DATE PROBLEM
The days of month
Lines Description
1 int nDayOfMonth(int m, int y){
2 int isLeap = checkLeapYear(y);
3 if(isLeap == -1 || m < 1 || m > 12) return -1;
4 else{
5 switch(m){
6 case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
7 case 4: case 6: case 9: case 11: return 30;
8 default:
9 if(isLeap == 1) return 29;
10 else return 28;
11 }
12 }} 35
DATE PROBLEM
Next day problem
◦ Given day, month, and year, let’s compute
next day
Examples:
◦ 28/02/2001 has next day: 01/03/2001
◦ 28/02/2008 has next day: 29/02/2008
◦ 31/12/2008 has next day: 01/01/2009
Year [1900, 10000] Month [1, 12] Day [1, dayInMonth] Not process
1 Day < dayInMonth Day + 1, Month, Year
Month 12 1, Month + 1, Year
Day = dayInMonth
Month = 12 1, 1, Year + 1
36
DATE PROBLEM
Next day problem
Lines Description
1 int nextDay(int d, int m, int y){
2 int nDayInMonth = nDayOfMonth(m, y);
3 if(nDayInMonth == -1 || d < 1 || d > nDayInMonth) return -1;
4 else{
5 if(d < nDayInMonth) d++;
6 else if(m < 12){
7 d = 1; m++
8 }
9 else{
10 d = m = 1; y++;
11 }}
12 return 1;} 37
PAYMENT ON ELECTRICITY
Pay on electricity by kWh a household uses
Sum = Desired value + 10%VAT
Tariff:
rated consumption Price (vnd / kWh)
Kwh in 0 – 100 1242
Kwh in 101 – 150 1304
Kwh in 151 – 200 1651
Kwh in 201 – 300 1788
Kwh in 301 – 400 1912
Kwh in 401 trở lên 1962
Example:
100 kwh consuming
50kwh 215 kwh
50kwh 15kwhneeds
Sum 215kwh
100 1242 50 1304 50 1651 15 298770 + 10%
1788 38
PAYMENT ON ELECTRICITY
Decision table
Cases Computation (non-tax)
Kwh 100 Kwh 1242
100 Kwh 100 1242 + (Kwh - 100) 1304
150
150 Kwh 100 1242 + 50 1304 + (Kwh - 150) 1651
200
200 Kwh 100 1242 + 50 1304 + 50 1651 + (Kwh - 200) 1788
300
300 Kwh 100 1242 + 50 1304 + 50 1651 + 100 1788 + (Kwh -
400 300) 1912
Kwh 400 100 1242 + 50 1304 + 50 1651 + 100 1788 + 100
1912 + (Kwh - 400) 1962
39
PAYMENT ON ELECTRICITY
Code
Lines Description
1 double TienDien(int k){
2 double s = 0;
3 if(k <= 100) s = k * 1242;
4 else if(k <= 150) s = 100*1242 + (k - 100)*1304;
5 else if(k <= 200) s= 100*1242 + 50*1304 + (k - 150)*1651;
6 else if(k <= 300) s= 100*1242 + 50*1304 + 50*1651 + (k - 200)*1788;
7 else if(k <= 400) s= 100*1242 + 50*1304 + 50*1651 + 100)*1788 + (k - 300)*1912;
8 else s= 100*1242 + 50*1304 + 50*1651 + 100)*1788 + 100*1912 + (k - 400)*1962;
9 s = s*1.1;
10 return s;
11 }
40
PAYMENT ON ELECTRICITY
Improved code
Kwh 100 Kwh 1242
100 Kwh 150 100 1242 + (Kwh - 100) 1304
150 Kwh 200 100 1242 + 50 1304 + (Kwh - 150) 1651
200 Kwh 300 100 1242 + 50 1304 + 50 1651 + (Kwh - 200) 1788
300 Kwh 400 100 1242 + 50 1304 + 50 1651 + 100 1788 + (Kwh - 300)
1912
Kwh 400 100 1242 + 50 1304 + 50 1651 + 100 1788 + 100 1912 +
(Kwh - 400) 1962
43
PAYMENT ON ELECTRICITY
Improved code (continue)
◦ Comment: computation only uses values in a
range [L, R]
Case 1: value is 0 if kwh < L
Case 2: value = (kwh - L) price if L kwh < R
Case 3: value = (L – R) price if kwh > R
Lines Description
1 #define _Extream -1
2 double Tinh(int L, int R, double P, int k){
3 double kq = 0;
4 if(k < L) return kq;
5 else{
6 if(k < R || R == _Extream) kq = (k - L)*P;
7 else kq = (R – L)*P;
8 }
9 return kq; }
44
PAYMENT ON ELECTRICITY
Improved code (continue)
Lines Description
1 double TienDien(int k){
2 double s = Tinh(0, L1, P1, k) +
Tinh(L1, L2, P2, k) +
Tinh(L2, L3, P3, k) +
Tinh(L3, L4, P4, k) +
Tinh(L4, L5, P5, k) +
Tinh(L5, _Extream, P6, k);
3 s = (1 + _VAT)*s;
4 return s;
5 }
45
PAYMENT ON WATER
Pay on water by cubic meters of water a
household uses
Sum = Desired value + 15%
Price
Consumption based n members Price (vnd / m3)
n 4 m3 4400 đ/m3
n 2 m3 8300 đ/m3
n next cubic meters of water 10500 đ/m3
Code
Lines Description
1 double TienNuoc(int m3, int n){
2 double s = 0;
3 if(m3 <= n*4) s = m3 * 4400;
4 else if(m3 <= n*(4 + 2)) s = n*4*4400 + (m3 – n*4)*8300;
5 else s= n*4*4400 + n*2*8300 + (m3 – n*(4 + 2))*10500;
6 return (1+0.15)*s;} 47
RECURSION FOR BRANCHING
PROGRAMMING
Recurive function is the one calling itself
to solve a smaller problem
Branching to an easy–to–solve case
Consider following table x n
1
n=0 n
x does not exist because cannot compute x 0
x = 0 n x does not exist
n<0 1
x0 √𝑥=
Set m = -n > 0 because 𝑛 n
x
x0 Compute n
x by calling pow(x, 1.0/n)
n>0 n odd Because n x = - n x
x<0
n even n
x does not exist
48
RECUSION FOR BRANCHING
PROGRAMMING
Code
Lines Description
1 #include <math.h>
2 void sqrt_N(double x, int n, bool& errorFlag){
3 double kq = 0;
4 errorFlag = false;
5 if(n == 0) errorFlag = true;
6 else if(n < 0){
7 if(x == 0) errorFlag = true;
8 else kq = 1/sqrt_N(x, -n, errorFlag);
9 }
10 else{
11 if(x >= 0) kq = pow(x, 1.0/n);
12 else{
13 if(n % 2 == 1) kq = -sqrt_N(-x, n, errorFlag)
14 else errorFlag = true;
15 }
16 }
17 } 49
REPLACING BRANCHING
STRATEGY
Replacing branching structure with
mathematical formular in some cases
Consider
3n 1n 2k 1
f (n) n
2 n 2k
51
REPLACING BRANCHING
STRATEGY
Computing the days of the month
◦ Formular for computing the days of the month 2
30+(m < 8)*(m%2)+(m>=8)*(1 – m%2)
◦ Formular for computing the days of the month (not
leap year)
28+
(m!=2)*(2+(m<8)*(m%2)+(m>=8)*(1– m%2))
◦ Formular for computing the days of the month
(leap year)
28+
(m!=2)*(2+(m<8)*(m%2)+(m>=8)*(1– m%2)) +
(m==2)*(y%4==0&&y%100!=0)||(y%400==0)) 52
REPLACING BRANCHING
STRATEGY
Syntax for condition expression in C
<Logical expression> ? A:B
Compute absolute value
(a > 0)?a : -a
Return max number
(a > b) ? a : b
Compute the days of the month 2
(m<8)?((m%2==1)?31:30):((m%2==1)?30:31)
53
REPLACING BRANCHING
STRATEGY
Building test–case table
◦ Xample: Program computing
Range of n Range of x n x Expected value
0 1.3
n=0 Any 0 0
0 -1.3 Does not exist
-1 0
x=0
-20.7 0
-1 1 1
n<0
-2 4 0.5
x0
-2 -1.7 Does not exist
-3 8.0 -0.5
2 0 0
x0 102 1 1
n>0 4 81 3
3 -125 -5 (n odd)
x<0
4 -0.115 Doesn’t exist (n even) 54