-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproductOfAllOtherNumbers.js
82 lines (67 loc) · 2.28 KB
/
productOfAllOtherNumbers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function getProductsOfAllIntsExceptAtIndex(intArray) {
// Make a list of the products
if (intArray.length < 2) {
throw new Error('Minimum two numbers needed for a product');
}
let productOfAllOthers = [];
let currentProduct = 1;
for (let i = 0; i < intArray.length; i++) {
productOfAllOthers[i] = currentProduct;
currentProduct *= intArray[i];
}
currentProduct = 1;
for (let j = intArray.length - 1; j >= 0; j--) {
productOfAllOthers[j] *= currentProduct;
currentProduct *= intArray[j];
}
return productOfAllOthers;
}
//O(n) time and O(n) space
// Tests
let desc = 'short array';
let actual = getProductsOfAllIntsExceptAtIndex([1, 2, 3]);
let expected = [6, 3, 2];
assertArrayEquals(actual, expected, desc);
desc = 'longer array';
actual = getProductsOfAllIntsExceptAtIndex([8, 2, 4, 3, 1, 5]);
expected = [120, 480, 240, 320, 960, 192];
assertArrayEquals(actual, expected, desc);
desc = 'array has one zero';
actual = getProductsOfAllIntsExceptAtIndex([6, 2, 0, 3]);
expected = [0, 0, 36, 0];
assertArrayEquals(actual, expected, desc);
desc = 'array has two zeros';
actual = getProductsOfAllIntsExceptAtIndex([4, 0, 9, 1, 0]);
expected = [0, 0, 0, 0, 0];
assertArrayEquals(actual, expected, desc);
desc = 'one negative number';
actual = getProductsOfAllIntsExceptAtIndex([-3, 8, 4]);
expected = [32, -12, -24];
assertArrayEquals(actual, expected, desc);
desc = 'all negative numbers';
actual = getProductsOfAllIntsExceptAtIndex([-7, -1, -4, -2]);
expected = [-8, -56, -14, -28];
assertArrayEquals(actual, expected, desc);
desc = 'error with empty array';
const emptyArray = () => (getProductsOfAllIntsExceptAtIndex([]));
assertThrowsError(emptyArray, desc);
desc = 'error with one number';
const oneNumber = () => (getProductsOfAllIntsExceptAtIndex([1]));
assertThrowsError(oneNumber, desc);
function assertArrayEquals(a, b, desc) {
const arrayA = JSON.stringify(a);
const arrayB = JSON.stringify(b);
if (arrayA !== arrayB) {
console.log(`${desc} ... FAIL: ${arrayA} != ${arrayB}`)
} else {
console.log(`${desc} ... PASS`);
}
}
function assertThrowsError(func, desc) {
try {
func();
console.log(`${desc} ... FAIL`);
} catch (e) {
console.log(`${desc} ... PASS`);
}
}