Skip to content

Instantly share code, notes, and snippets.

@bmcminn
Last active October 30, 2015 07:08
Show Gist options
  • Save bmcminn/dc9f2b389ef77e3a7a7d to your computer and use it in GitHub Desktop.
Save bmcminn/dc9f2b389ef77e3a7a7d to your computer and use it in GitHub Desktop.
A simple brainteaser script that generates an "ASCII" pyramid in console
function pyramid(rows) {
var message = []
, spaces = stars = ''
;
for (var i = 1; i <= rows; i += 1) {
// The (+1) and (*2) in both equations account for Array.join() omitting the
// first (0) index when it concatenates our string
spaces = new Array(rows-i+1).join('`');
stars = new Array((i*2)).join('*');
message.push(spaces + stars + spaces);
}
return message;
}
// spaces = rows - index
// ---------------------------
// 1 | `````````*
// 2 | ***
// 3 | *****
// 4 | ***** **
// 5 | ***** ****
// 6 | ***** ***** *
// 7 | ***** ***** ***
// 8 | ***** ***** *****
// 9 | ***** ***** ***** **
// 10 | ***** ***** ***** ****
// ---------------------------
// stars = (index * 2) -1
var pyr = pyramid(15);
// render pyramid
console.log(pyr.join('\n'));
// // render diamond
// console.log(pyr.join('\n'));
// console.log(pyr.reverse().slice(1, pyr.length).join('\n'));
// // render inverted pyramid
// console.log(pyr.join('\n'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment