Files
freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/rosetta-code/vector-cross-product.english.md

1.6 KiB

title, id, challengeType
title id challengeType
Vector cross product 594810f028c0303b75339ad2 5

Description

A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z).

Task:

Write a function that takes two vectors (arrays) as input and computes their cross product.

Your function should return null on invalid inputs (ie vectors of different lengths).

Instructions

Tests

tests:
  - text: dotProduct must be a function
    testString: 'assert.equal(typeof crossProduct, "function", "dotProduct must be a function");'
  - text: dotProduct() must return null
    testString: 'assert.equal(crossProduct(), null, "dotProduct() must return null");'
  - text: 'crossProduct([1, 2, 3], [4, 5, 6]) must return [-3, 6, -3].'
    testString: 'assert.deepEqual(res12, exp12, "crossProduct([1, 2, 3], [4, 5, 6]) must return [-3, 6, -3].");'

Challenge Seed

function crossProduct() {
    // Good luck!
}

After Test

console.info('after the test');

Solution

function crossProduct(a, b) {
  if (!a || !b) {
    return null;
  }

  // Check lengths
  if (a.length !== 3 || b.length !== 3) {
    return null;
  }

  return [
    (a[1] * b[2]) - (a[2] * b[1]),
    (a[2] * b[0]) - (a[0] * b[2]),
    (a[0] * b[1]) - (a[1] * b[0])
  ];
}