Javascript basic calculations always get NaN - javascript

Hello i am doing a basic calculator for a game but I am facing a problem I just started to learn this programming language read all tutorials I found and now I am just making some code and getting some experience , so I write a calculation code that I was written in a php before in a php was working perfect but I was using different technique there , so in javascript I create a function which will be called ones the calculate button will be pressed and create an object to store all data of 5 players take a look :
function count(){
function ninjas (name,dmg,dmgrate,dmggrow,speed,fury) {
this.name = name;
this.dmg = dmg;
this.dmgrate = dmgrate;
this.dmggrow = dmggrow;
this.speed = speed;
this.fury = fury;
}
var name = [];
var dmg = [];
var dmgrate = [];
var dmggrow = [];
var speed = [];
var fury = [];
var ninja = [];
for(var i = 0; i <5; i++){
name[name.length] = document.getElementById("ninja" + (i +1)).value;
dmg[dmg.length] = document.getElementById("dmg" + (i +1)).value;
dmgrate[dmgrate.length] = document.getElementById("dmgrate" + (i +1)).value;
dmggrow[dmggrow.length] = document.getElementById("dmggrow" + (i +1)).value;
speed[speed.length] = document.getElementById("speed" + (i +1)).value;
fury[fury.length] = 50;
ninja[i] = new ninjas(name[i],dmg[i],dmgrate[i],dmggrow[i],speed[i],fury[i]);
}
ninja.sort(function(a, b){return b.speed - a.speed});
var totaldmg;
var damagerate;
var damagegrow;
var furydmg;
for(var a = 0; a < 6; a++){ // 6 fight
for(var b = 0; b < 5; b++){ // 5 ninjas
if(ninja[b].name == "Kabuto"){
if(ninja[b].fury == 100){
damagerate = ninja[b].dmg / 100 * ninja[b].dmgrate;
damagegrow = damagerate / 100 * ninja[b].dmggrow;
furydmg = damagegrow + (damagegrow / 100) * ((ninja[b].fury - 100) / 0.25);
totaldmg += furydmg;
for(var c = 0; c < 5; c++){ // add fury each ninja by 25
ninja[c].fury +=25;
}
ninja[b].fury -= 25;
ninja[b].fury +=100;
}else if(ninja[b].fury > 100){
damagerate = ninja[b].dmg / 100 * ninja[b].dmgrate;
damagegrow = damagerate / 100 * ninja[b].dmggrow;
totaldmg += damagegrow;
for(var c = 0; c < 5; c++){// add fury each ninja by 25
ninja[c].fury +=25;
}
ninja[b].fury -= 25;
ninja[b].fury +=100;
}else {
damagerate = ninja[b].dmg / 100 * ninja[b].dmgrate;
totaldmg += damagerate;
ninja[b].fury += 50;
}
} else {
if(ninja[b].fury == 100){
damagerate = ninja[b].dmg / 100 * ninja[b].dmgrate;
damagegrow = damagerate / 100 * ninja[b].dmggrow;
totaldmg += damagegrow;
ninja[b].fury = 0;
}else if(ninja[b].fury > 100){
damagerate = ninja[b].dmg / 100 * ninja[b].dmgrate;
damagegrow = damagerate / 100 * ninja[b].dmggrow;
furydmg = damagegrow + (damagegrow / 100) * ((ninja[b].fury - 100) / 0.25);
totaldmg += furydmg;
ninja[b].fury = 0;
}else {
damagerate = ninja[b].dmg / 100 * ninja[b].dmgrate;
totaldmg += damagerate;
ninja[b].fury += 50;
}
}
}
}
document.getElementById("result").innerHTML = totaldmg;
};
I used few loops to store all data in her places and then use short function to short everyone by speed attribute after each step I did a check if everything is alright but at the end somehow I still got result which is NaN could someone help me to solve this I have checked my code many times but could find where is mistake , maybe there is something I do not know about a javascript and missed

initialize your total variables to 0
this way totaldmg += value will not result in totaldmg = "undefined + value;
var totaldmg = 0;
var damagerate = 0;
var damagegrow = 0;
var furydmg = 0;
Also, when reading the values from the DOM, convert them to numerics as string literals will concatenate
for(var i = 0; i <5; i++){
name[i] = parseInt(document.getElementById("ninja" + (i +1)).value, 10);
dmg[i] = parseInt(document.getElementById("dmg" + (i +1)).value, 10);
dmgrate[i] = parseInt(document.getElementById("dmgrate" + (i +1)).value, 10);
dmggrow[i] = parseInt(document.getElementById("dmggrow" + (i +1)).value, 10);
speed[i] = parseInt(document.getElementById("speed" + (i +1)).value, 10);
fury[i] = 50;
ninja[i] = new ninjas(name[i],dmg[i],dmgrate[i],dmggrow[i],speed[i],fury[i]);
}

I don't know what you want to do and how the code is supposed to work, but from just looking at your code here is the first error I could identify:
name[name.length]
dmg[dmg.length]
dmgrate[dmgrate.length]
speed[speed.length]
//etc
This is wrong. The elements in an array start from 0 and end to array.length - 1. This means that name[name.length] doesn't exist.
Here are some links on how a javascript array works:
http://www.w3schools.com/js/js_arrays.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
I hope this helps you. I will continue to see your code and if I find any other errors I am going to add them to my answer
2) How is this supposed to work:
for(var i = 0; i <5; i++){
name[name.length] = document.getElementById("ninja" + (i +1)).value;
dmg[dmg.length] = document.getElementById("dmg" + (i +1)).value;
dmgrate[dmgrate.length] = document.getElementById("dmgrate" + (i +1)).value;
dmggrow[dmggrow.length] = document.getElementById("dmggrow" + (i +1)).value;
speed[speed.length] = document.getElementById("speed" + (i +1)).value;
fury[fury.length] = 50;
//...
}
If you are trying to add elements to an array in javascript, name[name.length] is not the way it can be done. At the links above you can see how to do it, using the array.push(arg); function.

Related

brute force polynomial evaluation algorithm javascript

what is required is a brute force algorithm, and not some other!
I'm trying to implement the brute force method for a polynomial in javascript, but an error occurs, the answer is different from the other method above (horner method) - this method is checked and it gives the correct answer
but here is the second brut force- method that gives an excellent result, which is not correct.
What is the error in my code?
input :
_x = 6 _n = 5 polyEval = [2,3,5,-6,2]
output Horner method:
3386 // good. correct answer
output Bruforce method:
1496 // bad. incorrect answer
class Programm {
constructor(x:number, n:number) {
this._x = 4;
this._n = 5;
this.polyEval = [2,3,5,-6,2] //this.RandomArray(this._n);
}
private _x:number;
private _n:number;
private polyEval:number[] = [];
//working method
private Horner(poly:number[], n:number, x:number){
let time = performance.now();
let result = poly[0];
for (let i = 1; i < n; i++){
result = result * x + poly[i];
}
time = performance.now() - time;
console.log("Method: Horner |" ,`Result: ${result}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
}
// method with an error that I can't find
private BruteForce(poly:number[], n:number, x:number){
let time = performance.now();
let p: number = 0;
for(let i = n - 1; i >= 0; i--){
let coefficient = 1;
for(let j = 1; j <= i; j++){
coefficient = coefficient * x;
}
p = p + poly[i] * coefficient;
}
time = performance.now() - time;
console.log("Method: Brute Force |" ,`Result: ${p}, array: ${this.polyEval} |` ,`time: ${time.toFixed(5)}`);
}
// generate random array
private RandomArray(n: number):number[]{
let result:number[] = new Array(n);
for (let i = 0; i < n; i++){
if(Math.round(Math.random() * 1) > 0){
result[i] = Math.floor(Math.random() * (10 - 1)) + 1;
}else{
result[i] = Math.floor(((Math.random() * (10 - 1)) + 1) * -1);
}
}
return result;
}
public Main() {
console.log(`n - array length: ${this._n} | x - coefficient: ${this._x}`);
this.Horner(this.polyEval, this._n, this._x);
this.BruteForce(this.polyEval, this._n, this._x);
}
}
const random_N:number = Math.floor(Math.random() * (5 - 1)) + 3;
const random_X:number = Math.floor(Math.random() * (5 - 1)) + 2;
const poly = new Programm(random_N, random_X);
poly.Main();
The Horner's scheme works like this:
// initially
result = poly[0] == p_0;
// iteration 1
result = result * x + poly[1] == p_0 * x + p_1
// iteration 2
result = result * x + poly[2] == (p_0 * x + p_1) * x + p_2
== p_0 * x^2 + p_1 * x + p_2
Thus, the polynomial coefficients in the array poly are in order of highest to lowest. Then to replicate that in the brute force solution, one needs to apply the formula as
result = sum(poly[i] * pow(x, n-1-i)) ==
result = sum(poly[n-1-i] * pow(x, i))

Javascript Loop with adding same value

I hope you guys can help me!
I'm trying the following:
1000 + 100 = 1100 * 2 = 2200;
2200 + 100 = 2300 * 2 = 4600;
4600 + 100 = 4700 * 2 = 9400;
9400 + 100 = 9500 * 2 = 19000;
...
But I'm getting the flowing result.
1000 + 100 = 1100 * 2 = 2200;
2200 * 2 = 4400
4400 * 2 = 8800
...
The values are inputed by the user, but I used static values for the example.
I have te following code:
var generate = function generate(rate){
var array = [];
s=0;
for (var i = 0; i < 10; i++){
s =+ 100;
array.push([
(parseInt(1000) + 100) * Math.pow(2, i),
]);
}
return array;
}
Sounds to me like you want a function that adds 100, doubles and then calls itself recursively a fixed number of times.
This function will run 10 times and output the final answer:
function add100andDouble(num, runTimes){
if(runTimes == 0) return num;
return add100andDouble( (num + 100 ) * 2, runTimes - 1 );
}
$(function(){
var number = parseFloat(prompt("Enter a number"));
alert( add100andDouble(number, 10) );
});
var generate = function generate(rate){
var array = [];
s=0;
for (var i = 0; i < 10; i++){
s = rate + (array[i-1] ? array[i-1] :1000);
array.push(s*2);
}
return array;
}
console.log(generate(100));
I suggest to use a function f(x) for calculating the new value. It makes the code more clearly arranged.
function f(x) {
return (x + 100) * 2;
}
var i = 0,
x = 1000,
array = [];
for (i = 0; i < 10; i++) {
array.push(x);
x = f(x);
}
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
Recursion has its merits on other solutions but I would go with plain old for loop for this situation.
Assuming rate is the starting number, and the return is a fixed 10 value series:
function generate(rate) {
var series = [];
for(var i = 0; i < 10; i++) {
series.push(rate = ((rate + 100) * 2));
};
return series;
}
It can be easily modified to send the series length if needed.

How to write multidimensional array in JS in a loop?

I have the following code:
var marketReturns = [1];
var marketReturnsVol = [1];
var marketVolatility = [1];
var yearlyReturns = [];
var yearlyReturns2 = [];
for (y = 0; y < 50000; y++) {
for (x = 1; x <= 251; x++) {
do {
var rand1 = Math.random();
var rand2 = Math.random();
var x1 = 2.0 * rand1 - 1.0;
var x2 = 2.0 * rand2 - 1.0;
var w = Math.pow(x1, 2) + Math.pow(x2, 2);
} while (w === 0 || w > 1);
multiplier = Math.sqrt((-2 * Math.log(w)) / w);
var volVol = 1 + (((x2 * multiplier) / 100) * 5.98); // real ^VIX is 5.98.
marketVolatility[x] = volVol * marketVolatility[x - 1];
var y1 = 1 + (((x1 * multiplier) / 100) * 1.07); // 1.07 is the daily vol of ^GSPC
var y12 = 1 + (((x1 * multiplier) / 100) * 1.07 * marketVolatility[x]) + 0.00038; // 1.07 is the daily vol of ^GSPC
marketReturns[x] = y1 * marketReturns[x - 1];
marketReturnsVol[x] = y12 * marketReturnsVol[x - 1];
}
yearlyReturns[y] = marketReturns[251];
yearlyReturns2[y] = marketReturnsVol[251];
}
yearlyReturns.sort(function (a, b) {
return (a - b);
})
yearlyReturns2.sort(function (a, b) {
return (a - b);
})
for (x = 0; x < yearlyReturns.length; x++) {
document.write(yearlyReturns2[x] + ", ");
}
So essentially I am calculating marketReturns, which is marketReturns[x-1] * daily change. I want however to make this into subarrays where I can preserve all the individual marketReturns for each iteration of y instead of just preserving the last day like I am in yearlyReturns[y].
I thought I could do it as such:
marketReturns[y][x] = y1 * marketReturns[y][x - 1];
marketReturnsVol[y][x] = y12 * marketReturnsVol[y][x - 1];
But this doesn't work. Is there any way for me to start writing the marketReturns figures into subarrays? Thanks.
You can mimic the multidimensional array using nested array/nested object in javascript:
e.g.
var arr = [];
//Initialize a 10x10 "multidimensional" array
for(var i = 0; i < 10; i++) {
arr[i] = [];
for(var j = 0; j < 10; j++) {
arr[i][j] = 0;
}
}
//Store
arr[5][5] = 10;

Generating unique 6 digit code js

I am trying to generate 6 digit code using JS.
it must contains 3 digits and 3 chars.
here is my code
var numbers = "0123456789";
var chars = "acdefhiklmnoqrstuvwxyz";
var string_length = 3;
var randomstring = '';
var randomstring2 = '';
for (var x = 0; x < string_length; x++) {
var letterOrNumber = Math.floor(Math.random() * 2);
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
for (var y = 0; y < string_length; y++) {
var letterOrNumber2 = Math.floor(Math.random() * 2);
var rnum2 = Math.floor(Math.random() * numbers.length);
randomstring2 += numbers.substring(rnum2, rnum2 + 1);
}
var code = randomstring + randomstring2;
the code result will be 3chars + 3 numbers .. I want to just rearrange this value to be random value contains the same 3 chars and 3 numbers
http://jsfiddle.net/pgDFQ/101/
You could shuffle your current codes with a function like this (from this answer)
//+ Jonas Raoni Soares Silva
//# http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
You could use it like this:
alert(shuffle("StackOverflow".split('')).join(''));
Here is an updated demo with this code.
Here is the code for you
function(count){
var chars = 'acdefhiklmnoqrstuvwxyz0123456789'.split('');
var result = '';
for(var i=0; i<count; i++){
var x = Math.floor(Math.random() * chars.length);
result += chars[x];
}
return result;
}
what you can do is use a dingle loop from 6 times and use random character and random number function one by one while also incrementing by 1, Although not that a good option but this may also offer some flexibility
Try this:
var numbers = "0123456789";
var chars= "acdefhiklmnoqrstuvwxyz";
var code_length = 6;
var didget_count = 3;
var letter_count = 3;
var code = '';
for(var i=0; i < code_length; i++) {
var letterOrNumber = Math.floor(Math.random() * 2);
if((letterOrNumber == 0 || number_count == 0) && letter_count > 0) {
letter_count--;
var rnum = Math.floor(Math.random() * chars.length);
code += chars[rnum];
}
else {
number_count--;
var rnum2 = Math.floor(Math.random() * numbers.length);
code += numbers[rnum2];
}
}
I might note that such a code should not be considered truly random as the underlying functions could be predictable depending on the javascipt engine running underneath.

JavaScript setTimeout not working with prompt box

Here is my code:
var t = setTimeout("increment();", 1000 * 3);
var st;
function increment() {
st = 1;
}
for (i = 0; i < 10; i++) {
cnt = i;
var no1 = Math.floor(Math.random() * 101);
var no2 = Math.floor(Math.random() * 101);
if ((i % 4) == 0) {
crct_ans[i] = no1 + no2;
quest[i] = no1 + " + " + no2;
}
else if ((i % 4) == 1) {
crct_ans[i] = no1 - no2;
quest[i] = no1 + " - " + no2;
}
else if ((i % 4) == 2) {
crct_ans[i] = no1 * no2;
quest[i] = no1 + " x " + no2;
}
else if ((i % 4) == 3) {
crct_ans[i] = no1 / no2;
quest[i] = no1 + " / " + no2;
}
ans[i] = prompt(quest[i], "");
if (st == 1) break;
}​
I want to stop the for loop if 3 seconds pass. But this is not working. For loop runs after the 3 seconds also. How can I do this?
Remove () and quotes like this:
var t = setTimeout(increment, 3000);
Removing () disables running of that function straright away/immediately whereas setTimeout expects callabck.
Removing quotes makes sure that eval isn't used behind the scenes.
BTW, it is good practice to declare all variables with single var keyword like this:
var t = setTimeout(increment, 3000), st;
If it suits your requirements, you can simply check how much time pass.
Example:
var start = new Date();
for(i = 0; i < 10; i++){
var end = new Date();
var elapsed = end.getTime() - start.getTime();
if (elapsed >= 3000)
break;
}​
Try formatting like so:
var t = setTimeout(function(){increment();}, 3000);

Categories

Resources