2018-09-30 23:01:58 +01:00
---
id: 594810f028c0303b75339ad2
2020-11-27 19:02:05 +01:00
title: Vector cross product
2018-09-30 23:01:58 +01:00
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302342
2021-01-13 03:31:00 +01:00
dashedName: vector-cross-product
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2019-07-18 17:32:12 +02:00
2019-03-11 16:12:24 +09:00
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --instructions--
2019-07-18 17:32:12 +02:00
2020-11-27 19:02:05 +01:00
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.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
dotProduct should be a function.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert.equal(typeof crossProduct, 'function');
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
dotProduct() should return null.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert.equal(crossProduct(), null);
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
crossProduct([1, 2, 3], [4, 5, 6]) should return [-3, 6, -3].
2018-09-30 23:01:58 +01:00
```js
2020-11-27 19:02:05 +01:00
assert.deepEqual(res12, exp12);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --after-user-code--
2018-09-30 23:01:58 +01:00
```js
2018-10-20 21:02:47 +03:00
const tv1 = [1, 2, 3];
const tv2 = [4, 5, 6];
const res12 = crossProduct(tv1, tv2);
const exp12 = [-3, 6, -3];
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
function crossProduct(a, b) {
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
}
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
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])
];
}
```