0% found this document useful (0 votes)
4 views

Algorithms Intro

This document serves as an introduction to algorithms, emphasizing their importance in programming and problem-solving. It discusses various types of algorithms, including sorting and control algorithms, and provides examples from everyday life and nature. The document also highlights the significance of understanding algorithms for job interviews in the tech industry.

Uploaded by

nsaimkorkmaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Algorithms Intro

This document serves as an introduction to algorithms, emphasizing their importance in programming and problem-solving. It discusses various types of algorithms, including sorting and control algorithms, and provides examples from everyday life and nature. The document also highlights the significance of understanding algorithms for job interviews in the tech industry.

Uploaded by

nsaimkorkmaz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Algorithms

General Introduction

This presentation and other materials can be found at:


https://github.com/wai-t/CompSci/tree/main/ComputerScience/Algorithms_Intro
A Bootcamper’s dream…
• Interviewer:
• How do you sort this array of numbers?
• Let myArray = [34, 939, 30, -3, 32, -920, 344, 344, 12…];
• Bootcamper:
• Easy!
• Call myArray.sort()

• Time for MY questions now:


• What’s my starting salary?
• How many days holiday?
• Parking space?
…dream turns into nightmare…
• Interviewer:
•Not so fast!
•What if my array contains a million zillion elements?
•…and I only want the first 50?
•What if the possible element values are a fixed set? Like days
of the week?
•…
• Bootcamper:
• Pahh! What if you shoved your job up your (*”&(“!

*This is the second reason the


interviewee didn’t get the job
…a more constructive answer might
be…
• Bootcamper:
• I’d investigate how Array.sort() works internally and
analyse whether it is suitable for my purposes
• I’d implement code that is optimal for my requirement

Either way: You have to


understand something
about sorting
algorithms, and
…and it’s not just sorting algorithms
Sort
Encrypt
Compres
Simple Coding
s
Patterns are
algorithms
Solve
Simulat
e
Optimise
Searc
h
Control
What is an algorithm anyway?
• The word comes from a 9th Century Persian
mathematician called “Abdullah Muhammad bin Musa
al-Khwarithmi”
• The idea is a LOT OLDER than computers and programming
• Algorithms can be learned INDEPENDENTLY of programming
• In fact, algorithms are what DRIVES programming

• An algorithm is basically a set of instructions


designed to achieve a desired result
• In any language you like.
Use any language you like
Pseudocode
Natural/human language
for (I = 1 to LENGTH-1)
While job hunting and waiting {
for (J = 0 to LENGTH-
for opportunities, spend your
2)
time building knowledge that {
can improve your CV and your if (A[I] > A[J])
{
interview performance.
doSwap(I,J);
}
}
}
No
Alarm
Flowcha Press
Sleep ringing
rt Ye snooze
?
s
But use language precisely
For these
• Algorithms are typically written in workshops, this is
an imperative style:
• “Doing” words – verbs
not an algorithm
• Objects involved should be This is declarative
reasonably precisely understood, select CITY, count(*) from
e.g CUSTOMERS
• Positive integers where STATUS = “NEW”
• Array group by CITY
having count(*) > 50
• Month order by CITY
• Observables and State
But under the hood, the computer
• Things that happen will be running an algorithm. One
• Things that are of them will be a sorting
algorithm.
Examples
A cooking recipe is an algorithm
• Ingredients (i.e. pre-condition of the algorithm)

, i s
g th
• Instructions:
• Heat the pan

r i n es
o s
• Fry x until.. (a do/while loop)

B u
• If it’s too thick, add water (an if/then statement)

! e
a h
• Just like a computer program, there are:
n
N ry o
• types/objects (100g of minced beef)
• statements (including composite and conditional loops,

v e l e
if..then, switch..case)

p
e
• observables/inputs (too thick, browned, boiling…)

m
a
Airline seat pricing
Calculate price of economy seat
ticket

No Sold Yes Calculate probability P of


out? empty seat in business class

Yes No
P>0?

Quote economy Quote Sold out


price MAX(economy, (1-P)*business)
Traffic light control

Research into how to use


GPS data from vehicles to
optimize the timing of a set
of traffic signals in a road
network.

The aim could be to improve


CO2 emissions, improve
journey speed, reduce
accidents.

This is an example of a
control algorithm.
https://www.researchgate.net/publication/328698232_Cooperative-
Competitive_Paradigm_in_Traffic_Signal_Synchronization_Based_on_
Floating_Car_Data
More examples:
• Ed Thorp – Blackjack algorithm(1961)
• Was later banned from some Las Vegas
Casinos
• Took to wearing disguises to gain entry
• Caused casinos to increase the size of the
card deck and ban portable computers
• He went on to found a hedge fund that
made 20% every year for 20 years in a
row
• One of the pioneers of algorithmic trading
• (Maths can make you rich)
on
Bluetooth LE off

Device pairs synchronise their A transmits


listen/transmit periods, and save time
energy by using their radios only a B listens
fraction of the time (as low as
0.1%)
An algorithm to Device pairs synchronise On connect, a hop size
hops to avoid interference N is agreed. They use
save power with other devices in the 37 channels (a prime
area, incl Wi-Fi number). Why a prime
number?

and
an algorithm to allow co-existence
Algorithms are in nature
Nature
provides
inspiration for
development
of new
algorithms
Algorithms are in everyday life
• Think about the self-checkout machine at
the supermarket
• Let’s see if we can reverse-engineer its
algorithm
• What does the algorithm need to observe
(events)?
• barcode
• weight
• What programming features are used in the
algorithm?
• Are there do/while loops and if/then conditional
statements?
• Are there calculations?
• Is external data fetched from a backend?
• What causes the machine to say “Unexpected
Item in the Bagging Area”?
IDLE Happy path
Self-checkout Wait for Scan item
machine exercise event Put in bagging area
Scan item
Even Put in bagging area
t Scan item
type Put in bagging area
…etc
Finish and pay

Unhappy
paths
Item removed
before payment

Item added before


scan
Universe of algorithms in
programming
What you All known
already know
(but didn’t algorithms
know you
know) What I know

What they
might ask
you about at
interview
First look at Sorting
• The problem:
• [3,4,1,5,2].sort() should equal [1,2,3,4,5]
• As well as just sorting, many programming solutions
depend on the result of a sort function:
• find
• check for missing item (or duplicates)
• compare (sets)
• We’ll briefly look today at animations of a simple
algorithm and a more complex one:
• Insertion sort
• Merge sort
Insertion
Sort for (I = 1 to LENGTH-1) {
for (J = 0 to J-1) {
if (A[I] < A[J]) {
doRotate(J,I);
break;
}
}
}

Start by looking at the second element (using index


variable I)
Look at every element to the left of I (using index variable
J)
If they are out of order, move the element at I to J, and
move everything from J one place to the left to fill the gap
(this is called a rotate).
Repeat with next I.
Merge Sort 2
21 79 19 7 77 99 36 43 13 69

21 79 7 19 77 99 36 43 13 69

2 4

7 19 21 79 36 43 77 99 13 69

Recipe:
3
divide array into pairs
sort each pair (using swap) -> sorted sub-array 7 19 21 36 43 77 79 99 13 69
while (number of sorted sub-arrays > 1)
for each pair of sub-arrays:
“sortmerge” the pair -> sorted sub-array 5
(sortmerge is happening in steps 2,3,4,5 on 7 13 19 21 36 43 69 77 79 99
the right)
Pseudocode: recursive function call
function mergeSort (start, end) { // start, end of sub-array

if (start == end) return; // can’t go on forever

divider = somewhere_in_between_start_end(start, end)


// for (0,10) I chose 8 because it’s a power of 2, for (4,8) I chose 6
// but you can also just go halfway, it’ll still work

mergeSort (start, divider);


mergeSort (divider, end);

sortmerge(start->divider, divider->end);
// this is what is happening in the yellow boxes

}
Call structure: recursive function call
merge (0,
1 10)
1
4 1 1 6
5 merge (8,
merge (0, 8)
10)
7 1
2 8 3

merge (0, 4) merge (4, 8)

4 5 1
3 6 1
1 9 2
0 1
merge (0, merge (2,
merge (4, 6) merge (6, 8)
2) 4)
Experiment
Appreciating the art of sorting algorithms
A look ahead to the next workshop
What does the input data look like?What output is required?
• nearly sorted already • just the first few
• finite vocabulary (true/false, • just the comparison key
days of week, currency code) • is it sorted again using
• it’s actually changing all the another key (need stable
time! sort)

Do they cope with enormous


inputs?
Memory usage

Is the compare function Can they be multi-threaded?


Is copy/Move and expensive
expensive to call?
operation?
Complexity O(n), O(n log(n))
Takeaways
• You don’t need to know programming to learn algorithms
• Many jobs in IT involve spending the vast majority of the time
developing algorithms, not programs
• Programming is just a tool, the solution to the business
problem is in the algorithm
• You can get your next programming job without knowing the
programming language
• The I in IT stands for Information, NOT Programming:
i.e.
• Given some information, what do I do next ?
• You won’t find the answer at https://javascript.info/ !
Homework Challenge
Beat the Rock-Paper-Scissors Bot

The developers of an algorithm to play rock-paper-scissors


think they have one that in the long run can’t be beaten
consistently.

Your challenge is to implement an algorithm to beat it


consistently. SCISSORS beats PAPER
The code is at PAPER beats ROCK
https://github.com/wai-t/CompSci/blob/main/ComputerScience/Algorithms_Intro/rock_paper_scissors.js
ROCK beats SCISSORS
You can run the program with “node rock_paper_scissors.js” in a
terminal. Each run will play 1000 (NUM_GAMES) games. We get +1
for a win, -1 for a loss and 0 for a draw. If everything was equal we’d
expect a final score of between -30 and +30.

In the function my_play(), you have to change the code so that it will
consistently score above +30.
https://github.com/wai-t/CompSci/blob/main/ComputerScience/Algorithms_Intro/rock_paper_sciss
ors.js
let robo_plays = []; // list of bot’s game history

function robo_play (game_num)


{ // robo’s secret sauce
if ( Math.random() < 0.25 && game_num > 0) {
robo_plays[game_num] = robo_plays[game_num-1];
}
else {
let rand = Math.floor( Math.random() * 3 ) ;
robo_plays[game_num] = plays[rand];
}
return robo_plays[game_num];
}

function my_play(game_num)
{
// TODO
// At the moment your strategy is to play SCISSORS every time.
// Your challenge is to replace the statement below with a strategy that will

// beat robo consistently


//
return SCISSORS;
}

Main function will loop round NUM_GAMES times, calling robo_play() and my_play()
and decide who wins each game.
End of General
Introduction
Self-checkout
machine exercise IDLE
Wait for
event
Y
Fetch Eve
Update item’s scan weigh Weight

Price and
nt matche
bill type
s
Weight N

Update
Y expected
weight
Weight N Unexpecte
matche IDLE d item in
s Wait for bagging
item area
Place removal
item in
bagging
IDLE area
Wait for
item

You might also like