-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-get-products-of-all-ints-except-at-index.js
More file actions
124 lines (79 loc) · 2.43 KB
/
2-get-products-of-all-ints-except-at-index.js
File metadata and controls
124 lines (79 loc) · 2.43 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// arr = [1, 7, 3, 4];
//ALWAYS CONSIDER EDGE CASES!
// arr = [0, 0, 0, 0]
// arr = [1, 7, 3, 4, 0]
// arr = [1, 2, 6, 5, 9];
arr = [3, 1, 2, 5, 6, 4];
// The trick with this problem was to realize that the products before the index can be calculated and stored, and the products after the index as well.
// Needed to offset the index by 1 because there's no integers before the index we're looking at.
getProductsOfAllIntsExceptAtIndex = (arr) => {
// let arrDupe = arr.slice(0);
// let arrTemp = [];
let product = 1;
let product2 = 1;
let answer = [];
if(arr < 2) {
throw new Error('Getting a product requires at least two numbers')
}
for(var i = 0; i < arr.length; i++) {
answer.push(product)
product *= arr[i];
}
//Need to remember whether to include = in for loops
for(var j = arr.length - 1; j >= 0; j--) {
answer[j] *= product2
product2 *= arr[j]
}
return answer
}
getProductsOfAllIntsExceptAtIndex(arr)
// // arr = [1, 7, 3, 4];
// //ALWAYS CONSIDER EDGE CASES!
// // arr = [0, 0, 0, 0]
// // arr = [1, 7, 3, 4, 0]
// // arr = [1, 2, 6, 5, 9];
// arr = [3, 1, 2, 5, 6, 4];
// getProductsOfAllIntsExceptAtIndex = (arr) => {
// // let arrDupe = arr.slice(0);
// // let arrTemp = [];
// let product = 1;
// let answer = [];
// if(arr < 2) {
// throw new Error('Getting a product requires at least two numbers')
// }
// for(var i = 0; i < arr.length; i++) {
// product *= arr[i];
// console.log(product)
// }
// for(var j = 0; j < arr.length; j++) {
// answer.push(product/arr[j])
// }
// return answer
// }
// getProductsOfAllIntsExceptAtIndex(arr)
// // arr = [1, 7, 3, 4];
// //ALWAYS CONSIDER EDGE CASES!
// // arr = [0, 0, 0, 0]
// // arr = [1, 7, 3, 4, 0]
// arr = [1, 2, 6, 5, 9];
// getProductsOfAllIntsExceptAtIndex = (arrDupe) => {
// // let arrDupe = arr.slice(0);
// // let arrTemp = [];
// if(arrDupe < 2) {
// throw new Error('Getting a product requires at least two numbers')
// }
// let arrTemp;
// let answer = [];
// for(var i = 0; i < arr.length; i++) {
// arrTemp = arrDupe.shift()
// console.log(arrDupe)
// product = arrDupe.reduce((acc, ele) => {
// return acc * ele
// }, 1)
// answer.push(product)
// // console.log(arrDupe, arrTemp)
// arrDupe.push(arrTemp)
// }
// return answer
// }
// getProductsOfAllIntsExceptAtIndex(arr)