How to generate numbers in the following pattern in js?
const output = [1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100,200,300,400,500,600,700,800,900,1000,2000,3000,4000,5000, ... ]
Here is another solution. Basically you loop through the numbers 1-9 again and again, multiplying by 1, 10, 100 etc.
const maxExponent = 5;
let exponent = 0;
let result = [];
while (exponent <= maxExponent) {
for (let i = 1; i < 10; i++) {
result.push(i * Math.pow(10, exponent));
}
exponent++;
}
console.log(result);
You could take the logarithm of 10 and add one to the found digit.
const
fn = i => {
const l = Math.floor(Math.log10(i)),
d = i / 10 ** l;
return (d + 1) * 10 ** l;
};
for (i = 1; i < 10000; i = fn(i)) {
console.log(i);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
A non math approach
const
fn = i => +i.toString().replace(/./, d => +d + 1);
for (i = 1; i < 10000; i = fn(i)) {
console.log(i);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Not actually Math but working using string.repeat :)
max_zeros = 5;
cur_zeros = 0;
zero_string = '0';
output = [];
for (var cur_zeros = 0; cur_zeros <= max_zeros; cur_zeros++) {
for (var i = 1; i < 10; i++) {
output.push( parseInt(i + zero_string.repeat(cur_zeros)) )
}
}
console.log(output)