 # Algorithm for Printing pattern

I am stuck while printing pattern like this:

12345*
1234**
123***
12****
1*****

Can anyone suggest the algorithm ?

Looks like there is a repeat button so you should be using a loop.

Pseudo algorithm would be starting from the back, replace current value to *.

You can do this with a lot of ways.

For, return stament, etc…

My favorit one is the return one:

``````const minusOne = (number) => {
const asterisk = number.match(/\*/g);

if(asterisk == null) {
console.log(number);
return minusOne(`\${number.substring(0,number.length - 1)}*`)
} else {
const howMany = asterisk.length;
if(howMany == number.length) {
console.log(number);
return
} else {
console.log(number);
return minusOne(`\${number.substring(0,number.length - 1 - howMany)}\${asterisk.join('')}*`)
}
}
}

minusOne('12345');
``````

I forgot to mention that I wanted it to be written using loop. I have posted it in javascript section, but originally I was figuring this in php (I thought, I will implement the same loop in php).

``````
const printNumberStarMatrix = function (row, col) {

for (let i = 1; i <= row; ++i) {
let strToPrint = "";
for (let j = col - i; j >= 1; --j) {
strToPrint = j + strToPrint;
}
while (strToPrint.length < col) {
strToPrint += "*";
}
console.log(strToPrint);
}
}
``````
1 Like

Will you please elaborate, What the loop is doing in every step.

row = the total number of strings you want to print
col = the length of each string

The inner for loop builds the strToPrint by adding numbers to it at every iteration(however, I’ve assumed that you want at least 1 star on the first printed line, if that is not the case you should tell me what exactly you want to achieve). The inner while loop completes the strToPrint by adding stars to it if it’s not long enough.

The outer loop just repeats the inner loops row number of times.

If we use a different assumption from the one above (e.g. add stars to the first line only if col > row), then we can revise the details of the inner for loop to make sure it adds the right number of numbers.

``````const printNumberStarMatrix = function (row, col) {

for (let i = 0; i < row; ++i) {
let strToPrint = "";
for (let j = row > col ? col - i : row - i ; j >= 1; --j) {
strToPrint = j + strToPrint;
}
while (strToPrint.length < col) {
strToPrint += "*";
}
console.log(strToPrint);
}
}
``````