# Planting the Flag Warmup

This sequence of programs may help you prepare to do the Planting the Flag assignment for Week 7.

Our goal will be to plot “stock values” in green when prices are going up, and red when prices are going down.

Consider the following program:

``````var stocks = [];

function setup() {
createCanvas(400, 400);
// create some random values
for (var i = 0; i < width; i++) {
stocks.push(height/4 + noise(i * 0.05) * height/2);
}
noLoop();
}

function draw() {
background(100, 100, 100);
strokeWeight(2);
for (var i = 0; i < stocks.length - 1; i++) {
// draw line from i to i+1
line(i, stocks[i], i + 1, stocks[i + 1]);
}
}

``````

Key things to notice:

• `stocks` is an array the size of the `width` of the canvas.
• `stocks` is initialized to random values (based on Perlin `noise`).
• the values in `stocks` are used as Y values to draw the graph.
• the X values are the array indices; the middle of the array is plotted in the middle of the canvas.
• the graph is “upside down”: higher values in the array show up as lower values in the graph.
• The graph is made of short lines (from x1=i to x2=i+1).
• If we looped from 0 through 399 (400 or `width` iterations), the first line would go from x1=0 to x1=1, and the last line would go from x1=399 to x2=400, but there is no array element at index 400!
• To avoid accessing beyond the end of the array, we iterate `stocks.length-1` times, i.e. 399 times.

Let’s fix the “upside down” problem first. We just need to map the array values to more suitable Y values. To flip the direction of up and down, we’ll subtract the array values (stock prices) from `height`. (We could also scale the values here, or use `map` to translate from one range to another).

``````var stocks = [];

function setup() {
createCanvas(400, 400);
// create some random values
for (var i = 0; i < width; i++) {
stocks.push(height/4 + noise(i * 0.05) * height/2);
}
noLoop();
}

function draw() {
background(100, 100, 100);
strokeWeight(2);
for (var i = 0; i < stocks.length - 1; i++) {
// draw line from i to i+1
line(i, height - stocks[i], i + 1, height - stocks[i + 1]);
}
}

``````

Now, let’s add color based on the direction of the stock price. If stock prices are going up at say, location 100, then `stocks > stocks`, so in general, stocks are up if `stocks[i + 1] > stocks[i]`. We use that test to select either RED or GREEN color for the line before drawing each line segment.

``````var stocks = [];

function setup() {
createCanvas(400, 400);
// create some random values
for (var i = 0; i < width; i++) {
stocks.push(height/4 + noise(i * 0.05) * height/2);
}
noLoop();
}

function draw() {
background(100, 100, 100);
strokeWeight(2);
for (var i = 0; i < stocks.length - 1; i++) {
if (stocks[i + 1] > stocks[i]) {
stroke(0, 255, 0);
} else {
stroke(255, 0, 0);
}
// draw line from i to i+1
line(i, height - stocks[i], i + 1, height - stocks[i + 1]);
}
}

``````