How to create program for asterisks forming a box? - javascript

*******
* *
* * *
* *
*******
It should look like the above arrangement of asterisks. I'm new to programming. So far I have written:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<body>
<script>
var maxCount = 7;
var iterationCount = 0;
while (iterationCount < maxCount) {
iterationCount = iterationCount + 1;
document.write('*');
}
I have a strong feeling so far that's incorrect, and even if it's correct, I don't know how to go on from there.
I know I have to use for and nested loops, but I'm extremely confused.

Try
var width = 7,
height = 7, // for example
boxElem = document.getElementById("box"); // this is the element which will hold your box
for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
if(i === 0 || i === height - 1 || j === 0 || j === width - 1 || (i === Math.floor(height / 2) && j === Math.floor(width / 2))) {
// check if it's the first or last row or column, or if it's the centre of the box
boxElem.innerHTML += "*";
} else {
boxElem.innerHTML += " "; // otherwise, don't add an asterisk but an empty space
}
}
boxElem.innerHTML += "\n"; // new line
}

Related

Star Pattern in Javascript

var i, j;
for (i = 1; i <= 19; i++) {
for (k = 1; k <= i; k++) {
document.write("*");
}
document.write("<br/>");
}
<div id="output"></div>
Trying to create this pattern and not sure of the best way of how to get it decrement after 10th row:
*
**
***
****
*****
******
*******
********
*********
**********
*********
********
*******
******
*****
****
***
**
*
First increase the loop from 1 to 10 then make a loop that decreases from 9 to 1.
const max = 10;
for (let i = 1; i <= max; i++) {
document.write("*".repeat(i) + "<br/>");
}
for (let i = max - 1; i >= 1; i--) {
document.write("*".repeat(i) + "<br/>");
}
For fun i added a slowly growing example
let max = 1;
setInterval(() => {
document.body.textContent = "";
for (let i = 1; i <= max; i++) {
document.write("*".repeat(i) + "<br/>");
}
for (let i = max - 1; i >= 1; i--) {
document.write("*".repeat(i) + "<br/>");
}
max++;
}, 500)
Some notes on your code:
You should avoid document.write
Instead of having nested loops you could use String#repeat, to replicate the * character.
To manage the descend you just have to check whether the index has surpassed the half way point, and if it has print totalHeight - index + 1 amount of *;
Here is a interactive example based on the above notes.
function printTree(size, dom) {
if (!(dom instanceof HTMLElement)) dom = document.body; // if the element hasn't been defined get the body element
dom.innerHTML = ""; // clear any old content of the element
var half = Math.ceil(size / 2); // get the halfway point to compare (and avoid extra calculations inside loop);
for (var index = 1; index <= size; index++) {
dom.appendChild(document.createElement("div")).textContent = "*".repeat(index > half ? size - index + 1 : index);
}
}
var input = document.querySelector("#num"),
content = document.querySelector("#content");
input.addEventListener("input", refresh);
refresh();
function refresh() {
printTree(+input.value, content);
}
<input type="number" id="num" value="5" />
<div id="content"></div>

How to print basic Christmas Tree with JavaScript?

Trying to make a simple script that draws a tree of certain height in console with simple JS loops. It should look like that.
For height = 4 :
*
***
*****
*******
so far have this but somehow it's not working:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '***';
}
for ( var k = height - 1 ; k > 0; k-- ) {
spacesBefore = space.repeat(k);
star = spacesBefore + star;
}
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
alert('Check console')
any advice where I'm wrong? thx <3
You had 2 minor problems with your code.
There should be an odd number of stars per level (1, 3, 5, 7, ...) and you were adding 3n + 1 stars which will alternate between even and odd. The change to make for that is star = star + "**" instead of ... + "***"
There is no need for the for (var k = ...) loop for counting the spaces. Your logic is right, but looping over the entire height for each row will yield you the same number of spaces per row, which is what your output is showing, which is wrong. What you want to do instead for the number of spaces is height - i - 1.
A working solution would look like the following:
function drawTree(height) {
for ( var i = 0; i < height ; i++ ) {
var star = '*';
var space = ' ';
for ( var j = 1; j <= i; j++ ) {
star = star + '**';
}
var spacesBefore = space.repeat(height-i-1);
star = spacesBefore + star;
console.log(star);
}
}
var levels = prompt('How many levels high should be the tree?');
drawTree(levels);
A more concise version of this code would look like the following:
function drawTree(height) {
for (var i = 0; i < height; i++) {
// 2n+1 stars per row i.e. 1, 3, 5, 7, ...
var stars = '*'.repeat(2 * i + 1);
var spacesBefore = ' '.repeat(height - i - 1);
console.log(spacesBefore + stars);
}
}
drawTree(prompt('How many levels high should be the tree?'));
Would like to calculate width first and then use that width. Spaces are depended upon width and number of * in each height.
width = height*2 - 1;
Code for tree:
function tree(h) {
let i =0, j = 1;
w = h*2 - 1;
let space = parseInt(w / 2);
while (space >= 0) {
let str = '';
for (i = 0; i < space; i++) str += ' ';
for (i = 0; i<j; i++) str += '*';
console.log(str);
// Since every next line got 2 more *
j += 2;
// Number of space reduce by 1
space--;
}
}
function drawTree(h) {
let star = "*";
let space = " ";
let spaceCount = h-1;
let starCount = 1;
for(let i = 0; i < h; i++) {
console.log(`${space.repeat(spaceCount)}${star.repeat(starCount)}${space.repeat(spaceCount)}`);
spaceCount -= 1;
starCount += 2;
}
}
drawTree(20)

Pyramide of Stars Javascript

How could I create Pyramide of Stars that increase every row by 2 like that:
*
* * *
* * * * *
* * * * * * *
My currently code:
for (var x = 0; x < 5; x++) {
for (var y = 0; y <= x; y = y + 1) {
document.write(" * ");
}
document.write("<br>");
}
It's possible just to increment in your loop by 2.
for(var i = 1; i < 20; i += 2) {
console.log( Array(i).fill('*').join(' ') );
}
Otherwise just multiply inside your loop
for(var i = 0; i < 10; i++) {
console.log( Array(i*2 + 1).fill('*').join(' ') );
}
You may also need to polyfill Array.fill depending on your target.
Other answers recreate the entire row each time. This solution just extends the row each time to have another star.
function pyramid(n) {
let result = '', str = '', add = '*';
for (var i = 0; i < n; i++) {
str += add;
add = ' *';
if (!(i % 2)) result += str + '\n';
}
return result;
}
console.log(pyramid(5));
You can do like this.
function generate() {
var totalNumberofRows = 5;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
if(j==1)
output+="*";
else
output+=" "+ "*" + " "+ "*";
}
console.log(output);
output="";
}
}
generate()
Hope so this is also beneficial for you....
$(document).ready(function () {
var NumberofRows = 5,arr;
for (var i = 1; i <= NumberofRows; i++) {
pyramid = [];
for (var j = 1; j <= i; j++) {
pyramid.push('*');
}
console.log(pyramid.join(" ") + "\n");
}
});
``

How do you make every 9th element in Math.random array to be the same element?[javascript]

I have this bit of code here
<script language='javascript' type='text/javascript'>
var imagesArray = ["1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png","11.png","12.png","13.png","14.png","15.png","16.png","17.png","18.png","19.png","20.png","21.png" ];
var newArray = new Array(100);
for (i = 0; i < 100; i++)
{
if (i % 9 === 0)
{
}
else
{
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
}
}
</script>
the idea behind is that i need it so that every 9th number that would be randomly chosen would remain the same, but i have no idea what do i put there so it would work.
Do you got any advice?
Thanks!
Here is a sample of what you can do :
First fill your array with Math.random() or whatever you want.
imagesArray[i] = Math.floor((Math.random() * 10) + 1);
If you want the value to be the same every 9 elements , use a loop starting at 9 and going through every 9 elements with i+9
for(var i = 9; i < yourArray.length ; i = i + 9){
imagesArray[i] = imagesArray[9];
}
Actually you can start the loop at 18 as well
Demo
Try defining a variable outside of for loop to store value at first i % 9 === 0
var newArray = new Array(100), ninth = null;
for (i = 0; i < 100; i++) {
newArray[i] = imagesArray[Math.floor(Math.random() * imagesArray.length)];
if (i % 9 === 0 && ninth === null && i === 9) {
ninth = newArray[i]
};
if (i % 9 === 0 && i >= 9) {
newArray[i] = ninth;
};
}

changing 2 random numbers in 30 times in number table using java script

In this code each time you open the html page two random numbers are generated and thier location in the matrix will be changed.
for example the random numbers are 2,8
in the main table 2 is in the matrix[0][1],matrix[1][7],matrix[2][4],matrix[3][0],matrix[4][6],matrix[5][3],matrix[6][8],matrix[3][0],matrix[7][5]
,matrix[8][2] .in the result table 8 is set in these location and 2 is set in the current locations of 8.
I want to repeat this, 30 times.
so far I have :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
document.writeln('<table border="1">');
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
document.writeln("The result table is:");
for(i=0; i<9; i++)
{
document.writeln('<tr>');
for(j=0; j<9; j++)
{
if(matrix[i][j]==r1)
{
matrix[i][j]=r2;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
else if(matrix[i][j]!=r1 && matrix[i][j]!=r2)
document.writeln('<td>' + matrix[i][j] + '</td>');
else if(matrix[i][j]==r2)
{
matrix[i][j]=r1;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
</script>
</body>
</html>
I would change your code slightly.
First, I'd make a method to print the table:
function printMatrix(var matrix)
{
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
}
Then, I'd make a method for the swapping:
function sawpTwoNumbers(matrix)
{
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
// This is new code:
for(int i=0; i< matrix.length; i++){
var r1Index = matrix[i].indexOf(r1);
var r2Index = matrix[i].indexOf(r2);
matrix[i][r1Index] = r2;
matrix[i][r2Index] = r1;
}
}
Next, I'd put your code in the pageLoad method:
function pageLoad()
{
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
printMatrix(matrix);
// This is new code:
// It will call the swap method and the print method 30 times.
for(int i = 0; i < 30; i++)
{
swapTwoNumbers(matrix);
printMatrix(matrix);
}
}
Please Note: I haven't tested this code. I don't guarantee that it works. I hope it'll give you a push in the right direction though.

Categories

Resources