(Ik Its a stupid question) with the "do - while" the code runs multiple times at the same time (i putted a console.log('while') at the beginning, so it print 'while' when the code is executed) but I want to run it one time at a time. Here's an example:
Code:
let x = 100
let y = 100
do {
console.log('while')
/*
here there's a piece of code that let the user choose what want he to do
*/
let random = Math.floor(//random number between 1 and 2)
if (random == 1) {
y = y - 50
} else {
x = x - 50
} while (y >= 0 && x >= 0 )
Obviously the console prints 'while' until the process ends.
I tried to use for (let i; i < 100; i++) and in the for i putted a if ( y <= 0 && x <= 0) but I can't start-over the loop (I dont know how to use continue).
The main problem with your code is the brackets - your formatting is incorrect:
let x = 100
let y = 100
do {
//...
if (random == 1) {
y = y - 50
} else {
x = x - 50
} while (y >= 0 && x >= 0 );
You don't close off your "do" loop - you just go right into the while after the else. In order for your code to work properly, you need to insert a bracket after the else:
let x = 100
let y = 100
do {
//...
if (random == 1) {
y = y - 50
} else {
x = x - 50
}
} while (y >= 0 && x >= 0 );
Related
I want to have a logic where if I enter an even number I want next 10 even numbers to be printed and If I enter an odd number, I want next 10 odd numbers to be printed. How should I rectify this logic inside a function. If someone can please help me rectifying the logic which was answered.
JS
function oddEven() {
var input = prompt("");
for (let x = 1; x <= 10; x++) {
console.log(input + x * 2);
}
}
oddEven()
This should work for any number
const input = 2
for (let x = 1; x <= 10; x += 1) {
console.log(input + x * 2)
}
i hope this help
function printTen(input){
let list = []
let number = input
while(list.length <= 10){
number++
if(input % 2 === 0 && number % 2 === 0){
console.log(number + " is even");
list.push(number)
}else if(input % 2 !== 0 && number % 2 !== 0) {
console.log(number + " is odd");
list.push(number)
}
}
}
printTen(9)
let inputval = 2;
for (let x = 1; x <= 10; x++) {
console.log(inputval + x * 2)
}
I want to write a program in JavaScript to print all the numbers from 1 to 20 except 5 and 10. When I use a for loop like this:
for (x = 1; x <= 20; x++) {
if (x == 5 || x == 10) {
continue;
}
document.write(x + ' ');
}
It works properly and prints 1 2 3 4 6 7 8 9 11 12 13 14 15 16 17 18 19 20.
However, when I try to use a while loop like this:
var x = 1;
while (x <= 20) {
if (x == 5 || x == 10) {
continue;
}
document.write(x + ' ');
x++;
}
It makes the webpage unresponsive and I get a prompt asking me to close it. What is the problem here?
The problem is the following, inside the for-loop the continue will jump back to the update expression x++ but in the while loop it will jump back to the running condition while(x <= 20)
Referencing the mdn docs.
In a while loop, it jumps back to the condition. In a for loop, it
jumps to the update expression.
Because you are not updating the counter inside your condition
while (x <= 20) {
if (x == 5 || x == 10) {
continue;
}
x will remain 5 and gets never updated because with the continue inside the while-loop it jumps back to the running condition. This will end up in an endless loop.
To solve it you can increment the counter before the continue statement inside the while-loop
while (x <= 20) {
if (x == 5 || x == 10) {
x++
continue;
// for (x = 1; x <= 20; x++) {
// if (x == 5 || x == 10) {
// continue;
// }
// document.write(x + ' ');
//}
var x = 1;
while (x <= 20) {
if (x == 5 || x == 10) {
x++
continue;
}
document.write(x + ' ');
x++;
}
In the first case the loop declaration for (x = 1; x <= 20; x++) handles incrementing x between iterations, so every time the loop body executes, you get a different value of x.
In the second case, x++ is only executed if x is neither 5 nor 10. So, when x reaches 5 it's the loop will keep executing with x = 5 forever, since nothing is changing it.
I built an extensive minesweeper game in JS and I'm trying to implement an effective way to restart the game on click but I'm coming up short. Right now I'm just making the entire page reload on click but that's not what I want to happen. The way I built the game, everything is placed on load, so I'm not sure how to approach this without refactoring all of my code. I tried creating a function that resets all global variables, removes all the divs I created before and then calls a function which I created to just wrap all my code and do it all over again. This approach removed the divs but did not place them again.
This is my primary function
function createBoard() {
const bombsArray = Array(bombAmount).fill('bomb')
const emptyArray = Array(width * height - bombAmount).fill('valid')
const gameArray = emptyArray.concat(bombsArray)
// --Fisher–Yates shuffle algorithm--
const getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i)
gameArray.forEach((elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]])
// --- create squares ---
for (let i = 0; i < width * height; i++) {
const square = document.createElement('div')
square.setAttribute('id', i)
square.classList.add(gameArray[i])
grid.appendChild(square)
squares.push(square)
square.addEventListener('click', function () {
click(square)
})
square.oncontextmenu = function (e) {
e.preventDefault()
addFlag(square)
}
}
//add numbers
for (let i = 0; i < squares.length; i++) {
let total = 0
const isLeftEdge = (i % width === 0)
const isRightEdge = (i % width === width - 1)
if (squares[i].classList.contains('valid')) {
//left
if (i > 0 && !isLeftEdge && squares[i - 1].classList.contains('bomb')) total++
//top right
if (i > 9 && !isRightEdge && squares[i + 1 - width].classList.contains('bomb')) total++
//top
if (i > 10 && squares[i - width].classList.contains('bomb')) total++
//top left
if (i > 11 && !isLeftEdge && squares[i - 1 - width].classList.contains('bomb')) total++
//right
if (i < 129 && !isRightEdge && squares[i + 1].classList.contains('bomb')) total++
//bottom left
if (i < 120 && !isLeftEdge && squares[i - 1 + width].classList.contains('bomb')) total++
//bottom right
if (i < 119 && !isRightEdge && squares[i + 1 + width].classList.contains('bomb')) total++
//bottom
if (i <= 119 && squares[i + width].classList.contains('bomb')) total++
squares[i].setAttribute('data', total)
}
}
}
createBoard()
Really I just want to be able to clear on click the divs this function creates and then make them again. When I try this:
function resetGame() {
width = 10
height = 13
bombAmount = 20
squares = []
isGameOver = false
flags = 0
grid.remove('div')
createBoard()
}
This effectively removes the grid squares created on load but it doesn't create them again. I want to be able to run that initial function again. How can I do that?
Here's a codepen
You are removing the .grid container, instead of
grid.remove("div");
Use the following statement to remove all content of the container
grid.innerHTML = "";
Pen
I don't understand how the == 0 works with the remainder part of the code, for example (4+4) % 2 == 0, wouldn't that come out as 4 yet this code gives it a true, false, true, false, etc.
var size = 8;
var board = "";
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
if ((x + y) % 2 == 0)
board += " ";
else
board += "#";
}
board += "\n";
}
console.log(board);
var size = 8;
var board = "";
for (var y = 0; y < size; y++) {
for (var x = 0; x < size; x++) {
if ((x + y) % 2 == 0)
board += " ";
else
board += "#";
}
board += "\n";
}
console.log(board);
Works as expected.
The modulus operator returns the remainder. You will create a checker board pattern with this. If you want to reverse it, use === 1. If you want it to be the same on each row, just use x%2 === 0 or x%2 === 1
(4 + 4) % 2
8 / 2 = 4
and remaining value is 0
operation will give us remaining value after division
10 % 17 = 10
When we using long division for above case,
1) Find number of 17s in 10 answer is 0
2) Then 10 - (0 * 17) = 10
% is the modulus operation. It will will return whatever is left after the number is divided by the operand. So (4+4)%2 is the same as 8%2. And as 2 goes into 8 exactly (with no reminder) it returns 0.
I think maybe you are misunderstanding how modulo works. This example should print out what each iterations modulus remainder is. If the left side of the equation divides with no remainder then you get a 0.
const size = 8;
let board = "";
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
console.log(x + ' plus ' + y + ' (' + (x+y) +') modulus 2 equals ' + (x + y) %2);
board += ((x + y) % 2 === 0) ? " " : "#";
}
board += "\n";
}
console.log(board);
Think of %(modulo) as the 'remainder' when there is a division'
Let me give you a couple of instances...
10 % 2 = 0; //2 will go into 10, five times a leave a remainder of 0
12 % 2 = 0; //2 will go into 12, six times and leave a remainder of 0
5%2 = 1;// 2 will go into 5, 2 times and leave a remainder of 1
6%3 = 0; // 3 will go into 6, 2 times and leave a remainder of 0
3%5 = 3; //5 cant go into 3, so the remainder is 3. That's the same
number
(4+4)%2 = 0 // 8%2 = 0 .....2 will go into 8, four times and leave a
remainder of 0
I am making a simple cost estimator. I want to make an else if switch that checks the imputed values and displays a certain string dependant on those values. The cost estimation is working but I cant get the Else If switch to function.
Here is my codepen: http://codepen.io/FredHair/pen/FgJAd
I have tried to have a go here:
function myContainer(){
var container;
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
if (z < 25 && x < 110 && y < 90 ){
container = "1";
}
else if (z < 25 && x < 110 && y < 180 ){
container = "2";
}
else if (z < 25 && x < 220 && y < 90 ){
container = "3";
}
else if (z < 50 && x < 110 && y < 90 ){
container = "4";
}
else if (z < 50 && x < 110 && y < 180 ){
container = "5";
}
else if (z < 50 && x < 220 && y < 90 ){
container = "6";
}
else if (z < 75 && x < 110 && y < 90 ){
container = "7";
}
else if (z < 75 && x < 110 && y < 180 ){
container = "8";
}
else if (z < 75 && x < 220 && y < 90 ){
container = "9";
}
else if (z < 100 && x < 110 && y < 90 ){
container = "10";
}
else if (z < 100 && x < 110 && y < 180 ){
container = "11";
}
else if (z < 100 && x < 220 && y < 90 ){
container = "12";
}
else{
container = "?"
}
document.getElementById("container").innerHTML = container;
}
This is obviously meant to display a value in the HTML h3 id= "container", but currently nothing happens.
Where am I going wrong? is there a much better way to set up this? Using JQuery perhaps? Any help will be greatly appreciated. Sorry for my basic coding.
Your myContainer function is never being called. If you were to add it to your other function after you display the results, you'd get the results you wanted. Such as:
...
//Display Result//
document.getElementById("result").innerHTML = " = £ " + result;
myContainer();
}
That said you could simplify both functions. For example, the switch statement doesn't really serve much of a purpose, since you can modify your markup to produce the results that you want by changing your values to 50 and 30 such as:
<select id="choice" >
<option value = "1">1</option>
<option value = "50">2</option>
<option value = "30">3</option>
</select>
Now in your calculator function, you can set the result with a ternary operator. You read it like an if statement, meaning (if the value is true) ? (do this) : (else do this).
function calculator(){
var x = Number(document.getElementById("x").value);
var y = Number(document.getElementById("y").value);
var z = Number(document.getElementById("z").value);
var choice = Number(document.getElementById("choice").value);
var result = (choice === 1) ? z * 3 : x * 3 + choice;
//Display Result//
document.getElementById("result").innerHTML = " = £ " + result;
myContainer(x,y,z); //pass the values of x, y, z as arguments
}
You could simplify your myContainer as well, by passing the values to it for x, y and z directly from the calculator function, then you don't need to go back to the DOM and retrieve those values again.
function myContainer(x, y, z){
var container;
//all your if-else here ..
document.getElementById("container").innerHTML = container;
}