I tried to make pyramid with the length 4
this is code I have tried
console.log("-----------------------")
function middle(){
for (i = 0; i < 4; i++){
var output = '';
for(j=1; j < 4 - i; j++)
output += ' ';
for (k =1; k <=(2*i+1); k++)
output += '*';
console.log(output);
}
}
middle();
I got output
*
***
*****
*******
But I want to achieve output like this
You're likely using a monospaced font.
This means that all characters have the the same width.
This is handy in computer programming as it's more readable when things line up.
This means that it's not possible set a character 'halfway' between two others, unless you use spaces, like:
*
* *
* * *
In which case, it's just matter of adjusting your loops to include spaces in the right places.
There's no need to use loops to generate multiple characters - use String's repeat() function instead:
function middle(){
let s = "";
for (let i = 4; i >= 0; i--){
s += " ".repeat(i) + "* ".repeat(4 - i) + "\n";
}
return s;
}
console.log(middle());
Note that the empty spaces are actually non-breaking spaces - character code 160. As this outputs in monospace characters, the formatting will be ok. On a page, though, you would have to set the font-family to "monospace" to achieve the same effectc.
Seen as your question doesn't state that this has to use Console output, here is a version were the output is HTML / Webpage.
const pyramid = document.querySelector('#pyramid');
for (let l = 1; l <= 4; l +=1) {
const p = document.createElement('div');
p.innerText = '⭐'.repeat(l);
pyramid.appendChild(p);
}
#pyramid {
text-align: center;
font-size: 50px;
line-height: 90%;
}
<div id="pyramid">
</div>
This is what you need :-
const renderTree = () => {
const noOfColums = Number(document.getElementById("inputNumber").value);
let finalTree = "";
const STAR = "*";
const SPACE = "  ";
for (let rowNumber = 1; rowNumber <= noOfColums; rowNumber++) {
let row = "";
const starStarIndex = noOfColums - rowNumber;
for (let j = 0; j < starStarIndex; j++) {
row += SPACE;
}
for (let j = 0; j < rowNumber; j++) {
row += STAR + SPACE;
}
row += "<br>";
finalTree += row;
}
const div = document.getElementById("output");
div.innerHTML = finalTree;
};
window.onload = function () {
document.getElementById("inputNumber").addEventListener("change", renderTree);
};
<html>
<head>
<title>TREE</title>
<script src="./tree.js"></script>
</head>
<body>
<input id= "inputNumber" onchange="renderTree">Input your number</input>
<div>
Tree is :-
<div id="output"></div>
</div>
</body>
</html>
Related
Write a program that dynamically creates a 100x100 table. Each element
in the table will have a unique number, starting at 1 and increasing
by 1.
This page will also have a button that will be "Calculate almost prime
numbers." This button will cause all the cells in the table that have
“Almost Prime” numbers to have a yellow background.
Almost prime number: it is a number that is only divisible by itself,
the unit and by a single number that is neither the unit nor itself.
Hello, I am relatively new to the world of JavaScript and I am trying to solve this JavaScript exercise and as you can see the first part is to make a 100x100 table, which I have been able to do, the problem is the second part in which I have to change the background of the cells to the "almost prime numbers"
Here I leave my code, probably many things can be improved apart from finding a solution to putting the background color of the cells, anyway thanks if you can help me.
window.addEventListener("DOMContentLoaded", main);
function main() {
var body = document.getElementsByTagName("body")[0];
var tabla = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < 100; i++) {
var fila = document.createElement("tr");
for (var j = 0; j <= 100; j++) {
var columna = document.createElement("td");
var numero = document.createTextNode(j + i * 100);
columna.appendChild(numero);
fila.appendChild(columna);
}
tblBody.appendChild(fila);
}
tabla.appendChild(tblBody);
body.appendChild(tabla);
tabla.setAttribute("border", "2");
}
function casiprimos() {
let contador = 0;
for (var i = 0; i < 100; i++) {
for (var j = 0; j <= 100; j++) {
let num = (j + i * 100)
for (var z = 1; z <= num; z++) {
let resultado = num % z;
if (resultado == 0) {
contador = contador + 1;
}
}
if (contador == 3) {
// num.setAttribute("style","background-color: yellow;"); ? Idk
contador = 0;
} else {
contador = 0;
}
}
}
}
I'm trying display 2 different characters, but it doesn't work. It only shows one of the characters. (first letter - 8 times by 1 letter, second letter on a different line - 8 times by 3 letters).
For example:
i i i i
ttt ttt ttt ttt
Could someone help please?
<script>
function rainbow() {
var temp = "";
var i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < 6; j++) {
temp += " " + " " + " ";
}
temp += document.getElementById("dead_rainbow").value
}
var pop = "";
var k, l;
for (k = 0; k < 8; k++) {
for (l = 0; l < 3; l++) {
pop += " " + " ";
}
pop += document.getElementById("dead_unicorn").value
}
document.getElementById("demo").innerHTML = " " + temp;
document.getElementById("demo").innerHTML = " " + pop;
}
</script>
<input id="dead_unicorn" type="text" />  Character For Candles<br>
<input id="dead_rainbow" type="text" />  Character For Menorah<br><br>
<button type="button" onclick="rainbow()">Run</button>
<p id="demo"></p>
I didn't understand well your question but is this what you need ? if not let me know in order to adjust the script: so my understanding is:
input 1 = i
input 2 = j
result :
i i i i i i i i (8 times)
jjj jjj jjj jjj jjj jjj jjj jjj (8 times)
if this is correct so try this solution:
<script>
function rainbow() {
var temp = "";
var i, j;
for (i = 0; i < 8; i++) {
for (j = 0; j < 6; j++) {
temp += " " + " " + " ";
}
temp += document.getElementById("dead_rainbow").value;
}
var pop = "";
var k, l;
for (k = 0; k < 8; k++) {
for (l = 0; l < 8; l++) {
pop += " " + " ";
}
secondVal = document.getElementById("dead_unicorn").value
pop += secondVal + secondVal + secondVal;
}
document.getElementById("demo").innerHTML = " " + temp + "<br>";
document.getElementById("demo").innerHTML += " " + pop;
}
</script>
<input id="dead_unicorn" type="text" />  Character For Candles<br>
<input id="dead_rainbow" type="text" />  Character For Menorah<br><br>
<button type="button" onclick="rainbow()">Run</button>
<div id="demo"></div>
Good luck!
First and foremost: your debugger doesn't show an error because there is no - at least from a syntactical point of view. Your problem is inside the logic.
As blex already mentioned the most predominate is this:
document.getElementById("demo").innerHTML = " " + temp;
document.getElementById("demo").innerHTML = " " + pop;
I guess you might have thought this will simply add-up the strings and ultimately be assigned to the .innerHTML property of your <div>. Well that's not the case. With the = operator you're assigning a new value - so the second call will wipe out what was there previously. You can add the two strings (and possibly a new line tag) and assign it in one go:
document.getElementById("demo").innerHTML = " " + temp + pop;
Your for-loop seems a bit overloaded. To simplify I'd recommend creating a 'pattern' by code, which you simply repeat using a simpler for-loop.
So in pseudo-code:
My-result=[empty]
My-pattern= ttt[space]
for a=0 to 8
My-result = My-result + My-pattern
Now unfortunately I'm not sure what you want the result to look like. I think you want to have the single characters right above the space in between the groups of three letters. With a standard font this is not exactly possible because the width of individual characters is not the same. As a result it will look a little something like this:
As you can see the letters drift apart. Compensation is usually done by using a monospace font. That's a font where e.g. the space character and the i character (as well as all other characters) are of equal width.
You can fake it by putting equal characters in between your desired characters on both lines and make them invisible.
Here's an example:
function rainbow() {
var letterA = document.getElementById("dead_rainbow").value;
var letterB = document.getElementById("dead_unicorn").value;
var myResult = "";
var myPattern = "<span style='visibility:hidden;'>" + letterA + letterA + letterA + "</span>" + letterB;
for (j = 0; j < 8; j++) {
myResult += myPattern;
}
myResult += "<br>";
myPattern = letterA + letterA + letterA + "<span style='visibility:hidden;'>" + letterB + "</span>";
for (j = 0; j < 8; j++) {
myResult += myPattern;
}
document.getElementById("demo").innerHTML = myResult;
}
<input id="dead_unicorn" type="text" />  Character For Candles<br>
<input id="dead_rainbow" type="text" />  Character For Menorah<br><br>
<button type="button" onclick="rainbow()">Run</button>
<p id="demo"></p>
I am trying to draw a grid on screen numbered in a snake pattern in Javascript, I have a working grid but it follows the pattern of
12345
67890
And what I need is
12345
09876
I have seen this done with modulo and have tried to implement but im having trouble getting the right number sequence.
Here is my function
function createGrid(length, height) {
var ledNum = 0;
for (var rows = 0; rows < height; rows++) {
for (var columns = 0; columns < length; columns++) {
var backwards = ledNum + columns;
if (rows % 2 == 0 || rows != 0) {
$("#container").append("<div class='grid' id='" + ledNum + "'>" + //HERE IS MY PROBLEM+"</div>");
}
else if (!rows % 2 == 0) {
$("#container").append("<div class='grid' id='" + ledNum + "'>" + ledNum + "</div>");
}
ledNum++;
};
};
$(".grid").width(960 / length);
$(".grid").height(960 / height);
};
How do I work out the true modulo case to show the numbers correctly in snake pattern?
I am not well versed with 2d arrays but perhaps that might be a better way?
The best way I can think of is to use an object with arrays and exploit its inbuilt functions to ease your job...for example
function createGrid(length,height) {
var lednum = 0;
var grid = [];
for (var row = 0; row < height; row++) {
grid[row] = [];
for (var col = 0; col < length; col++) {
if ((row % 2) === 0) {
grid[row].push(lednum);
} else {
grid[row].unshift(lednum);
}
lednum++;
}
}
return grid;
}
console.log(createGrid(10, 10))
Then you can just print out above grid
Update : How to print above data. You could simply use two for loops.
var length = 10;
var height = 15;
var brNode = document.createElement('br');
var grid = createGrid(length, height));
for (var row = 0; row < height; row++) {
var rowPrint = "";
for (var col = 0; col < length; col++) {
rowPrint += String(grid[row][col]) + " ";
}
var rowNode = document.createTextNode(rowPrint)
$("#container").appendChild(rowNode);
$("#container").appendChild(brNode);
}
Note that this will create rows of textNode broken by <br/> tags. if you want it formatted in some other way..well you have the preformatted data..all you need to do is traverse through it and print it how you want.
This general idea seems to work...
// Input variables
var data = 'abcdefghijklmnopqrstuvwxyz';
var width = 5;
// The actual algorithm.
var rows = Math.ceil(data.length / width);
for (var y = 0; y < rows; y++) {
var rowText = "";
for (var x = 0; x < width; x++) {
// Basically, for every other row (y % 2 == 1),
// we count backwards within the row, as it were, while still
// outputting forward.
var offset = y * width + (y % 2 == 1 ? width - 1 - x : x);
rowText += data[offset] || " ";
}
console.log(rowText);
}
$ node so51356871.js
abcde
jihgf
klmno
tsrqp
uvwxy
z
As I mentioned in comments, there is a lot wrong with the boolean logic in your code:
The first if condition always evaluates to true, except in the first iteration
The second if condition is therefor only evaluated once, and it will be false.
I would split the functionality in two parts:
Create a 2D array with the numbers in "snake" sequence
Create the DOM elements from such a matrix, using some CSS to control the line breaks
function createSnake(width, height) {
const numbers = [...Array(width*height).keys()];
return Array.from({length:height}, (_, row) =>
numbers.splice(0, width)[row % 2 ? "reverse" : "slice"]()); // 2D array
}
function createGrid(matrix) {
$("#grid").empty().append(
[].concat(...matrix.map(row => row.map((val,i) =>
$("<div>").addClass("grid").toggleClass("newline", !i).text(val))))
);
}
// Demo generating a 3 x 3 grid
createGrid(createSnake(3,3));
.grid {
float: left;
padding: 3px;
}
.newline {
clear:left
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid"></div>
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
}
return line + "\n";
}
console.log(makeLine(2));
I am trying to print triangle, i dont know where i am doing wrong, can some please explain the logic behind printing triangle using nested loops
*
**
***
After you finish printing a line, you need to add a newline "\n" so that you move to the next line. You could do this as below :
function makeLine(length) {
// length has the number of lines the triangle should have
var line = "";
for (var i = 1; i <= length; i++) {
// Enter the first for loop for the number of lines
for(var j=1; j<=i; j++){
// Enter the second loop to figure how many *'s to print based on the current line number in i. So the 1st line will have 1 *, the second line will have 2 *s and so on.
line += "*";
}
// Add a newline after finishing printing the line and move to the next line in the outer for loop
line+="\n";
}
// Print an additional newline "\n" if desired.
return line + "\n";
}
console.log(makeLine(2));
don't forget about .repeat()
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
line+="*".repeat(i)+"\n";
}
return line;
}
console.log(makeLine(3));
The \n was at an incorrect position.
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
line += "\n";
}
return line;
}
console.log(makeLine(5));
function hashTriangle(length)
{
let str="";
for(let i=0;i<length;i++)
{
str+="#";
console.log(str);
}
}
hashTriangle(7);
console.log() prints a new line. So it is not necessary for nested loops and confusing newline characters to be appended to our string.
function makeLine(length) {
var line = "";
for (var i = 1; i <= length; i++) {
for (var j = 1; j <= i; j++) {
line += "*";
}
// add new line after loop is completed
line = line + "\n"
}
return line + "\n";
}
console.log(makeLine(5));
you need to add \n to line when the inner loop is completed
const printTriangle=(symbol,gapSymbol,num) =>{
// const num =25;
let gap = 1;
const Sgap = symbol+' ';
for(i= num-1;i>=0;i--){
let prefixSuffix=''
prefixSuffix = gapSymbol.repeat(i);
let line = ''
if(i == num -1){
line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(i);
}
if(i != num -1 && i !=0){
line = gapSymbol.repeat(i)+symbol+gapSymbol.repeat(gap)+symbol+gapSymbol.repeat(i);
gap = gap+2;
}
if(i<1){
line = ''+Sgap.repeat(1)+Sgap.repeat(num-2)+Sgap.repeat(1);
}
console.log(line)
}
}
printTriangle('*','.',15)
This is a JavaScript function that generates a triangle shape using the console.log method. The function takes in three parameters:
symbol: the character to be used to draw the triangle
gapSymbol: the character to be used as a gap in between the symbols
num: the size of the triangle (the number of symbols on the base)
The function starts by initializing the variable gap with the value 1 and Sgap as a string of symbol followed by a space. It then uses a for loop to iterate num number of times, starting from num - 1 down to 0.
For each iteration of the loop, the function uses a single line variable to store the string to be logged. The prefixSuffix variable is used to store the repeated gapSymbols, which are used in each iteration of the loop.
The logic for each iteration is controlled by conditional statements, which determine the shape to be drawn based on the value of i. If i is equal to num - 1, the line is constructed using a single symbol surrounded by repeated gapSymbols. If i is not equal to num - 1 and i is not equal to 0, the line is constructed using repeated gapSymbols, a symbol, a gap of repeated gapSymbols, and another symbol, all surrounded by repeated gapSymbols. If i is less than 1, the line is constructed using repeated Sgaps.
Finally, the constructed line is logged using the console.log method.
Simple solution using padStart, padEnd, repeat method for printing right and left triangle
Left triangle
const printLeftTriangle = (n) => {
let output='';
for (let i = 1; i <= n; i++) {
output +="*".repeat(i).padStart(n) + "\n";
}
return output;
}
console.log(printLeftTriangle(5));
Right triangle
const printRightTriangle = (n) => {
let output='';
for (let i = 1; i <= n; i++) {
output +="*".repeat(i).padEnd(n) + "\n";
}
return output;
}
console.log(printRightTriangle(5));
try this solution please:
const halfTriangle = N => {
for (let row = 0; row < N; row++) {
let line = "";
for (let col = 0; col <= N; col++) {
if (col <= row) {
line += '#';
} else {
line += ' '
}
}
console.log(line);
}
}
halfTriangle(4)
// creates a line of * for a given length
function makeLine(length) {
let line = "";
for (var j = 1; j <= length; j++) {
line += "* ";
}
return line + "\n";
}
// your code goes here. Make sure you call makeLine() in your own code.
function buildTriangle(length) {
// Let's build a huge string equivalent to the triangle
var triangle = "";
//Let's start from the topmost line
let lineNumber = 1;
for (lineNumber = 1; lineNumber <= length; lineNumber++) {
// We will not print one line at a time.
// Rather, we will make a huge string that will comprise the whole triangle
triangle = triangle + makeLine(lineNumber);
}
return triangle;
}
// test your code
console.log(buildTriangle(10));
Center Tringle
let line='';
for(let i=1; i<=5;i++){
line += ' '.repeat(5-i)
line += '*'.repeat(i+i-1)+'\n'
}
console.log(line);
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.