Last active
December 2, 2018 19:36
-
-
Save IegorT/d55175604a20c1ac37be23f2186ef434 to your computer and use it in GitHub Desktop.
UniLecs - Задача 143
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function makePyramid(height) { | |
if (typeof height !== 'number' && height < 1) throw 'Wrong number'; | |
// Total number in pyramid is qual height^2 | |
const total = Math.pow(height, 2); | |
// make 2d array filled 0 | |
// each internal array length qual number of block in this pyramid leyer | |
let output = Array.from( | |
{ length: height}, | |
(_, i) => Array.from({ length: 2*(i+1) - 1}).fill(0) | |
); | |
// accepting: | |
// array - link to array slice that need to fill | |
// start - start number | |
// iteration - number of recutsion iteration | |
function fill(array, start, iteration) { | |
if (!array.length) return; | |
// step 1: fill horizontal leyer - | |
// last array in slice | |
let h_array = array[array.length-1]; | |
let size = h_array.length - iteration; | |
for (let i = iteration; i < size; i++) { | |
h_array[i] = start; | |
start ++; | |
if (start > total) return; | |
} | |
// step 2: fill right side | |
for (let i = array.length - 2; i > 0; i--) { | |
array[i][array[i].length - 1 - iteration] = start; | |
start ++; | |
if (start > total) return; | |
} | |
// step 3: fill left side | |
for(let i = 0; i < array.length - 1; i++) { | |
array[i][iteration] = start; | |
start ++; | |
if (start > total) return; | |
} | |
fill(array.slice(1, array.length - 1), start, iteration + 1) | |
} | |
fill(output, 1, 0); | |
return output; | |
} | |
// print pyramid layers | |
function printOut(array, print) { | |
const str = array.reduce((str, arr) => { | |
return str + arr.join(' ') + '\n'; | |
}, '') | |
print(str) | |
} | |
printOut(makePyramid(4), console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment