04 Algorithms
04 Algorithms
$ cd WW
$ mkdir playground ; cd playgroun
$ vim index.html
<!DOCTYPE html
<body onload="init()"
<h1>Welcome!</h1
</body>
https://stanford.edu/~YourSUNet/playground/
>
>
>
>
<!DOCTYPE html
<body onload="init()"
<h1>Welcome!</h1
</body>
>
>
>
</script
</head
<body onload="init()"
<h1>Welcome!</h1
</body>
}
>
>
>
>
>
>
>
>
Most web pages also include a backend, which can store data
and run programs on the server where the web page is
located. The frontend makes a request to the backend
(possibly with some data), and a program is run on the
backend and returns data to the frontend.
You can request "CGI access" from Stanford for your web
space, and you can then put runnable files (Python, PERL,
PHP, compiled C, Bash, etc.) in the cgi-bin directory,
which sits alongside your WWW directory.
A simple backend program
Let's write our backend in Python. We need to first create the
appropriate directory in our cgi-bin directory, and copy
over a word list. Then we can create the python program:
mkdir ~/cgi-bin/playgroun
cd ~/cgi-bin/playgroun
cp /usr/share/dict/words .
vim ~/cgi-bin/playground/search-words.cgi
DICT_FILE = "words
print("Content-type:application/javascript\n"
else
print(json.dumps({'prev': '', 'next': ''}))
:
'
"
function search_words(name)
fetch('../cgi-bin/playground/search-words.cgi?firstname=' + name
.then(response => response.json()
.then(data =>
console.log(data
prev_word = document.getElementById("prev_word")
next_word = document.getElementById("next_word")
prev_word.innerText = data.prev
next_word.innerText = data.next
})
</script
</head
<body onload="init()"
<h1>Welcome!</h1
</body>
}
>
>
>
>
>
>
>
>
>
Expressions in JavaScript
• As in most languages, computation in JavaScript is specified
in the form of an expression, which usually consists of terms
joined together by operators.
• Each term must be one of the following:
– A constant (such as 3.14159265 or "hello, world")
– A variable name (such as n1, n2, or total)
– A function call that returns a value (such as sqrt)
– An expression enclosed in parentheses
• You can test this in a browser directly by using the Developer mode:
• In Google Chrome:
• View->Developer->Javascript Console.
• In Apple Safari:
• Go to Safari->Preferences and then the advanced tab, and click "Show
Develop menu in the menu bar." Then, Develop->Show Javascript
Console.
Expressions in JavaScript
• As in most languages, computation in JavaScript is specified
in the form of an expression, which usually consists of terms
joined together by operators.
• Each term must be one of the following:
– A constant (such as 3.14159265 or "hello, world")
– A variable name (such as n1, n2, or total)
– A function call that returns a value (such as sqrt)
– An expression enclosed in parentheses
• You can test this in a browser directly by using the Developer mode:
• In Google Chrome:
• View->Developer->Javascript Console.
• In Apple Safari:
• Go to Safari->Preferences and then the advanced tab, and click "Show
Develop menu in the menu bar." Then, Develop->Show Javascript
Console.
Variables
• The simplest terms that appear in expressions are numeric
constants and variables. A variable is a placeholder for a value
that can be updated as the program runs.
• A variable in JavaScript is most easily envisioned as a box
capable of storing a value.
answer
42
if (condition) {
statements to be executed if the condition is true
}
You use the second form whenever you want to choose between
two alternative paths, one for cases in which a condition is true
and a second for cases in which that condition is false:
if (condition) {
statements to be executed if the condition is true
} else {
statements to be executed if the condition is false
}
The while Statement
The while statement is the simplest of JavaScript’s iterative
control statements and has the following form:
while ( condition ) {
statements to be repeated
}
init;
while ( test ) {
statements to be repeated
step;
}
This statement executes the loop body ten times, with the control
variable i taking on each successive value between 1 and 10.
This statement executes the loop body N times, with i counting from
0 to N - 1. This version is the standard Repeat-N-Times idiom.
This statement executes the loop body with the variable x taking on
successive powers of two from 1 up to 1024.
Writing Functions
• The general form of a function definition is
return expression;
function fact(n) {
let result = 1;
for (var i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
Functions and Algorithms
• Functions are critical to programming because they provide a
structure in which to express algorithms.
• Algorithms for solving a particular problem can vary widely in
their efficiency. It makes sense to think carefully when you
are choosing an algorithm because making a bad choice can be
extremely costly.
• The next few slides illustrate this principle by implementing
two algorithms for computing the greatest common divisor of
the integers x and y, which is defined to be the largest integer
that divides evenly into both.
The Brute-Force Approach
• One strategy for computing the greatest common divisor is to
count backwards from the smaller value until you find one that
divides evenly into both. The code looks like this:
function gcd(x, y) {
let guess = x;
while (x % guess !== 0 || y % guess !== 0) {
guess--;
}
return guess;
}
function gcd(x, y) {
while (x % y !== 0) {
let r = x % y;
x = y;
y = r;
}
return y;
}
How Euclid’s Algorithm Works
• If you use Euclid’s algorithm on 1000005 and 1000000, you
get the correct answer in just two steps, which is much better
than the million steps required by brute force.
• Euclid’s great insight was that the greatest common divisor of
x and y must also be the greatest common divisor of y and the
remainder of x divided by y. He was, moreover, able to prove
this proposition in Book VII of his Elements.
• It is easy to see how Euclid’s algorithm works if you think
about the problem geometrically, as Euclid did. The next slide
works through the steps in the calculation when x is 78 and y
is 33.
An Illustration of Euclid’s Algorithm
Step 1: Compute the remainder of 78 divided by 33:
x 78
y 33 33 12
function count() {
count.stop = false;
const iterations = 100;
const counter = document.getElementById("counter");
counter.innerHTML = "";
function stop() {
count.stop = true; // triggered by button press
}
function count() {
count.stop = false;
const iterations = 100;
const counter = document.getElementById("counter");
counter.innerHTML = "";
• http://logos.cs.uic.edu/340%20Notes/rsa.html
• https://www.youtube.com/watch?v=b57zGAkNKIc
Data Compression Algorithms
• If you’ve ever seen an image on the Internet, or ever listened
to an .mp3, or ever watched Netflix, you’ve benefited from
data compression.
• Compression can be either lossless or lossy — a lossless
compression algorithm (such as the .zip file format, or the .png
format, or Huffman encoding, which you may have practiced
in CS 106B), allows exact decompression. A lossy
compression algorithm (e.g., .jpg, or .mp3, or Netflix movies)
removes some data, but in a way that is (hopefully)
imperceptible to the viewer, or listener (for example).
• An .mp3 is lossy, in that frequencies that you cannot hear from
the original are removed to save space. There has been great
debate over whether audiophiles can perceive the difference
between a raw audio file with all the data and .mp3 files.
Pseudo-random Number Generation