Variable's value changes for no reason - javascript

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.

Related

Print a list of number using While loop and Do While loop

I am trying to implement the while and do while loop without using an actual array to print an list of number. Here is my code and the output I want.
My code
console.log("While Loop")
let j = 0;
while(j < 5){
j += 1;
console.log (j);
}
console.log("Do While Loop")
var i = 0; //set varible i = 0
do {
i += 1; //return i + 1 to i
console.log (i);
}
while (i < 5); //where i suppose to less than 5
Actual Output I want:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
There is two things here:
You need an inner loop to create the countdown of numbers.
If you are only using JavaScript, you need to form a string with your output and then use console.log() to print. This is because console.log() will append a newline.
The example below will print the first half of the triangle.
console.log("While Loop")
let j = 1;
while (j <= 5) {
let k = 1;
let str = "";
while (k <= j) {
str += k + " ";
k++;
}
j += 1;
console.log(str);
}
If you are using Node.js you can use process.stdout.write to print to the same line and then explicitly write the newline character when needed.
console.log("While Loop")
let j = 1;
while (j <= 5) {
let k = 1;
while (k <= j) {
process.stdout.write(k + " ");
k++;
}
j += 1;
process.stdout.write("\n");
}

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

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>

Why my code to find prime number from 2 to a given number in Javascript not working properly

I'm learning JavaScript at the moment and have an exercise to solve. The exercise is given bellow:
Output prime numbers
An integer number greater than 1 is called a prime. if it cannot be divided without a
remainder by anything except 1 and itself.
In other words, n > 1 is a prime if it can’t be evenly divided by anything except 1 and n .
For example, 5 is a prime, because it cannot be divided without a remainder by 2 , 3 and 4 .
Write the code which outputs prime numbers in the interval from 2 to n .
For n = 10 the result will be 2,3,5,7 .
P.S. The code should work for any n , not be hard-tuned for any fixed value.
Now i try to solve it this way.
let n = 20;
outer:
for (let i = 2; i < n; i++) {
for (let j = 1; j < n; j++) {
while (j>1 && j<i) {
if (i%j == 0 ) {
continue outer
}
}
}
console.log(i);
}
but it show wrong output
now i also can solve it in this way
let n = 20;
let result = 0;
outer:
for (let i = 2; i < n; i++) {
for (let j = 2; j < i; j++) {
if (i%j == 0) {
continue outer
}
}
console.log(i)
}
Now I ask for your help to know that exactly in where I did mistake in 1st Salutation .
The problem is that if if (i%j == 0 ) is false you remain in the while without changing the variables so you are infinite stuck there.
You could add another label for the inner for and either go to the one or the other
let n = 20;
outer: for (let i = 2; i < n; i++) {
inner: for (let j = 1; j < n; j++) {
while (j>1 && j<i) {
if (i%j == 0 ) {
continue outer;
} else {
continue inner;
}
}
}
console.log(i);
}

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.

I cannot understand why my condition is failing and unable break an infinite for loop in javascript

I am learning JavaScript and tried editing and running following code in about:blank on Chrome and the output I get is an infinite loop-
// Draw as many smileys as you want!
var drawSmileys = function (howManyTimes) {
for (var i = 0; i < howManyTimes < 20; i++) {
console.log(i + " ;p");
}
};
drawSmileys(15);
Can some one tell me why the condition is not failing?
Your looping condition syntax is not producing the logic that you want it to.
It appears that you want to continue looping as long as your loop counter (i) is both less than howManyTimes and 20. Because of that, you'll need to use the short-circuited AND operator (&&) because that's 2 conditions that both need to be true for the loop to continue.
// Draw as many smileys as you want!
var drawSmileys = function (howManyTimes) {
for (var i = 0; i < howManyTimes && howManyTimes < 20; i++) {
console.log(i + " ;p");
}
};
drawSmileys(20); // Doesn't run
drawSmileys(19); // Does run
This could be another approach
// Draw as many smileys as you want!
var drawSmileys = function (howManyTimes) {
howManyTimes = howManyTimes > 20 ? 20 : howManyTimes;
for (var i = 0; i < howManyTimes; i++) {
console.log(i + " ;p");
}
};
drawSmileys(21);
Your loop is infinite because it's always true:
console.log(0 < 15 < 20)//true
console.log(1 < 15 < 20)//true
console.log(5 < 15 < 20)//true
console.log(15 < 15 < 20)//true
The evaluation is (0<15) < 1 is (true) < 1 and this is false because (0<15) == 1 is true then 1<1 is false
console.log((0 < 15))//true
console.log((0 < 15) < 20)//true
console.log((0 < 15)==1)//true
console.log((0 < 15)<1)//false
Then, the only way to obtain a false with this x<y<z is if z == 1 and x<y == true that is (true)<1
If you want to put two limits you could do:
var drawSmileys = function (howManyTimes) {
for (var i = 0; i < howManyTimes && i < 20; i++) {
console.log(i + " ;p");
}
};
console.log(drawSmileys(8))//7 smiles
console.log("----")
console.log(drawSmileys(200))//19 smiles

Categories

Resources