The book's stock market visualizer made use of Processing's
map()
function, which is used to extrapolate a value that was
originally expressed within one range, to its corresponding
value in another range. (See for example its use on page 169.)
Its formal signature, as discussed in
Processing's
online reference, is
float map(float value, float start1, float stop1, float start2, float stop2)
As an example, the call
Your task, once you understand the desired behavior, is to provide a self-contained implementation of such a map function. The body of your function implementation should not include any calls to other functions, but instead should revert to the underlying arithmetic to determine the answer.
Hint: Consider the absolute gap between start1 and stop1, the gap between start2 and stop2, and the gap between value and start1.
A concise coding of this function could appear as:
float map(float value, float start1, float stop1, float start2, float stop2) {
return start2 + (stop2-start2) * (value-start1)/(stop1-start1);
}
A slightly more verbose expression of this calculation appears as:
float map(float value, float start1, float stop1, float start2, float stop2) {
float p = (value-start1)/(stop1-start1);
float interpolate = start2 * (1-p) + stop2 * p;
return interpolate;
}
To understand why this works, we must consider the variable,
p, which represents the portion of the way that
value1 is on the way from start1 toward
start2. This proportion is
We then continue by interpolating between start2 and
stop2 using proportion p, such that when
p is zero we get start2 and when p is
1 we get stop2. Thus we compute the value
When demonstrating recursion in lecture, we left a parting
challenge to implement what is known as Sierpinski's Triangle.
For this homework question, we wish to have you complete that
challenge. You do not need to provide the complete Processing
program in your solution; we are only interested in your
implementation of a recursive function
drawTriangle() having the following signature:
void drawTriangle(float x0, float y0, float x1, float y1, float x2, float y2)
For simplicity, you may assume that those points are oriented so
that (x0,y0) is the top vertex of the triangle, that (x1,y1) is
the bottomleft vertex, and (x2,y2) is the bottomright vertex.
We suggest the following implementation:
void drawTriangle(float x0, float y0, float x1, float y1, float x2, float y2) {
triangle(x0,y0,x1,y1,x2,y2);
if (dist(x0,y0,x1,y1) > 5) {
// point A will represent midpoint of line from 0 to 1
float xa = (x0+x1)/2, ya = (y0+y1)/2;
// point B will represent midpoint of line from 0 to 2
float xb = (x0+x2)/2, yb = (y0+y2)/2;
// point C will represent midpoint of line from 1 to 2
float xc = (x1+x2)/2, yc = (y1+y2)/2;
drawTriangle(x0, y0, xa, ya, xb, yb); // top subcase
drawTriangle(xa, ya, x1, y1, xc, yc); // bottom-left subcase
drawTriangle(xb, yb, xc, yc, x2, y2); // bottom-right subcase
}
}