How to create multiple pyramid in Javascript? - javascript

I want to create a multiple pyramid program using Javascript but I really don't understand from where should I start to create multiple star pyramid program.
Note: I have to create this using For Loop.
Output I want:
* *
* * * *
* * * * * *
Here is my Code:
for(i=1;i<=3;i++){
for(j=1;j<=i;j++){
document.write("*"+ " ")
}
for(k=5;k>=1;k=k-2){
for(m=1;m<=k;m++){
document.write("*")
}
}
document.write("<br>")
}

Try the following:
var allowedIndexes = [];
const columnNum = 6
for(var i=0; i<3 ;i++){
allowedIndexes.push(i)
allowedIndexes.push(columnNum - (i+1))
for(var j=0;j< columnNum ;j++){
if(allowedIndexes.includes(j)){
document.write("* ")
}
else {
document.write(" ")
}
}
document.write("<br>")
}

The following code would draw a double pyramid of N levels, using underscores (_) to depict spaces. You may modify the characters used.
const drawPyramid = length => {
for (let i = 0; i < length; i++) {
const N = 2*(length - i - 1)
, blankValues = [...Array(N+1).keys()].slice(1).map(n => n + i)
for (let j = 0; j < 2 * length; j++) {
if (!blankValues.includes(j)) document.write("* ")
else document.write("_ ")
}
document.write("<br>")
}
}
drawPyramid(3)
document.write("<br>")
drawPyramid(4)
document.write("<br>")
drawPyramid(10)

const writePyramid = (levels, row = 0, level = [], spacers = 0) => {
if (row === levels) return;
document.write("<br>")
if (spacers === 0) spacers = levels + 1;
let stars = new Array(row + 1).fill('*')
level = [...stars, ...new Array(spacers > 1 ? spacers : 0).fill(' '), ...stars]
document.write(level.join(''))
writePyramid(levels, row + 1, level, spacers / 2);
}
writePyramid(3)

Related

Pattern of star in JavaScript

I have a problem in JavaScript programing. I am beginner and from last 24 hrs I just completed one task that made pyramid star pattern which only work in console but the problem is this, that the same coding doesn't work on browser. In the browser the triangle become 📐 such type of triangle.
I added br to code for the browser but the triangle become 📐 right angle triangle.
use pre tag to render your result, so it doesn't remove extra spaces. most html tag will remove extra spaces because it thinks those are useless.
let starCount = 1;
const row = 35
let result = "";
for (let i = 0; i < row; i++) {
let starString = "";
const p = starCount;
for (let j = 0; j < row; j++) {
if (j >= ((row - p) / 2) && j < (((row - p) / 2) + p)) {
starString += "*";
continue;
}
starString += " "
}
result += starString + "\n";
if (row % 2 == 0) {
if (i < (row / 2) - 1) {
starCount += 2;
}
if (i > ((row / 2) - 1)) {
starCount -= 2;
}
} else {
if (i < Math.floor(row / 2)) {
starCount += 2;
} else {
starCount -= 2;
}
}
}
document.querySelector("pre").innerHTML = result;
<pre></pre>

Getting a type error: cannot read properties of undefined (reading 'value) when implementing quick sort in javascript

Please excuse the bad structure of the program. I'm a newbie programmer trying my first project in creating a sorting visualizer. I was able to implement bubble sort, but when I came around to trying to see if quick sort worked with the values in the child divs, I keep getting this error. My partition function correctly changes the value in each div, but my quick sort function shoots this error out. What's going on?
return Math.floor(Math.random() * (max - min) + min);
}
function rand_num_height(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//Visuals
let speed = 500;
let c = 0;
let delay = 10000 / (Math.floor(10 / 10) * speed);
let p = "#75DF5B";
let p1 = "#63D7D8";
let p2 = "#008FF9";
let sorted = "#A946DA";
let p3 = "#E9EC13";
let p4 = "#F50101";
const anim = (bar, height, color) => {
setTimeout(() => {
bar.style.height = height + "px";
bar.style.backgroundColor = color;
}, (c += delay + 50));
};
const bar_container = document.getElementById("bar-container");
let children = bar_container.children;
const generate = document.getElementById("generate");
const btn = document.getElementById("sort-btn");
const reset = document.getElementById("reset");
generate.addEventListener("click", () => {
generateNewArray(rand_num_bars(10, 15));
});
function generateNewArray(rand_num_bars) {
bar_container.innerHTML = "";
//Inserting child bars into parent bar container, using rand_num function to generate # of bars
for (let i = 0; i < rand_num_bars; i++) {
document.getElementById(
"bar-container"
).innerHTML += `<div id = 'indiv_bar'></div>`;
}
//Randomizing the height for each child bar
for (i = 0; i < children.length; i++) {
var rand_height = rand_num_height(100, 500);
children[i].style.height = `${rand_height}px`;
//Setting values of each element in bar_con array to the current child height to use for sorting later
children[i].value = rand_height;
}
}
function disableBtn() {
//Prevent buttons from triggering an event
generate.style.pointerEvents = "none";
btn.style.pointerEvents = "none";
//Styling the elements to visually show user buttons are disabled
generate.style.color = "#FF0000";
btn.style.color = "#FF0000";
}
//Bubble Sort Algorithm
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i - 1; j++) {
anim(arr[j], arr[j].value, p1);
anim(arr[j + 1], arr[j + 1].value, p2);
if (arr[j].value > arr[j + 1].value) {
[arr[j].value, arr[j + 1].value] = [arr[j + 1].value, arr[j].value];
anim(arr[j], arr[j].value, p2);
anim(arr[j + 1], arr[j + 1].value, p1);
}
anim(arr[j], arr[j].value, p);
anim(arr[j + 1], arr[j + 1].value, p);
}
anim(arr[n - i - 1], arr[n - i - 1].value, sorted);
}
sortState = true;
c = 0;
}
//Quick Sort Algorithm
function partition(arr, low, high) {
let i = low;
let j = high;
pivotEl = arr[low].value;
do {
do {
i++;
} while (arr[i].value <= pivotEl);
do {
j--;
} while (arr[j].value > pivotEl);
if (i <= j) {
[arr[i].value, arr[j].value] = [arr[j].value, arr[i].value];
}
} while (i < j);
[arr[low].value, arr[j].value] = [arr[j].value, arr[low].value];
return j;
}
function quickSort(arr, low, high) {
var j;
if (low < high) {
j = partition(arr, low, high);
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
}
btn.addEventListener("click", () => {
disableBtn();
quickSort(children, 0, children.length - 1);
});

Function to generate specified number of random hex and rgb colors

Trying to write a function that generates a specified amount of random rgb or hex colors. It takes 'rgb' or 'hex'(type) and then 'n'(quantity to generate) as parameters, but I'm getting NaN when running code. Here's what I have written:
function generateColors(type, n) {
let result = ''
var quantity = Number(n)
if (type === 'rgb') {
let num = Math.round(0xffffff *
Math.random());
let r = num >> 16
let g = num >> 8 & 255
let b = num & 255
return ('rgb(' + r + ', ' + g + ', ' + b + ')') * quantity;
} else if (type === 'hexa') {
let hexDigits = '0123456789ABCDEF'
let randomHex= []
for (var i = 0; i < 6; i++) {
randomHex +=
hexDigits.charAt(Math.floor(Math.random() *
hexDigits.length));
}
return [randomHex] * quantity;
} else {
console.log('type not applicable')
}
return result
}
console.log(generateColors('rgb', 3))
console.log(generateColors('hexa', 3))
Not sure what I'm missing, or if I should do a switch statement instead, but any advice is welcome.
you will need to use loop...
you can loop n times inside the function. push the output into the result and return the result. it will look like something like this:
function generateColors(type, n) {
let result = [];
for (let x = 0; x < n; x++) {
if (type === "rgb") {
let num = Math.round(0xffffff * Math.random());
let r = num >> 16;
let g = (num >> 8) & 255;
let b = num & 255;
result.push("rgb(" + r + ", " + g + ", " + b + ")");
} else if (type === "hexa") {
let hexDigits = "0123456789ABCDEF";
let randomHex = "";
for (var i = 0; i < 6; i++) {
randomHex += hexDigits.charAt(
Math.floor(Math.random() * hexDigits.length)
);
}
result.push(randomHex);
} else {
console.log("type not applicable");
}
}
return result;
}
console.log("rgb", generateColors("rgb", 3));
console.log("hex", generateColors("hexa", 3));
Working example - dont forget to open the console ;)
Or, slightly shorter:
function mulcol(n,hex){
function rndcol(hex){
let col=[1,2,3].map(v=>Math.floor(Math.random()*256).toString(hex?16:10).padStart(hex?2:1,"0"));
return hex?`#${col.join("")}`:`rgb(${col.join(",")})`;
}
return [...Array(n)].map(v=>rndcol(hex));
}
console.log(mulcol(3)); // RGB output
console.log(mulcol(5,1));// hex output

How to generate a wordlist of alphabets using javascript

Hi Everyone I am New Here Basically i want to generate a array with the help of nodejs means i want to generate an array which keeps on generating alphabets like this
array = ["A","B","C"..."Z","AA","BB",..."ZZ","AAA","BBB",..."ZZZ"]
After googling i came across this one
function columnToLetter(column)
{
var temp, letter = '';
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
But can't understand it still new to the language
I think my method can meet your requirements
function columnToLetter(column) {
var letter = [],
newLetter = [],
merchant = Math.floor(column / 26),
remainder = column % 26;
if (merchant === 0) {
for (let i = 0; i < remainder; i++) {
newLetter.push(String.fromCharCode(i + 65));
}
return newLetter;
} else if (merchant > 0) {
for (let j = 0; j < 26; j++) {
let str = String.fromCharCode(j + 65);
letter.push(str)
}
for (let i = 1; i <= merchant; i++) {
newLetter.push(...letter);
letter = letter.map(item => item + item.split('')[0])
}
newLetter.push(...letter.slice(0, remainder));
return newLetter;
}
}
console.log(columnToLetter(28));

count 9's from 1 to n - 5kyu Kata

I am working on this kata https://www.codewars.com/kata/count-9-s-from-1-to-n/train/javascript
and i have written this code for it, but its not working. This question is similar to this one Count the number of occurrences of 0's in integers from 1 to N
but it is different because searching for 9's is practically very different to searching for 0's.
think part of the problem with this code is that it takes too long to run...
any advice appreciated!
function has9(n) {
var nine = [];
var ninearr = n.toString().split('');
for (var j = 0; j < ninearr.length; j++) {
if (ninearr[j] == '9') {
nine.push(ninearr[j]);
}
}
return nine.length;
}
function number9(n) {
var arr = [];
var arrnew = [];
for (var i = 0; i <= n; i++) {
arr.push(i);
}
for (var l = 0; l < arr.length; l++) {
arrnew.push(has9(l));
}
var sum = arrnew.reduce((a, b) => a + b, 0);
return sum;
}
Why not a regex based solution? (Too slow as well?)
const count9s = num => num.toString().match(/9/g).length
console.log(count9s(19716541879)) // 2
console.log(count9s(919191919191919)) // 8
console.log(count9s(999)) // 3
console.log(count9s(999999)) // 6
I have taken the above hint and completely re written the code, which I now feel should work, and it does for most inputs, but codewars is saying it fails on some of them. any ideas why?
function nines(n){
if(n>=100){
var q= Math.floor(n/100);
var nq= q * 20;
var r = (n%100);
var s = Math.floor(r/9);
if (r<=90){
return s + nq;
}
if (r == 99){
return 20 + nq;
}
if (90 < r < 100 && r!= 99){
var t = (r-90);
return nq + s + t;
}
}
if (n<100){
if (n<=90){
var a = Math.floor(n/9);
return a ;
}
if (n == 99){
return 20
}
if (90 < n < 100 && n!= 99){
var c = (n-90);
return 10 + c;
}
}
}
=== UPDATE ===
I just solved your kata using
function number9Helper(num) {
var pow = Math.floor(Math.log10(num));
var round = Math.pow(10, pow);
var times = Math.floor(num / round);
var rest = Math.abs(num - (round * times));
var res = pow * (round==10 ? 1 : round / 10) * times;
if (num.toString()[0] == '9') res += rest;
if (rest < 9) return res;
else return res + number9Helper(rest);
}
function number9(num) {
var res = number9Helper(num);
res = res + (num.toString().split('9').length-1);
return res;
}
== Function below works but is slow ===
So, could something like this work for you:
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
Basically, there are many way to achieve what you need, in the end it all depends how do you want to approach it.
You can test it with
function nines(n) {
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
return nines;
}
function number9(n) {
if (n < 8) {
return 0
};
if (n === 9) {
return 1
};
if (n > 10) {
let str = ''
for (let i = 9; i <= n; i++) {
str += String(i)
}
return str.match(/[9]/g).length
}
}

Categories