Linear Interpolation - javascript

Here is a program that asks the user for a number (variable r) to find the positive root of, and then asks for a starting interval [a,b]. This is done in some HTML code. The javascript below it has the code for linear interpolation inside a while loop.
function everything() {
r= document.getElementById('ri').value*1;
a= document.getElementById('ai').value*1;
b= document.getElementById('bi').value*1;
bisect(function(x){return x*x-r;},a,b);
}
function bisect(f,a,b) {
var avg,fa,fb;
avg = NaN;
while (Math.abs(a-b)>1e-10) {
fa=f(a);
fb=f(b);
if(fa*fb<0) {
grad=(fb-fa)/(b-a);
avg=a-(fa/grad);
favg=f(avg);
} else {
alert('There has been an error. Redifine the interval A to B');
break;
}
if (fa*favg<0) {
b=avg;
} else {
a=avg;
}
}
alert(avg);
}
The problem with this code is it returns the error text, and the final value for avg at the end. This is a problem.

Chris said
while (Math.abs(a - b) > 1e-5) {
fa = f(a);
fb = f(b);
if (Math.abs(fa) < 1e-10) {
avg = a;
break;
}
if (Math.abs(fb) < 1e-10) {
avg = b;
break;
}
if (fa * fb < 0) {
grad = (fb - fa) / (b - a);
avg = a - fa / grad;
favg = f(avg);
//alert([a,fa,b,fb])
} else {
alert("There has been an error. Redifine the interval A to B");
break;
}
if (fa * favg < 0) {
b = avg;
} else {
a = avg;
}
}
alert(avg);

Related

(Codility binary gap error) Problem : Cant convert octal code into expected array

Its works well when converting to string except binary with prefix 0.
My code:
function dec2bin(dec) {
return dec.toString(2);
}
function getRndInteger(min, max) {
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
const min = 1;
const max = 2147483647;
const nilai = dec2bin(getRndInteger(min, max));
function solution(N) {
**const nilaiArr = Array.from(String(N), Number);**
let temporer = 0;
let save = \[\];
for (let i = 0; i \< nilaiArr.length - 1; i++) {
if (nilaiArr\[i\] == 1 && nilaiArr\[i + 1\] == 0) {
for (let j = i + 1; nilaiArr\[j\] == 0; j++) {
temporer++;
if (nilaiArr\[j + 1\] == 1) {
save.push(temporer);
temporer = 0;
} else if (nilaiArr\[j + 1\] == undefined) {
break;
}
}
} else {
continue;
}
}
if (save.length === 0) {
console.log(0);
} else {
save.sort();
save.reverse();
console.log(save\[0\]);
}
}
solution(nilai);
Problem sample : 010000010001 became 1073745921.
Expected output same as origin binary number. I cant find the answer as long as I scroll in this forum lol. I

How can I get setInterval() to increase by 1 instead of 12?

My game has two players that get random numbers, and the person who has the bigger number gets 1 "win". My while loop is for the "auto-roll" button, and instead of clicking "roll dice" each time, auto-roll will do it for you until one player has wins == game limit # (bestof.value). No matter where I put my setInterval it increases by a bunch at a time. If bestof.value = 10 then each interval displays at least 10 wins for one player at a time.
checkBox.checked = input checkmark that enables auto-roll feature. So this setInterval will only be active while the auto-roll loop is active.
Anyways, what am I doing wrong?
button.addEventListener("click", myFunction);
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
screenID.innerHTML = random;
screenIDD.innerHTML = random2;
if (random > random2){
winNumber.innerHTML = ++a;
} else if(random2 > random){
winNumba1.innerHTML = ++b;
} else {
console.log("Draw");
}
if (a > b){
winNumber.style.color = 'white';
winNumba1.style.color = 'black';
} else if(b > a){
winNumba1.style.color = 'white';
winNumber.style.color = 'black';
} else {
winNumber.style.color = 'black';
winNumba1.style.color = 'black';
}
if (checkBox.checked){
setInterval(myFunction, 2000)
while(a < bestof.value && b < bestof.value){
myFunction();
}};
if (winNumba1.innerHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumba1 wins!');
} else if (winNumber.innterHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumber wins!');
} else {}
};
I wrote a simplified js only version of your game here since I don't have html at hand, but I am sure you can adjust it to your environment.
Main difference: I check if someone won and use return to stop the function
If no one won and autoplay is activated I autoplay after 500ms again.
let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
console.log("New Round " + random + " vs " + random2)
if (random > random2) {
playerA++
} else if (random2 > random) {
playerB++
} else {
console.log("Draw");
}
if (playerA > playerB) {
console.log("a is winning")
} else if (playerB > playerA) {
console.log("b is winning")
} else {
console.log("There has been a draw")
}
if (playerA == bestOf) {
console.log('A won');
return
} else if (playerB == bestOf) {
console.log('B won');
return
}
if (autoPlay) {
setTimeout(myFunction, 500)
};
};
myFunction()

How do I define methods in Javascript objects?

I'm new to Javascript, I'm working on a small game to get a better handle of it. I'm trying to define a character object with methods, but for some reason I'm getting weird errors from my IDE, "Label 'updateHealth' on function statement, Missing name in function declaration". I'm just trying to figure out what I'm doing wrong. In my code, display is how the character's health display's on the screen.
function Character(display) {
this.health = 100;
this.display = display;
// updates the health on the screen
updateHealth: function() {
if(health == 100) {
this.display.innerText = 'HP: ' + health;
}
else if(health > 10 && health < 100) {
this.display.innerText = 'HP: 0' + health;
}
else if(health < 10 && health > 0) {
this.display.innerText = 'HP: 00' + health;
}
else {
this.display.innerText = 'HP: 000';
}
}
// returns true if character has died
checkForDeath: function() {
if(health <= 0) return true;
else return false;
}
// function used when damage is inflicted on
// a character object
takeDamange: function(damage) {
this.health -= damage;
}
// handles the four possible moves
// opponent is null because if player heals
// then it does not make sense for there to be
// an opponent
makeMove: function(move, opponent=null) {
switch(move) {
case 'PUNCH':
opponent.takeDamage(parseInt(Math.random() * 100) % 10);
opponent.updateHealth();
break;
case 'HEAL':
this.health += 20;
break;
case 'KICK':
opponent.takeDamage(parseInt(Math.random() * 100) % 20);
opponent.updateHealth();
break;
case 'EXTERMINATE':
opponent.takeDamage(opponent.health);
opponent.updateHealth();
break;
}
return opponent.checkForDeath();
}
}
Object's can be instantiated via a constructor function such as your Character() function however, you'll need to ensure object methods (such as updateHealth(), etc) are "attached" to the instance of the character object.
One way to achieve that is via the this keyword:
/* Attach the checkForDeath() function as a method of "this" Character instance */
this.checkForDeath = function() {
/* Accessing "this" corresponds to the instance of the character object */
if (this.health <= 0) return true;
else return false;
}
By making these changes, checkForDeath() is now defined as a member function of the corresponding character instance. You'll need to ensure that you access fields on the instance via this, as shown on this line if(this.health <= 0) { ... }
You'll also need to ensure that you instantiate instances of Character via the new operator like this:
const characterInstance = new Character( someElement );
Here is a revised version of your code demonstrating this approach:
function Character(display) {
this.health = 100;
this.display = display;
this.updateHealth = function() {
const health = this.health; /* Add this */
if (this.health == 100) {
this.display.innerText = 'HP: ' + health;
} else if (health > 10 && health < 100) {
this.display.innerText = 'HP: 0' + health;
} else if (health < 10 && health > 0) {
this.display.innerText = 'HP: 00' + health;
} else {
this.display.innerText = 'HP: 000';
}
}
this.checkForDeath = function() {
if (this.health <= 0) return true;
else return false;
}
this.takeDamange = function(damage) {
this.health -= damage;
}
this.makeMove = function(move, opponent = null) {
switch (move) {
case 'PUNCH':
opponent.takeDamage(parseInt(Math.random() * 100) % 10);
opponent.updateHealth();
break;
case 'HEAL':
this.health += 20;
break;
case 'KICK':
opponent.takeDamage(parseInt(Math.random() * 100) % 20);
opponent.updateHealth();
break;
case 'EXTERMINATE':
opponent.takeDamage(opponent.health);
opponent.updateHealth();
break;
}
return opponent.checkForDeath();
}
}
const player = new Character( document.querySelector('p') );
player.takeDamange();
player.updateHealth();
<p></p>
change : to =, and assign it to a local property, such as
this.updateHealth = function() {
...
}
I'd recommend using the class syntax.
class Character {
constructor(display) {
this.health = 100;
this.display = display;
}
// updates the health on the screen
updateHealth() {
this.display.innerText = `HP: ${Math.max(health, 0).toString().padStart(3, '0')}`;
}
// returns true if character has died
checkForDeath() {
return health <= 0;
}
// function used when damage is inflicted on
// a character object
takeDamange(damage) {
this.health -= damage;
}
// handles the four possible moves
// opponent is null because if player heals
// then it does not make sense for there to be
// an opponent
makeMove(move, opponent = null) {
switch (move) {
case 'PUNCH':
opponent.takeDamage(parseInt(Math.random() * 100) % 10);
opponent.updateHealth();
break;
case 'HEAL':
this.health += 20;
break;
case 'KICK':
opponent.takeDamage(parseInt(Math.random() * 100) % 20);
opponent.updateHealth();
break;
case 'EXTERMINATE':
opponent.takeDamage(opponent.health);
opponent.updateHealth();
break;
}
return opponent.checkForDeath();
}
}
I also did some slight refactoring, which should make it easier to understand what is happening.

From this code of Javascript, what is the password and how did you get it?

function a(val) {
let a = 500
let loc = window[arguments[0]];
for(let i = 0, a = 800; i < 5; i++) {
debugger;
for(a; a < 1000; a++) {
debugger;
}
}
console.log(a);
console.log((a / 100) - 3);
let p = Object.getOwnPropertyNames(loc).sort();
let href = p[p.indexOf("hash") + ((a / 100) - 2)];
return loc[href]
}
function check() {
let p = prompt("What is the password?");
let c = btoa(a("location") +btoa(arguments.callee) + btoa(a("location").split('/').toString()))
if(p == c) {
console.log("Correct.")
}
}
From this Javascipt code, what would be the password.
For sure the password is from this line
let c = btoa(a("location") +btoa(arguments.callee) + btoa(a("location").split('/').toString()))
The «password» will depend on the location of the page where this script is run. Without knowing that, it is impossible to tell.
Regardless, let's run it and find out what the password is for this very page on StackOverflow:
function a(val) {
let a = 500
let loc = window[arguments[0]];
for (let i = 0, a = 800; i < 5; i++) {
//debugger;
for (a; a < 1000; a++) {
//debugger;
}
}
//console.log(a);
//console.log((a / 100) - 3);
let p = Object.getOwnPropertyNames(loc).sort();
let href = p[p.indexOf("hash") + ((a / 100) - 2)];
return loc[href]
}
function check() {
let p = "" //prompt("What is the password?");
let c = btoa(a("location") + btoa(arguments.callee) + btoa(a("location").split('/').toString()))
if (p == c) {
console.log("Correct.")
}
return c; /* Only thing added is this return statement */
}
console.log(check());

javascript array not defined

Working on a project for school and arrays are causing me a serious problem. They are returning the error:
Uncaught ReferenceError: oddNumbers is not defined.
I did exactly what every other question on this site asked and to no avail. You can see in the ScriptManager "class" (as I am used to Java and C#) the oddNumbers and evenNumbers can't be pushed into. Please tell me whats wrong.
var manager = new ScriptManager();
function enterNumber() {
var number = prompt("Enter a number");
if (manager.addNumber(number)) {
document.getElementById("even").innerHTML = manager.getEvenNumbers();
document.getElementById("odd").innerHTML = manager.getOddNumbers();
document.getElementById("sum").innerHTML = manager.sum;
document.getElementById("average").innerHTML = manager.average;
}
}
function ScriptManager() {
this.count = 0;
this.oddCount = 0;
this.evenCount = 0;
this.sum = 0;
this.average = 0;
this.oddNumbers = [];
this.evenNumbers = [];
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
evenNumbers.push(number);
evenCount++;
count++;
} else {
oddNumbers.push(number);
oddCount++;
count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
sum += oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
sum += evenNumbers[x];
}
average = sum / count;
return true;
};
this.getEvenNumbers = function() {
var stream = "";
var first = true;
for (var x = 0; x < evenCount; x++) {
if (!first) {
stream + ", ";
}
stream += String.valueOf(evenNumbers[x]);
if (first) {
first = false;
}
}
return stream;
}
this.getOddNumbers = function() {
return "bleh";
}
}
You need to use the this. prefix before all the object properties.
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
this.evenNumbers.push(number);
this.evenCount++;
this.count++;
} else {
this.oddNumbers.push(number);
this.oddCount++;
this.count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
this.sum += this.oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
this.sum += this.evenNumbers[x];
}
this.average = this.sum / this.count;
return true;
};
In javascript, you have to use this in front of member variables to access them. So:
oddNumbers.push(number);
needs to be:
this.oddNumbers.push(number);
And, similarly for all the other member variables.

Categories