Code to compute collatz conjecture has no output - javascript

So, I saw a video by Veritasium -> (https://youtu.be/094y1Z2wpJg)
And I wanted to try to translate it into code.
when I run it, nothing gets logged and no errors appear at all
it might be a very simple fix due to the fact that I am a VERY new programmer so yea.
if you could help that would be great! :)
var i = document.getElementById("solvebtn");
function solve() {
while(i > 1) {
//even
if(i % 2 == 0) {
(i / 2)
console.log(i)
}
//odd
else {
(i * 3 + 1)
console.log(i)
}
}
}
/* RULES */
//if odd i * 3 + 1
//if even i / 2
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3X + 1</title>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" placeholder="Number"></input>
<button id="solvebtn" onclick="solve()">Solve</button>
</body>
</html>

You where using the wrong value, the button doesnt contain the input value, you need to get that from the input field.
var i = document.getElementById("solvebtn");
function solve() {
let value = document.getElementById("val").value;
while (value > 1) {
//even
if (value % 2 == 0) {
value = value / 2
console.log(value)
}
//odd
else {
value = value * 3 + 1
console.log(value)
}
}
}
/* RULES */
//if odd i * 3 + 1
//if even i / 2
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3X + 1</title>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" id="val" placeholder="Number"></input>
<button id="solvebtn" onclick="solve()">Solve</button>
</body>
</html>

you should change the input type to number in your HTML code
you can get the input number using element.value
const element = document.getElementById("input");
function solve() {
//this is wat you shold add
let i = element.value;
console.log(i);
while(i > 1) {
//even
console.log("ddd")
if((i % 2) === 0) {
(i /= 2)
console.log(i)
}
//odd
else {
(i =i*3 + 1)
console.log(i)
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="#">
<title>Document</title>
<script defer src="app.js"></script>
</head>
<body>
<!--change the type to number-->
<input id="input" type="number" placeholder="Number"></input>
<button id="solvebtn" onclick="solve()">Solve</button>
</body>
</body>
</html>

Related

Having trouble randomizing choice using (Math.floor(Math.random() * 3)). When applied to variable "computerChoice", same number always results

When the button on-page is clicked it always results in the same output, which is 1 or "Wealth will find you". I have been tinkering and tweaking for a long while and have been unable to find a solution. Any tips or suggestions would be appreciated, even just a place to start troubleshooting!
let computerChoice = (Math.floor(Math.random() * 3));
function clickEvent() {
if (computerChoice === 0) {
alert("You will perish soon.");
} else if (computerChoice === 1) {
alert("Wealth will find you.");
} else if (computerChoice === 2) {
alert("Love is in the air.");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="index.js"></script>
<title>8Ball</title>
</head>
<body>
<h1 class=header>Cower in Fear, the Magic 8 Ball is here</h1>
<div class="container-one">
<img class="hero-image" src="Images/8ball.jpeg" alt="8ball">
</div>
<div class="container-two">
<!--<button id="action">Swirl the 8ball</button>-->
<input id="action" type="button" value="Swirl" onClick="clickEvent();" />
<h3 class="button-text">Hit the swirl button to discover what the future holds!</h3>
</div>
</body>
</html>
This should work as expected. I have place the computerChoice variable inside the clickEvent function to make it generate the random numbers as expected.
const
swirl_btn = document.querySelector('#action')
function clickEvent() {
let
computerChoice = (Math.floor(Math.random() * 3));
if (computerChoice === 0) {
alert("You will perish soon.");
} else if (computerChoice === 1) {
alert("Wealth will find you.");
} else if (computerChoice === 2) {
alert("Love is in the air.");
}
}
swirl_btn.addEventListener('click', function() {
clickEvent()
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="index.js"></script>
<title>8Ball</title>
</head>
<body>
<h1 class=header>Cower in Fear, the Magic 8 Ball is here</h1>
<div class="container-one">
<img class="hero-image" src="Images/8ball.jpeg" alt="8ball">
</div>
<div class="container-two">
<!--<button id="action">Swirl the 8ball</button>-->
<input id="action" type="button" value="Swirl" />
<h3 class="button-text">Hit the swirl button to discover what the future holds!</h3>
</div>
</body>
</html>

Uncaught SyntaxError: Unexpected token 'export'

I tried to export variables to another module, but error occured.
Uncaught SyntaxError: Unexpected token 'export'.
File structure:
./css:
select.css style.css
./html:
index.html make.html select.html
./javascript:
make.js script.js select.js
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Search Maker</title>
</head>
<body>
<div class="title-h1">
<h1>
Simple Word Search maker
</h1>
</div>
<div class="start">
<button id="start-button">Start ➝</button>
</div>
<script src="/javascript/script.js"></script>
<link rel="stylesheet" href="/css/style.css">
</body>
</html>
script.js
const startButton = document.querySelector("#start-button");
const activeclass = "active";
function handlestartBtnMouseEnter() {
startButton.classList.add(activeclass);
}
function handlestartBtnMouseLeave() {
startButton.classList.remove(activeclass);
}
function handleStartBtnClick() {
window.location.href = "/html/select.html";
}
startButton.addEventListener("mouseenter", handlestartBtnMouseEnter);
startButton.addEventListener("mouseleave", handlestartBtnMouseLeave);
startButton.addEventListener("click", handleStartBtnClick);
select.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Making Basic template</title>
</head>
<body>
<h1>
Basic template:
</h1>
<div class="settings">
width: <input type="text" id="width">
<br>
height: <input type="text" id="height">
</div>
<button id= "make-button">Make</button>
<script type="module" src="/javascript/select.js"></script>
</body>
</html>
select.js:
let width_textbox = document.getElementById("width");
let height_textbox = document.getElementById("height");
let width = null;
let height = null;
const makebutton = document.querySelector("#make-button");
function handleClickMakeBtn() {
width = parseInt(width_textbox.value);
height = parseInt(height_textbox.value);
if (width > 30 || height > 30) {
alert("Width and height cannot longer than 30!");
width_textbox.value = "";
height_textbox.value = "";
} else if (width < 5 || height < 5) {
alert("Width and height cannot shorter than 5!");
width_textbox.value = "";
height_textbox.value = "";
} else if (isNaN(width) || isNaN(height)) {
alert("Width and height must be number!");
width_textbox.value = "";
height_textbox.value = "";
} else if (width == null || height == null) {
alert("You have to enter width and height!");
}
else {
window.location.href = "/html/make.html";
}
export { width, height }
}
makebutton.addEventListener("click", handleClickMakeBtn);
make.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Make word search</title>
</head>
<body>
<script type="module" src="/javascript/make.js"></script>
</body>
</html>
make.js:
import * as settings from "./select.js";
for (i=0; i <= width; i ++) {
document.createElement('input') * settings.width;
console.log(settings.height);
}
I'm very new to web. Sorry if it's just my mistake.
the issue come from function handleClickMakeBtn
you can't export object in function like that
if you want to return value you have to use the keyword return
but like width and height are global variable when you modify it in function it's modify the global variable
You can only export stuff only at the top-level of the file (ie not inside a function).
However you can use window object to access the variable from anywhere.
like this
function handleClickMakeBtn() {
width = parseInt(width_textbox.value);
height = parseInt(height_textbox.value);
window.settings = { width, height }
}
now you can access the object from anywhere.
like window.settings. I don't recommend this way instead you can create a global object inside the module and export that at top level.

SetInterval Not Working Each time a Button Is Clicked

I have an H1 value that should decrease each time a button is clicked. The value of H1 is 10, when clicked the first time, it reduces to 9 after two seconds and when clicked again, it reduces to 8 after 2 seconds also. And it continues like that. My code below is not working as expected. It starts reducing only after the first clicks until it gets to zero. Please help me check my code below and tell me what I'm doing wrong.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>10</h1>
<button onclick='execute()'>Start Timer</button>
</body>
<script>
let count = document.getElementsByTagName("h1")[0].innerHTML;
let btn = document.getElementsByTagName("button")[0]
function execute(){
window.setInterval(function()
{
count--;
h1 = document.getElementsByTagName("h1")[0].innerHTML = count;
if(count <= 0){
document.getElementsByTagName("h1")[0].innerHTML = 0
btn.disabled = true;
}
}, 1000);
}
</script>
</html>
You have to use setTimeout instead, because with setInterval it runs on a loop. If you want 2 seconds you have to use 2000 ms also.
Here it goes what you want:
let count = document.getElementsByTagName("h1")[0].innerHTML;
let btn = document.getElementsByTagName("button")[0]
function execute(){
window.setTimeout(function() {
count--;
h1 = document.getElementsByTagName("h1")[0].innerHTML = count;
if(count <= 0){
document.getElementsByTagName("h1")[0].innerHTML = 0
btn.disabled = true;
}
}, 2000);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>10</h1>
<button onclick='execute()'>Start Timer</button>
</body>
</html>

how to append on to this array with javascript

when you say new it should add the item you enter to the todo list and when I call list it should give me the list but the quit works and it quits the program if you have any advice can you please tell me how to fix this problem thank you in advance
window.setTimeout(function() {
while(true){
var rep = prompt("what ya wanna do?");
var list = [];
if(rep === "new"){
var newItem = prompt("whacha wanna add?")
list.push(newItem);
}
if(rep === "list"){
alert(list)
}
if(rep === "quit"){
break;
}
}
}, 500);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="ps3.js"></script>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add A Todo</li>
<li>"list" - Veiw All Todos</li>
<li>"quit" - Quit Applet</li>
</ul>
</body>
</html>
Declare variable var list = []; outside the while loop
Working example
window.setTimeout(function() {
var list = [];
while(true){
var rep = prompt("what ya wanna do?");
if(rep === "new"){
var newItem = prompt("whacha wanna add?")
list.push(newItem);
}
if(rep === "list"){
alert(list)
}
if(rep === "quit"){
break;
}
}
}, 500);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="ps3.js"></script>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add A Todo</li>
<li>"list" - Veiw All Todos</li>
<li>"quit" - Quit Applet</li>
</ul>
</body>
</html>
Declare list to be out of while loop
var list = [];
window.setTimeout(function() {
while(true){
var rep = prompt("what ya wanna do?");
if(rep === "new"){
var newItem = prompt("whacha wanna add?")
list.push(newItem);
}
if(rep === "list"){
alert(list)
}
if(rep === "quit"){
break;
}
}
}, 500);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="ps3.js"></script>
</head>
<body>
<h1>Todo List</h1>
<ul>
<li>"new" - Add A Todo</li>
<li>"list" - Veiw All Todos</li>
<li>"quit" - Quit Applet</li>
</ul>
</body>
</html>

Javascript execute a function after some time elapse

I am making a javascript based life game, and I am currently working on a salary system so, for example, every 10 seconds the balance goes up by 1. I've been looking for a while how to do it but never found anything. Here are my codes:
var balance = 100;
function balanceSys(){
let newbalance = balance + 100;
balance = newbalance;
document.getElementById("balance").innerHTML = (balance);
}
function salary(){
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Life Game</title>
<link rel="stylesheet" href="main.css">
<link href="https://fonts.googleapis.com/css?family=Mukta+Malar" rel="stylesheet">
</head>
<script src="main.js"></script>
<body>
<center><h1 class="title">Life Game</h1></center>
<table>
<tr>
<td class="mainTd"><h1 id="balance">0</h1></td>
<td class="mainTd"><h1 id="state">Begger</h1></td>
</tr>
</table>
<button onclick="balanceSys()">Click Me</button>
</body>
</html>
Use setInterval(). It will execute a function every X milliseconds (The second parameter).
You can also take in a parameter for amt to adjust by, and add varying amounts (In this case, I specified 1 in the original interval function, and 100 by default if not specified.
var balance = 0;
setInterval(() => balanceSys(1), 1000);
function balanceSys(amt = 100){
let newbalance = balance + amt;
balance = newbalance;
document.getElementById("balance").innerHTML = (balance);
}
function salary(){
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Life Game</title>
<link rel="stylesheet" href="main.css">
<link href="https://fonts.googleapis.com/css?family=Mukta+Malar" rel="stylesheet">
</head>
<script src="main.js"></script>
<body>
<center><h1 class="title">Life Game</h1></center>
<table>
<tr>
<td class="mainTd"><h1 id="balance">0</h1></td>
<td class="mainTd"><h1 id="state">Begger</h1></td>
</tr>
</table>
<button onclick="balanceSys()">Click Me</button>
</body>
</html>
I agree with FrankerZ's method, but you don't want to run getElementById every second. Here is a better solution. DOM manipulation is very slow, so try to minimize the impact in performance as much as possible.
function balanceSys(){
let element = document.getElementById("balance");
setInterval(() => {
let newbalance = balance + 1;
balance = newbalance;
element.innerHTML = (balance);
}, 10000);
}

Categories

Resources