Lesson 2 of 15

Adding and Subtracting Tuples

Adding and Subtracting Tuples

Tuples support component-wise arithmetic. Adding a vector to a point gives a new point. Subtracting two points gives a vector.

Addition

point + vector = point  (w: 1 + 0 = 1)
vector + vector = vector  (w: 0 + 0 = 0)
// Adding tuple(3,-2,5,1) + tuple(-2,3,1,0):
// → tuple(1, 1, 6, 1)  (a point)

Subtraction

point - point = vector  (w: 1 - 1 = 0, a direction between two points)
point - vector = point  (w: 1 - 0 = 1)
// Subtracting point(3,2,1) - point(5,6,7):
// → vector(-2, -4, -6, 0)

Implementation

Tuple add(Tuple a, Tuple b) {
    return Tuple(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}

Tuple subtract(Tuple a, Tuple b) {
    return Tuple(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}

Your Task

Implement add(Tuple a, Tuple b) and subtract(Tuple a, Tuple b) free functions that return new Tuples.

Expected output:

1 1 6 1
-2 -4 -6 0
JSCPP loading...
Loading...
Click "Run" to execute your code.