Chapter 6 - Algorithms Part II
Chapter 6 - Algorithms Part II
PROGRAMMING TECHNIQUES
CHAPTER 6
Algorithms – Part II
Võ Duy Thành
Department of Automation Engineering
Control Technique and Innovation Lab. for Electric Vehicles
School of Electrical and Electronic Engineering
Hanoi University of Science and Technology
[email protected] | [email protected]
Outline
2
1. Brute Force Algorithm
Example:
• Smithsonian
Museums in
Washington DC
• In 2018, we
stayed here for
1 month
• We want to visit
as many as
possible events
• We can arrange
some days in a
week
• Brute Force Algorithm will check all combinations and see what is the
best.
Week 1 Week 1
Mon Thu
2x5 = 10 combinations
Week 2 Week 2 Week 2 Week 2 Week 2
Mon Tue Fri Sat Sun
2 3
6 10 1 20
2 3 Total = 32
Optimal Solution
6 10 1
Chargeeerrrrr….
2PM Charge
14:30 – 15:00: TA meeting
3PM Use in 2 hours
15:30 – 16:30: Lab. Seminar
4PM Charge
5PM 17:00 – 18:00: Students meeting
6PM Use in 2.5 hours
7PM 18:30 – 20:00: Gala Dinner
Eugen Lavresky, “Greedy Optimal Control,” in proc. American Control Conference, 2000.
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 13
2. Greedy Algorithm
Fibo(120) = 8.670.007.398.507.948.658.051.921
If each recursive call takes 1ns → it will take about 250.000 years to finish
Fibo(5) Fibo(4)
Fibo(1) Fibo(0)
• To reduce calculation:
• Record the result by the first call Memorization is the key idea
• Check if the result is stored when being called behind dynamic programming
def fastFibo(n, memo = {}):
if n == 0 or n == 1:
return 1
try:
return memo[n]
except KeyError:
result = fastFibo(n-1, memo) + fastFibo(n-2, memo)
memo[n] = result
return result
25