[CREDITS HERE]
Intro to
Algorithms:
Day 1
Recursion & Pseudoclasses
Stacks & Queues
[preface stuff]
- Agenda?
- Class format?
- FAQs?
Recursion
Call Yourself
function callMyself() {
callMyself();
}
What if you do a Google search for recursion?
General Algorithm
function callMyself() {
if() {
// base case
return;
} else {
// recursive case
callMyself();
}
return;
}
- Identify base case
- Identify recursive cases
- Write procedures for each case
Advice: Use a bottom-up approach by looking for patterns by starting with small or first few cases
Example: Factorial
function computeFactorial(num) {
var result = 1;
for(var i = 2; i <= num; i++) {
result *= i;
}
return result;
}
results *= 2;
results *= 3;
results *= 4;
results *= 5;
If we call computeFactorial(5), then the loop will run:
Example: Factorial
function computeFactorial(num) {
if(num === 1) {
return 1;
} else {
return num * computeFactorial(num - 1);
}
}
5 * computeFactorial(4)
4 * computeFactorial(3)
3 * computeFactorial(2)
2 * computeFactorial(1)
1
If we call computeFactorial(5), then the recursion will run:
function logNumbers(start, end) {
for(var i = start; i <= end; i++) {
console.log(i);
}
}
function logNumbersRecursively(start, end) {
function recurse(i) {
console.log(i);
if(i < end) {
recurse(i + 1);
}
}
recurse(start);
}
Converting a loop into recursion
Exercises!
(but first, a quick overview)
Pseudoclasses
function MyClass(input) {
this.myProp = input;
}
MyClass.prototype.myMethod = function() {
console.log('Check it out: ' + this.myProp);
};
Syntax
Constructor
Properties
(per instance)
Defining a (pseudo)Class
Methods (for all instances)
function MyClass(input) {
}
Syntax
Using a (pseudo)Class
var myInstance = new MyClass('hello');
var myOtherInstance = new MyClass('bye');
myInstance.myMethod();
myOtherInstance.myMethod();
The results of the shared method depend on the unique instance properties
Data Structures:
Stacks
Stacks
Description
Stacks
The last item added into the stack will be the first one taken out of the stack.
(aka LIFO)
Description
(aka pushed onto)
(aka popped off)
Stacks
Example Use Cases
-
Backtracking / History
i.e., Hitting the back + forward
buttons of your web browser
- Call stack
Data Structures:
Queues
Queues
Description
[ TODO: Find diagram that is legal for commercial use ]
Queues
The first item added into the queue will be the first one taken out of the queue.
(aka FIFO)
Description
(aka enqueued)
(aka dequeued)
Queues
Example Use Cases
-
JavaScript's Event Queue
-
Message Queueing
e.g., RabbitMQ
deck2
By rebootjeff
deck2
- 791