Skip to content
Chan Jun Shern edited this page Sep 18, 2018 · 14 revisions

1. Introduction

javascript-gif (Image source: https://hackernoon.com/12-amazing-javascript-shorthand-techniques-fef16cdbc7fe)

Recap: Last Week

  • Variable types
  • Logical operations

2. Development Environment

New Shortcuts


3. Main Content

If necessary, download the files from the p5.js website

Also useful: The p5.js documentation

  • while loop
let i = 0;
while (i < 10) {
  console.log(i);
  i++; // Shorthand for i = i + 1
}
  • for loop
for (let i = 0; i < 10; i++) {
  console.log(i);
}

Exercise 3.1

Write a for-loop that counts from 0 to 99, printing each number to the console.

Expected output:

0
1
2
3
4
/// And so on...

Exercise 3.2

Write a for-loop that counts from 100 to 1, printing each number to the console and stating whether the number is an even number or an odd number.

Expected output:

100
even
99
odd
98
even
97
odd
/// And so on...

Exercise 3.3 (Challenge)

checkerboard

Write a program that uses nested for-loops to produce the above pattern. Nested for-loops are for-loops that sit inside one another, for example:

for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    console.log(i, j);
  }
}
let myArray = [15, "Jun Shern", true, -0.327];
  • Used to store lists of values
  • Index notation, start counting from 0 (eg. arr[0])
  • Array.length
  • Array.push(newElement)

Exercise 3.4

Count the number of times the number "3" appears in the following array:

let arr = [7, 3, 1, 9, 9, 9, 0, 2, 5, 7, 9, 0, 3, 8, 6, 7, 1, 2, 1, 7, 4, 1, 4, 2, 6, 3, 2, 1, 2, 9, 2, 7, 2, 2, 1, 0, 9, 5, 3, 3, 9, 1, 2, 2, 6, 6, 3, 8, 5, 3, 3, 2, 7, 9, 9, 2, 1, 7, 8, 9, 6, 10, 9, 7, 7, 6, 7, 10, 9, 1, 5, 3, 0, 6, 5, 8, 2, 7, 9, 5, 1, 1, 1, 9, 6, 3, 10, 9, 0, 2, 5, 6, 1, 4, 1, 2, 4, 3, 7, 3];

Expected answer:

12

Exercise 3.5

Using the same array as before, increment all numbers in the array by 1, and then count the number of odd numbers.

Expected answer:

40

Exercise 3.6

  • Create an array containing all multiples of 3 below 1000.

Expected answer:

[3, 6, 9, 12, 15, 18, 21, 24, 27, ..., 996, 999]

Exercise 3.7

  • Create an array called arr, containing 50 random numbers between (0, height).
  • Plot each value in that array as a bar on the screen.

You can use the following template:

const NUM_VALS = 50;
let arr = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
  // Populate arrays using arr.push(NEW_VALUE)
  // TO-DO
}

function draw() {
  background(255);
  fill(0);
  let barWidth = width / NUM_VALS;
  // For each value in the array, draw a rect
  // TO-DO
}

Example output: barplot

Exercise 3.8 (Challenge)

  • Create an array called xposArray, containing NUM_BALLS numbers between (0, width).
  • Create an array called yposArray, containing NUM_BALLS numbers between (0, height).
  • For every pair of coordinates, draw an ellipse
  • For every pair of coordinates, add a random number between (-5, 5) to the coordinates

You can use the following template:

const NUM_BALLS = 100;
let xposArray = [];
let yposArray = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
  // Populate arrays
  // DO SOMETHING HERE
}

function draw() {
  background(30, 10);
  fill(255);
  // For every pair of coordinates, draw an ellipse
  // DO SOMETHING HERE

  // For every pair of coordinates, add a random number between (-5, 5) to the coordinates
  // DO SOMETHING HERE
}

Expected output: Here

  • Functions are modular, reusable pieces of code which we can use to do things.
  • Vanilla (pure) JavaScript comes with some functions, we can get more functions written by other people by downloading libraries, and we can also write our own functions. Can you think of a few functions we have already used?
  • Input (can have multiple): Parameters / Arguments
  • Output (can only have one): The return keyword
  • Good use of functions and good names of functions make code readable without needing comments!

Example with no inputs and no outputs:

// We make functions that do useful things for us
function fillRandom() {
  fill(random(255), random(255), random(255));
}

Example with two inputs and one output:

function isWithinRange(number, min, max) {
  if (number >= min && number <= max) {
    return true;
  } else {
    return false;
  }
}

Exercise 3.9

Create a function calcMean that takes as input an array of numbers, and returns the mean-average value of those numbers.

function calcMean(/* TO-DO */) {
  // TO-DO
}

Example usage:

let numbers = [10, 13, 14, 22, 51, 100, 73, -123, 0];
let mean = calcMean(numbers);
console.log(mean);
// Expected output: 17.77777777777778

Exercise 3.10

distance (Image source: http://mymatheureka.blogspot.com/2011/04/distance-formularevealed.html)

Write a function that calculates the distance between two 2D points. Start with the following template:

function calcDistance(x1, y1, x2, y2) {
  return 0 // This is wrong, change this!
}

Example usage:

calcDistance(0, 3, 4, 0)
// Expected answer: 5

4. Project: Network

This week's project is to create an array of bouncing balls, with a link created between each pair of balls which are closer to each other than a certain distance threshold. The final program might look something like this.

Begin with the following template:

const NUM_DOTS = 100;
const LINK_THRESHOLD = 200;
let xposArray = [];
let yposArray = [];
let xdirArray = [];
let ydirArray = [];

function setup() {
  createCanvas(windowWidth, windowHeight);
  // Populate all arrays
  for (let i = 0; i < NUM_DOTS; i++) {
    // TO-DO: Add random x-location (0, width) to xposArray
    // TO-DO: Add a random y-location (0, height) to yposArray
    // TO-DO: Add a random x-direction (-1, 1) to xdirArray
    // TO-DO: Add a random y-direction (-1, 1) to ydirArray
  }
}

function draw() {
  background(30);
  // For each ball
  for (let i = 0; i < xposArray.length; i++) {
    // TO-DO: Check distance against all other balls

    // TO-DO: Update position of this ball

    // TO-DO: If the ball has hit the borders, bounce
  }
}

function calcDistance(x1, y1, x2, y2) {
  let dist = sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
  return dist;
}

Make sure you get the main features of the program working, then go crazy and have fun with it! Some ideas for extensions:

  • Set the color of each link according to the distance between the linked pair
  • Give each ball a different starting velocity
  • Try changing the number of balls, or the link threshold!
  • Turn it into a game (?!)

5. Feedback

Please fill up the feedback form so that I can improve future sessions!