How to use a variable in Math.floor - javascript

I want to get the max amount of money a person has with
let targetUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
var targetForMath = userData[targetUser.id].money;
and I want to use that variable to set the max amount for a Math.floor. I tried
let randomStealCoins = Math.floor(Math.random() * targetForMath) + 1;
but when I use that it gives me NaN. How can I make it so it gives me the actual an actual number not something weird?

If targetForMath is undefined, that will give you NaN:
Since:
Math.random() * undefined -> NaN
I would ensure that targetForMath is a valid number.

I'm not gonna mention that you're mixing var and let, other than to say that you're doing it and should be careful of that.
The first question I'd ask is what the typeof userData[targetUser.id].money is, and more specifically what its value is. If it's a number, boolean, null, or empty array (?!) it should work, or at least not return NaN. However, if it's a string, undefined, or any other value, JavaScript won't really know what you mean when you say, for example, multiply Math.random() times "fish".
Usually in this case it's a good idea to console.log out what userData[targetUser.id] is, just to make sure the object you're getting back from that is actually what you think it is. Is there actually a property on the userData object defined by the targetUser's id?

Related

Sum of 2 elements in array - Algorithm - JavaScript

I'm working on JavaScript algorithms and could use some help. What am I doing wrong exactly?
// Given an array of arr, positive integers, and another number X.
// Determine whether or not there exist two elements in arr whose sum is exactly X.
function keyPair(arr, x){
var sum=false;
var key=0;
var temp=0;
for(var i=0;i<=arr.length;i++){
while(sum=false){
key=arr[i];
arr[i]=temp;
temp=key;
}
if(temp+arr[i]==x){
sum=true;
}
}
console.log(sum);
}
keyPair([1,2,4,3,6], 4);
I think this one deserves an explanation:
sum=false is an assignment statement. As an expression, an assignment statement is evaluated as undefined (regardless of the value assigned). So while(sum=false) is actually while(undefined), which is interpreted as while(false).
Your mistake was - as explained multiple times - the wrong comparison operator. I took the liberty of rewriting your code involving a .reduce() call:
function keyPair(arr,sum){
return arr.reduce((a,c,j)=>{
let i=arr.indexOf(sum-c);
if (i>-1 && j<i) a.push([c,arr[i]]);
return a;}, []);
}
console.log(keyPair([1,2,4,3,6], 5));
I'm not going to repeat what has been already said about your code. But even if you're starting coding in JS, it pays for you to start using JS built-ins that will save you a lot of time:
// Determine whether or not there exist two elements in arr whose sum is exactly X.
So you're only interested in whether they exist, not in which are those:
const keyPair = (arr,value) =>
// some: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
// slice: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
arr.some( (x,i) => arr.slice(i).some( y => x + y === value));
console.log(keyPair([1,2,4,3,6], 4))
console.log(keyPair([1,1,1,1,1], 4))
With some you check if there is an x+y sum that equals to your desired value
With slice you omit the portion of the array that you don't need to check
first off, you might want to start by considering changing while(sum=false) to (sum===false), although running on vs code- it does run regardless.

Random Array Picker - Javascript

i was coding for a small project but my random array picker doesnt work
var btnarray = [xfn.left, xn.left, xnln.left, xln.left, xnn.left];
(this is the array)
var rand = btnarray[Math.floor(Math.random() * 4)];
(this is the random picker var)
Well, when i start, the rand value results equal to btnarray[0]
anyone can help me please?
Oh i perfectly know that the variables are all different.
Thanks
Since your array's length is 5, you need to multiply the value of the random function by that number. Better yet, use the length property.
var rand = btnarray[Math.floor(Math.random() * btnarray.length)];
You shouldn't use Math.floor since it will make very hard to get the last element in your btnarray array, you'll need to get exactly the number btnarray.length in order to get at that element. Also, floor tends to flatten probability outcomes and looks like you're stuck on some value(s) since it's threshold is forcing you to have the greatest integer smaller than or equal to some number.
You should use round instead, this will even the probability for every array element and will give you more apparently random indexes. Try this, it's already tested with a dummy btnarray array variable and works fine.
var rand = btnarray[Math.round(Math.random() * btnarray.length)];
if you toss this in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
you can just do this:
var randomValue = rando(btnarray).value
I usually go with randojs.com because it can handle pretty much any random functionality you need, and it's all short and easy to read.

I am trying to convert numbers into their opposite value regardless of whether number is positive or negative

I tried this code, it works
const opposite = number => -number
Code won't run, just trying to experiment with different ideas
function opposite(number){
return Math.abs(number)
}
opposite(1)
What Am I missing here ?
Your code is running, your just noticing the output for two reasons:
returning a value from your function doesn't mean it will be logged to the console. You need to console.log() the function call to see its output (the returned value)
Math.abs() will get the absolute value of a number passed into it (which isn't the same as the opposite). You can think of this as the distance a given number is away from 0. Thus doing Math.abs(1) will give 1 not -1, perhaps making you think your function isn't working. With this in mind Math.abs() will only give you the opposite for numbers which are negative, not positive.
See running example below:
function opposite(number){
return Math.abs(number)
}
console.log(opposite(-1)); // returns 1
console.log(opposite(1)); // returns 1

Javascript. Give value to variable depending on parameter value

I have been given a Javascript code, and there is a sentence I cannot fully understand:
var isFaculty = (paramArray[0] == "yes"),
isFaculty variable is used afterthat in a equation, where more variables are involved. While the latter are defined along the code, the former is supposed to be defined (i.e. numerical value) by that sentence, as it depends on a parameterArray that the user should introduce (the parameter array is of size 3, anyway). For cell [0], paramArray can have two values, namely "yes" or "no".
I am wondering a possibility, but any help is welcome.
Thanks in advance,
/Jorge.
(paramArray[0] == "yes")
This is like a mini if statement that returns either true or false.
isFaculty is a boolean variable that captures that result.
Once the true or false is caught it can be used as a numeric 1 or 0 that even though is not recommended but could be multiplied by a number to turn it into a 0 if it's false or leave it unchanged if it's true
thanks for your help. The point is that isFaculty variable is involved in a formula as follows:
var xExample = 1/(1+Math.exp(-(-2 + 4*city - 0.11*gender + 0.6*isFaculty + 0.2*city*gender - 0.424885*city*isFaculty - 0.3*citygenderisFaculty)));
consequently, I understand that isFaculty gets value 1 or 0 depending on being true or false?
== is a comparator that will return a boolean value, so the code you have will assign true or false to isFaculty
The var name isXxxx would suggest to me that its value would be boolean.
So what you have is basically:
var isFaculty - for the variable isFaculty
= - assign the value of the following expression
paramArray[0] - take the first value from the array paramArray
== - check if it matches in content but not necessarily type with
"yes" - the string value that you are looking for to assign true
Implicitly this also means that if the content of paramArray[0] does not match with the content of the string value "yes" then the value of isFaculty will be false.
This could be used as a 'flag' later on by using false as 0 and true as 1.

Javascript Sum Values

I need to sum several values in javascript. I've tried by using following code
var a = 2;
var b = 5;
c = a+b;
But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :
c = 25
I believe you guys can help me easily about this. Thx before. Regard Andha.
Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.
The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
This works fine:
var a = 2;
var b = 5;
var c = a + b; // c is now 7
The code you show will not work the way you describe. It will result in 7.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt().)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].
Use parseInt():
var a=2;
var b=5;
c=parseInt(a)+parseInt(b);
-Is important to apply Number() to every value. The ideal way is:
var sum = 0
sum = Number('93') + Number('7') //result 100
-instead of this way (careful with this)
var sum = 0
sum = Number('97' + '3') //result 937
-and careful with this (as variable is going to assign string type by default)
var sum = 0
sum = Number('97') + '3' //result "973"
You can simply convert string to a number by adding + before it. For somebody can be more readable.
Example:
const a = "2";
const b = "5";
const c = +a + +b
or const c = (+a) + (+b) may be more readable.
That will first convert the string to a Number.

Categories

Resources