-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay 18 - ArrayPreviousLess.js
61 lines (45 loc) · 1.4 KB
/
Day 18 - ArrayPreviousLess.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
/*Array previous less
https://scrimba.com/scrim/cod3741dcb9da7acefae9c8b2
DESCRIPTION:
Given an array of integers, for each position i, search among the previous positions for the last (from the left) position
that contains a smaller value. Store that value at position i in the answer. If no such value can be found, store -1 instead.
Example:
For items = [3,5,2,4,5], the output should be [-1,3,-1,2,4]
Hints: unshift()
*/
function arrayPreviousLess(nums) {
let result = []
for(i=0; i < nums.length; i++) {
let everythingBefore = nums.slice(0, i)
//console.log(i + " " + nums[i] + " :" + everythingBefore)
let r = findNumLowerThan(everythingBefore, nums[i])
result[i] = r
console.log(r)
}
return result
}
function findNumLowerThan(arr, num) {
let result = -1
for (let i = 0; i < arr.length; i++) {
const elem = arr[i]
if (elem < num) {
result = elem
}
}
return result
}
/**
* Test Suite
*/
describe('arrayPreviousLess()', () => {
it('shift previous postions from the left to a smaller value or store -1', () => {
// arrange
const nums = [3, 5, 2, 4, 5];
// act
const result = arrayPreviousLess(nums);
// // log
console.log("result: ", result);
// // assert
expect(result).toEqual([-1, 3, -1, 2, 4]);
});
});