I have the following problem, I have tried in several ways, but still I am getting the below output, but my desired output is different. Can anyone of you please check and let me know where I am doing wrong and how to achieve the desired output pattern. I have an input number(n). The input value should be between 2 and 10. We need to validate if the input value is not in expected range.
I am getting the below output:
if I enter n = 2:
A
B C
if I enter n = 3:
A
B C
D E F
But my desired outputs are like below:
Example 1. if I give n = 3 in the input field, then we need to show the below output:
A
A B
C D E
Example 2: if I give n = 4 in the input field, then we need to show the below output:
A
A B
A B C
D E F G
Created Stackblitz
You can just change the logic like so.
First we split the string into an array.
Then we use slice
to specify the start and end index.
We adjust the start and end indexes to generate the desired output.
For the last index alone, we take from the last element upto n characters, this generates the same output as the expected.
createSequence(n: number): string[] {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let sequence: string[] = [];
let currentCharIndex = 0;
for (let i = 1; i <= n; i++) {
const alphaArr = alphabet.split('');
const output = i !== n ? alphaArr.slice(0, i) : alphaArr.slice(i - 1, i + n -1);
console.log(output);
sequence.push(output.join(' '));
}
return sequence;
}