-
Notifications
You must be signed in to change notification settings - Fork 0
/
question1.js
44 lines (40 loc) · 1.13 KB
/
question1.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
let array = [2,2,2,2,2,2,2,2,2,2]; // test case 1
// let array = [4,2,1,3]; // test case 2
// let array = [8,4,6,12] // test case 3
// let array = [2,4,8,20] // test case 4
let timeTaken = [];
function addAndPushLowestTwoNumbers(array) {
let lowestNumber1 = 10000000;
let lowestNumber2 = 10000000;
let lowestNumber1Index = -1;
let lowestNumber2Index = -1;
for(let i=0;i<array.length;i++) {
if(lowestNumber1>=array[i]) {
lowestNumber1=array[i];
lowestNumber1Index = i;
}
}
array.splice(lowestNumber1Index, 1);
for(let i=0;i<array.length;i++) {
if(lowestNumber2>=array[i]) {
lowestNumber2=array[i];
lowestNumber2Index=i;
}
}
array.splice(lowestNumber2Index,1);
timeTaken.push(lowestNumber1+lowestNumber2);
array.push(lowestNumber1+lowestNumber2);
if(array.length>1) {
addAndPushLowestTwoNumbers(array);
}
else
return timeTaken
}
array = array.sort(function(a,b) {
return a-b;
})
addAndPushLowestTwoNumbers(array);
timeTaken = timeTaken.reduce((a,b)=>{
return a+b;
})
console.log(timeTaken);