How do I print on a new line after every 6th number? - javascript

So I'm making a loop that's supposed to print from 0-99 and it's supposed to make a new line after every 6th number like in the example below;
012345
678910
But right now it doesn't make a new line it just increases space between the "chunks" it's displaying. How do I get it to make a new line after every 6th number?
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '\n';
i--;
}

A literal newline doesn't result in a visual newline in HTML:
foo
bar
You need <br> instead:
for (var i = 0; i < 100; i++) {
for (var j = 0; j < 6 && i <= 100; j++) {
document.body.innerHTML += i;
i++;
}
document.body.innerHTML += '<br>';
i--;
}
Or, I'd prefer to surround each block in a <div> - and you can increment the i only inside the inner loop to make the logic clearer:
for (var i = 0; i < 100;) {
const div = document.body.appendChild(document.createElement('div'));
for (var j = 0; j < 6 && i <= 100; j++, i++) {
div.textContent += i;
}
}

You could use a modulus to insert a br every sixth item - save you doing loops inside loops:
for (var i = 0; i < 100; i++) {
document.body.innerHTML += i;
if ((i + 1) % 6 === 0) { // using i plus one as you start at 0
document.body.innerHTML += '<br>';
}
}

I am answering
supposed to print from 0-99 and supposed to make a new line after every 6th number
We need a PRE to not use a <br>
document.getElementById("res").innerHTML =
Array.from(Array(100).keys())
.map(i => `${i.toString().padStart(3," ")}${(i + 1) % 6 === 0 ? '\n' : ''}`)
.join("");
<pre id="res"></pre>

Related

Variable's value changes for no reason

I am trying to make a simple tiktakto game with html, css, js. I am making a gamemode where you can square up against the computer. This code is supposed to check if a column should be blocked by the bot:
for(let i = 0; i <= 2; i++)
{
for(j = 0; j <= 2; j++)
{
console.log("j = ", j)
S += board[j][i];
} // <-- inside for loop j only goes from 0 to 2
if(S === 2) // <-- inside of this if statemnt j is 3
{
console.log("j = ", j)
if(prevent(i, j, "column")) return 1;
else return 0;
}
S = 0;
}
However somewhere after for loop the value of j randomly goes from 2 to 3 before the prevent() function can be executed, why?
This for loop:
for (j = 0; j <= 2; j++) {
console.log("j = ", j)
S += board[j][i];
}
Is equivalent to this while loop:
j = 0
while (j <= 2) {
console.log("j = ", j)
S += board[j][i];
j++
}
So if j <= 2 is true the body loop body is executed and also the j++.
The for loop will only stop once the condition evaluates to false. Here, the first time j <= 2 is false is when j has been incremented to 3.

for loop is not stopping why? even I specifically say to stop on 10 in condition

for(var i = 0; i <= 10; i+1){
console.log(i); // the loop goes on and on
}
why this for loop don't stop ? I did specifically typed in condition that it need to stop on 10.
The i+1 is your issue. It should be i = i + 1, i++ or i+=1
These are just different ways of adding 1 to the current value of i
for(var i = 0; i <= 10; i++){
console.log(i);
}
You never change i.
for (var i = 0; i <= 10; i + 1) {
^^^^^
You need to increment i
for (var i = 0; i <= 10; i++) { // or
for (var i = 0; i <= 10; i = i + 1) {
It's missing the =: i is not being mutated:
for(var i = 0; i <= 10; i += 1){
console.log(i); // the loop goes on and on
}
Change it to i++ and it will work. Right now you are just checking against 0+1 every loop iteration, and that will never be > 10.

How to print a half pyramid in javascript

The code works but I don't want the inner for loop to take me to the new line.
for (i = 0; i < 5; i++) {
for (j = 1; j <= i; j++) {
console.log('*');
}
console.log();
}
console.log('-----------------');
console.log will automatically break the line. Concatenate to a string instead of a log. Log at the end.
let str = '';
for(i = 0; i <= 5 ; i++) {
for(j = 1; j <= i; j++) {
str += '*';
}
str += '\n';
}
console.log(str);
You can do this way, with the help of a string variable:
for (i = 0; i < 5; i++) {
var str = '';
for (j = 1; j <= i; j++) {
str+='*';
}
console.log(str);
}
console.log('-----------------');
If you want to print at the page, use like below
for (i = 0; i < 5; i++) {
let j=0;
do{document.write("*");j++;}while(j < i)
document.write("<br/>")
}
You need to break the line with the console.log you can also controle the space between * with output+='*' + " ";
function pyramid() {
var total = 5;
var output="";
for (var i = 1; i <= total; i++) {
for (var j = 1; j <= i; j++) {
output+='*' + " ";
}
console.log(output);
output="";
}
}
pyramid()
You can get rid of second for loop as follows:
var str = '';
for (i = 1; i <= 5; i++) {
str +=Array(i).join("*");
str +='\n';
}
console.log(str);
let string = "";
for (let i = 0; i < 5; i++){
string += '*';
console.log(string);
}
Output:
*
**
***
****
*****
A simple way to solve this "exercise" in JavaScript:
let width = ""
while(width.length < 6) console.log(width += `#` );
Basically, we create a string (width) and increment its value using the while loop till we hit a restriction.
I found the more typical method "bulky"(?)...plus there's the issue of not getting the exact picture of a half pyramid.
let i,j
for (i= 0; i < 6; i++){
for (j = 0; j<=i; j++){
console.log("#")
}
console.log("\n")
}
function pyramid(n){
let result = "";
for(let i=0; i<=n; i++){
result += "*".repeat(i);
result += "\n"
}
return result;
}
console.log(pyramid(5));
//OutPut
*
**
***
****
*****
As we need n number of pyramid structure with '' / '#' / any symbol. by using above code we can achieve. Here you can see we just created a function called pyramid with one parameter 'n'. and inside function we declare a variable 'result'. So inside for loop the length of 'i' is "<=n" and also you can use "repeat() method to print '' 'i' times. So if you call that function like console.log(pyramid(5)); You can able to see your Answer as expected..
shortest code:
console.log('*\n**\n***\n****\n*****');

Simple Javascript Christmas Tree

I created a half of the Christmas Tree but here I got blocked. Some one please help me to understand how to do the left side too.
for (var i = 0; i < 8; i++) {
for (var j = 0; j <= i; j++) {
document.write("^");
}
document.write("<br>");
}
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>
Source: http://codeforwin.org/2015/07/equilateral-triangle-star-pattern-program-in-c.html
C to JavaScript by me.
I wrote the following code for this problem.
I also added a nice extra, christmas-tree ornaments :-)
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
private static Random RND = new Random(System.currentTimeMillis()); // useful for placing balls
private static char[] BALLS = {'o','⌾','⛣','⏣','◍'}; // symbols being used as balls
public static void main (String[] args) throws java.lang.Exception
{
int w = 27; // width of the tree
int b = 10; // number of balls in the tree
String tree = ""; // this will end up containing the tree
// build tree
w = ( w % 2 == 1 ) ? w : 13; // check whether width is odd
for(int i=1;i<=w;i+=2){
int s = (w - i) / 2;
tree += repeat(' ', s) + repeat('*', i) + repeat(' ', s) + "\n";
}
// randomly replace some parts by balls
int i=0;
while(i < b){
int j = RND.nextInt(tree.length());
if(tree.charAt(j) == '*'){
tree = tree.substring(0, j) + BALLS[RND.nextInt(BALLS.length)] + tree.substring(j+1);
i++;
}
}
// build trunk
tree += repeat(' ', (w - 4) / 2) + repeat('*', 4) + "\n" + repeat(' ', (w - 4) / 2) + repeat('*', 4);
// output
System.out.println(tree);
}
// this function builds a String by repeating a given character a couple of times
private static String repeat(char c, int l){
String s = "";
for(int i=0;i<l;i++)
s += c;
return s;
}
}
The output should look something like this:
⏣
***
*o***
**⌾*o**
*****⛣**⛣
*****⌾****⏣
**◍*◍********
****
****
The keyword is think.
var x = 8;
for (let i = 0; i < x; i++) {
for (let j=x-1; j>i; j--) {
document.write("&nbsp&nbsp");
}
for (let k=0; k<=(i*2); k++) {
document.write("^");
}
document.write("<br>");
}
for (let i=0; i<2; i++) {
for (let j=0; j<(x*2)-3; j++) {
document.write("&nbsp");
}
document.write("^<br>");
}
Constraints: Only looks good starting from x = 5.
Original code by me
The answers above heavily rely on nested loops, thought I post another approach with "modern" JS (of course still using a single loop with the map function given to Array.from()):
function xmas(height) {
// add 1 more level for the trunk, e.g. height+1
return Array.from({length: height+1}, (v, i) => {
return i === height
// that's for the trunk of the tree
? '*'.padStart(Math.round((2 * i)/2), ' ')
// the actual tree "levels"
: '*'.repeat(2 * i + 1).padStart(2 * i + height-i, ' ');
}).join('\n');
}
document.write(`<pre>${xmas(10)}</pre>`);
maybe the attempt to make it work with .padStart() is not optimal because the math gets a bit ugly, but anyways, just for fun =)...
Here's a solution with a simple for loop without any nested loop.
let row = ""
let l = 9
for (let i = 0; i < l; i++) {
row += " ".repeat(l - i) + "*" + "*".repeat(i * 2) + `\n`;
}
console.log(row);
Simple christmas tree function:
function christmasTree(x) {
if(x < 3) {
return "";
}
let tree = "";
for(let i = 1; i <= x; i++) {
for(let j = 1; j <= x + x - 1; j++) {
if(j <= x - i || j >= x + i) {
tree += " ";
} else {
tree += "*";
}
}
tree += "\n";
}
return tree;
}
Incase you are looking for how to do this in a function for javascript or typescript
Use 3 for loops,
1 - Number of rows
2 - Number of spaces
3 - Number of characters
function christmas(n) {
let tree = '';
for (let i = 1; i <= n; i++) {
for (let j=0; j <= n-i; j++) {
tree += ' ';
}
for (k = 0; k< (i*2)-1; k++) {
tree += '*';
}
tree += '\n';
}
return tree;
}
console.log(christmas(3));
<pre>
<script>
//Reads number of rows to be printed
var n = 8;
for(i=1; i<=n; i++)
{
//Prints trailing spaces
for(j=i; j<n; j++)
{
document.write(" ");
}
//Prints the pyramid pattern
for(j=1; j<=(2*i-1); j++)
{
document.write("*");
}
document.write("<br>");
}
</script>
</pre>

Exercise with a loop in javascript

I need for an university exercise to display onscreen with a document.write the tree below using a kind of loop:
I used at the beginning a for loop but i printed only the first row... someone can help me?
This is what I tried:
var numbers = [0, 1, 2, 3, 4]
for (var i = 0; i <= numbers.length; i++) {
if (numbers [i] == 0) {
document.write(" * </br>");
}
if (numbers [i] == 1) {
document.write(" *** </br>");
}
if (numbers [i] == 2) {
document.write(" ****** </br>");
}
if (numbers [i] == 3) {
document.write(" ******* </br>"); }
if (numbers [i] == 4) {
document.write("********* </br>");
}
return
}
Thank You!
I'm going to give you a "golfed-ish" (goldfish? should this be a thing?) version of the code. In other words, the smallest, most obscure code I can think of to accomplish the task. You should not use this, because your teacher will undoubtedly ask you what it means and you won't know, but I'm bored XD
var size = 5;
document.write("<center>"+Array.apply(0,new Array(size)).map(function(_,i) {return new Array((i+1)*2).join(" * ");}).join("<br>")+"</center>");
Demo
As I said, don't use this :p
Here is my code for you ...
<html>
<head>
<script type="text/javascript" language="javascript">
document.write("<center>"); //write a center tag to make sure the pyramid displays correctly(try it without this step to see what happens)
for(var i = 0; i <= 10; i++) //a loop, this counts from 0 to 10 (how many rows of stars)
{
for(var x = 0; x <= i; x++)// a loop, counting from 0 to whatever value i is currently on
{
document.write("*");//write a * character
}
document.write("<br/>"); //write a br tag, meaning new line, after every star in the row has been created
}
document.write("</center>"); //close the center tag, opened at the beginning
</script>
</head>
<body>
</body>
</html>
Adds spaces and fully extendable
function pyramid(lines, char) {
var start = 2,html = '<pre>';
for (var i=lines; i--;) {
html += new Array(Math.floor(i+1)).join(' ') + new Array((start=start+2)-2).join(char) + '<br />';
}
return html + '</pre>';
}
document.write( pyramid(5, '*') );
FIDDLE
function pyramidStar(n) {
var str = "";
for(var i=1; i<=n; i++) {
for(var j=1; j<=n-i; j++) {
str += " ";
}
for(var k=n-i+1; k<n+i; k++) {
str += "* ";
}
for(var m=n+i; m<=2*n-1; m++) {
str += " ";
}
str += "\n";
}
return str;
}
document.getElementById("result").innerHTML = pyramidStar(9);
<pre id="result"></pre>
Another way of printing pyramid of stars.
<pre><script>
for (var i = 0; i < 5; i++) {
for (var c = 0; c < 9; c++) {
if (Math.abs(4 - c) <= i)
document.write("*");
else
document.write(" ");
}
document.write("<br />");
}
</script></pre>
It is a simple version with document.write(). The only complicated thing is Math.abs which gives the distance from the middle.
PS: watch out for magic numbers
function star(n) {
for (var i = 1; i <= n; i++) {
for (var j = i; j < n; j++) {
document.write("-");
}
for (var k = 1; k <= (2 * i) - 1; k++) {
document.write("*");
}
document.write("<br/>");
}
}
//function calling
star(9);

Categories

Resources