Write the printNumbers () function, which takes two integer values: num - a finite number of cols - the number of columns and displays numbers from 0 to num in the following order printNumbers (12, 3)

0 4 8 1 5 9 2 6 10 3 7 11 

output is desirable via console.log

UPD: I tried while it is primitive to output 0 4 8 into one line, and how to display them in this way until I thought of it

 var num = 5; var n1 = 0; var res = 0; console.log(n1) for (i=0; i<=3; i++){ res = res + n1 +(num-1); console.log(res); } 
  • 3
    What were you trying to do? - RubaXa

2 answers 2

Perhaps there is a more elegant way:

 /** * Вывод чисел в колонках * @param {Number} max от 0 до max * @param {Number} cols количество колонок * @returns {String} */ var printNumbers = function (max, cols) { var result = [], rows = Math.ceil(max/cols), r, c, num ; for (r = 0; r < rows; r++) { row = []; for (c = 0; c < cols; c++) { num = r + (c * rows); if (num < max) { row.push(num); } } result.push(row.join(' ')); } return result.join('\n'); }; console.log(printNumbers(12, 3)); 
  • You see, I just study js and after sitting for 5 minutes I already broke my brain, can it be realized without the methods and properties of objects, arrays, objects, through the function of course. Primitive and as far as possible universal code. Of course I do not insist. - msim
  • This code can be very easily altered by replacing work with arrays with strings, etc. but here it is better for you to figure out the code yourself, and so is simple Try to provide it with comments, directly each line that is not known read on javascript.ru. In the end, you have the whole picture. - RubaXa

Solving through lines

 "use strict"; var printNumbers = function (max, cols) { // Считаем кол-во строк let stringsCount = Math.ceil(max / cols); console.log(`Строк ${stringsCount}`); let result = ''; // Выводит строку for (let i = 0; i < stringsCount; i++) { let line = ''; // Каждая строка let step = i; // Ограничивает кол-во значений в строке for (let g = 1; g <= cols; g++) { if (step < max) { line = line + step + ' '; step = step + stringsCount; } } result += line + '\n'; // console.log(line); } return result; }; console.log(printNumbers(11, 3));