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>
Related
Here is the my javascript code for printing the pattern shown below in the image.
please check the code and solve the error.
<script>
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
</script>
I want Output like this :
but I got just 2 spaces in output
Convert your input to Number:
n = Number(n);
and then change your code as #TomLV mentioned:
var n = prompt("Enter the number of n you want to print");
//rows = Math.floor(n / 2)
n = Number(n);
let str = ""
var i, j, k
for(i = 1; i <= n; i++){
for(j = 1; j <= i; j++){
str += "*"
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(k = n + 1; k >= i; k--){
str += " "
}
for(j = 1; j <= i; j++){
str += "*"
}
str += "\n"
}
for(i = 1; i <=n + 2; i++){
for(j = n + 2; j > i; j--){
str += "*"
}
for(k = 1; k <= i; k++){
str += " "
}
for(k = 1; k <= i; k++){
str += " "
}
for(j = n + 2; j > i; j--){
str += "*"
}
str += "\n"
}
console.log(str)
You are setting str equal to " " in both "k loops" in the second "i for loop".
e.g:
for(k = 1; k <= i; k++){
str = " "
}
for(k = 1; k <= i; k++){
str = " "
}
If you update those to += it works.
Some issues:
prompt returns a string, you need to convert it to a number. You can use the unary plus for that.
str = " " occurs at two places where you should have done str += " "
The generated pattern has two spaces in the center line, while you are asked to only have one space there. To make that happen have the k loops make one iteration less, and add str += " " as a separate statement outside of those loops.
The output has an empty line at the very end. This is because the second i loop is making one iteration too many.
Not a problem, but:
Use semi-colons to separate statements. Although JavaScript provides automatic semi-colon insertion, you wouldn't be the first to fall into one of the pitfalls. It is better to take control of this yourself and have the habit of adding the semi-colons.
There really is no need here to declare loop variables at the top. Just declare them at the moment you need them with only the scope they need to have.
I'll assume that the number of lines in the output is supposed to be n*2+1 and that there was no error concerning that aspect.
Corrected code:
// Convert string to number using unary plus:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= i; j++) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = n; k >= i; k--) {
str += " ";
}
for (let j = 1; j <= i; j++) {
str += "*";
}
str += "\n";
}
// Reduced number of iterations. i should not become equal to n + 2
for (let i = 1; i <= n + 1; i++) {
for (let j = n + 2; j > i; j--) {
str += "*";
}
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
// Add one space for the center column
// that is the only column without asterisks
str += " ";
// Reduced the number of iterations here:
for (let k = 1; k < i; k++) {
str += " "; // Fixed assignment
}
for (let j = n + 2; j > i; j--) {
str += "*";
}
str += "\n";
}
console.log(str);
Note that JavaScript has functions that can facilitate this proces, like "*".repeat(i) can be used instead of a loop to produce the same string.
So then it becomes:
const n = +prompt("Enter the number of n you want to print");
let str = "";
for (let i = 1; i <= n + 1; i++) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
for (let i = n; i >= 1; i--) {
str += "*".repeat(i) + " ".repeat(2*n + 3 - 2*i) + "*".repeat(i) + "\n";
}
console.log(str);
And you could also reuse the results of the first loop to derive the second half of the output by storing the lines in an array. You can then reverse that array to get the second half (without the middle line):
const n = +prompt("Enter the number of n you want to print");
const arr = Array.from({length: n + 1}, (_, i) =>
"*".repeat(i+1) + " ".repeat(2*(n-i)+1) + "*".repeat(i+1)
);
console.log([...arr, ...arr.reverse().slice(1)].join("\n"));
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>
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.
I'm trying to create a simple algorithm that builds an array with a dynamic length.
Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last.
like this:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
I put together a simple demo to show what I'm trying to do.
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
Fiddle
It works fine, the only problem is it's out of order.
Right now it seems to only iterate by number of asterisks, then by index. I need it to do the opposite.
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
If someone could help that would be great because I am really at a loss!
This should get it done.
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
JSFiddle
This seems to work well:
str = "1234567"
len = str.length;
for(var stars = 1; stars < len - 1; stars++) {
for(var pos = 1; pos < len - stars; pos++) {
var s = str.substr(0, pos)
+ new Array(stars + 1).join("*")
+ str.substr(pos + stars);
document.write(s + "<br>");
}
}
I have this problem I have been working on for a few days. I need to make a page that requests the user for 12 letters, and click the submit button. I cannot make what I have come up with work. Suggestions are welcomed! The Javascript that is run should do the following: Generate a random number 1-3, for the number of rows, and put the 12 characters into a formatted table. For example, a random generated table might produce the following:
Text entered: abcdefghijkl
a b c
d e f
g h i
j k l
Or:
a b c d
e f g h
i j k l
etc.
My HTML:
<form name="table">
<p>Enter 12 letters</p>
<input type="text" id= "userVal" size="12">
<input type="button" value="submit" onclick="createTable()">
Javascript:
var numrows= randomnumber=Math.floor(Math.random()*4)
var numcols=4
document.write ("<table border='1'>")
for (var i=1; i<=numrows; i++)
{
document.write ("<tr>");
for (var j=1; j<=numcols; j++)
{
document.write ("<td>" + i*j + "</td>");
}
document.write ("</tr>");
}
document.write ("</table>");
function createTable(){
See if this is the behavior you are looking for:
http://jsfiddle.net/sDbkw/
I modified the loops to be zero based and referenced the textbox:
var createTable = function () {
var numrows = Math.floor(Math.random()*3) + 1; // x3 gets 0, 1, or 2 so increment 1
var numcols = 12 / numrows; // if always printing 12 chars
var userText = $('#userVal').val();
var output = "<table border='1'>";
for (var i=0; i < numrows; i++)
{
output += "<tr>";
for (var j=0; j<numcols; j++)
{
output += '<td>' + userText[i*numcols + j] + '</td>';
}
output += "</tr>";
}
output += "</table>";
$('#output').html(output);
};