How to get Almost Increasing Sequence of Integers in JavaScript?
JavaScript can be used to generate an almost increasing sequence of integers. An ‘almost increasing sequence’ is characterized by each element being greater than or equal to its predecessor, except at most one element being smaller than its preceding element. Our objective is to determine the length of such a sequence and subsequently return the sequence itself.
Example:
Input: n= 5 Output: [42, 49, 53, 60, 66] Explanation: In this we select a random number and then increments by random values between 1 and 10, resulting in an almost increasing sequence of length 5. Input: n= 8 Output: [20, 23, 26, 29, 32, 35, 38, 41] Explanation: In this we start with a base number and increments by 3 in each iteration to get almost increasing sequence of integers
Below are the approaches to get almost increasing sequence of integers in JavaScript:
Table of Content
- Randomized Approach
- Iterative Approach
Randomized Approach
In this approach we first generate an almost increasing sequence of integers and then randomly select the first number within a specified range after which we iteratively add a random value between 1 and 10 to the previous number to get an almost increasing sequence of integers.
Example: To demonstrate increasing sequence of integers in JavaScript using the randomized approach.
// Function for generating the sequence
function genSeq(len) {
let seq = [];
// Randomly produce first number
seq.push(Math.floor(Math.random() * 100));
// Produce the rest of the series
for (let i = 1; i < len; i++) {
let num = seq[i - 1] + Math.floor(Math.random() * 10) + 1;
seq.push(num);
}
return seq;
}
let len = 10; // length of the sequence
let sequence = genSeq(len);
console.log(sequence);
Output
[ 63, 70, 79, 80, 86, 93, 96, 100, 106, 112 ]
Time Complexity: O(n ), where n is the length of the sequence.
Auxiliary Space: O(n), because it creates an array to store the sequence of length n.
Iterative Approach
In this approach we start with a base number and increment it by a fixed amount in each iteration to generate an almost increasing sequence of integers.
Example: To demonstrate increasing sequence of integers in JavaScript using the iterative approach.
// Function for generating the sequence
function genSeq(len) {
let seq = [];
let base = 50; // Starting base number
for (let i = 0; i < len; i++) {
seq.push(base);
base += 3; // Increment base by 3 in each iteration
}
return seq;
}
let len = 10; // length of the sequence
let sequence = genSeq(len);
console.log(sequence);
Output
[ 50, 53, 56, 59, 62, 65, 68, 71, 74, 77 ]
Time Complexity: n), because it iterates over the length of the sequence to generate each number.
Auxiliary Space: O(n), because an array of length n is created to store the sequence.