Files
freeCodeCamp/curriculum/challenges/english/08-coding-interview-prep/rosetta-code/vector-cross-product.english.md
Randell Dawson c25916c9a2 fix(curriculum): changed test text to use should for Coding Interview Prep - part 2 of 2 (#37766)
* fix: changed test text to use should

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: removed extra period

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>

* fix: corrected typo

Co-Authored-By: Tom <20648924+moT01@users.noreply.github.com>
2019-11-20 10:01:31 -05:00

1.5 KiB

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

Description

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

Instructions

Write a function that takes two vectors (arrays) as input and computes their cross product. Your function should return null on invalid inputs such as vectors of different lengths.

Tests

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

Challenge Seed

function crossProduct(a, b) {
    // Good luck!
}

After Test

const tv1 = [1, 2, 3];
const tv2 = [4, 5, 6];
const res12 = crossProduct(tv1, tv2);
const exp12 = [-3, 6, -3];

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])
  ];
}