Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
This post was edited and submitted for review 14 days ago.
Improve this question
I was working trying to generate a random number the other day. The assignment is basically that, given an array with names, I was gonna log names on the console at random. I tried to generate a random number that is gonna help accessing the names working as the index of the elements (e.g., array[random_number_as_index]).
My confusion started when storing the method Math.random() in a variable and accessing that same variable, the result was the exact same number over and over. My line of code looks something like this.
const randomNumber = Math.floor(Math.random()*10));
Whereas when part of a function, e.g.,
function randomNum () {return Math.floor(Math.random()*10));}
would actually generate a random number every time the function is invoked. My expectation was that, upon accessing the variable, a random number was gonna be generated every single time, which was not the case, and only works if it is within a function.
const randomNumber = Math.floor(Math.random()*10));
Generates a random number, then assigns that random number to randomNumber.
randomNumber is a constant variable (meaning its value cannot be changed after the fact).
You're generating one random number, then saving it in a variable.
function randomNum () {return Math.floor(Math.random()*10));}
Defines a function that returns a random number when called.
Each invocation of randomNum generates a new random number.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a function I call with nameOfFunction(); the output of the function is an integer eg. 10.
I also have var number = 5;.
I cannot change the function nameOfFunction(); or substitute it with another variable.
Is there a way to add number to nameOfFunction(); so the output of nameOfFunction(); will equal 15?
Like this:
nameOfFunction() + number = nameOfFunction();
output would be
10 + 5 = 15
Edit with more info: NameOfFunction(); is the total cost of all items in the cart of my ecommerce site. It is the output of all the functions required to calculate the number of items and their amounts.
The number variable is the delivery charge that changes depending on the amount in the cart. The total is rendered using NameOfFunction(); and the value posted to a form.
I need to manipulate the output of NameOfFunction(); with altering the functions that define it. Adding number must occur after.
I cant show the code as it is obtuse and out of context would not make sense.
I cannot change the function nameOfFunction(); or substitute it with another variable.
From your subsequent comments, my guess (and the guess of a now-edited and -deleted answer — apologies to Ele, you got it right) is that you can, you just don't realize you can. In a normal scenario, this will do it (not the same as that deleted answer, stuck to ES3-level features):
var oldFunction = nameOfFunction;
nameOfFunction = function() {
return oldFunction.apply(this, arguments) + 5;
};
The identifier (technically, binding) of the function is writable by default, so the above remembers the old function, then replaces the value of its binding with a new function that calls the original and adds 5 to the result. The code uses Function#apply and arguments to ensure that both this and all arguments passed to the function are passed on by the wrapper.
Now, all calls to nameOfFunction will see the old function's return value with 5 added to it.
Live Example:
// The original function
function nameOfFunction(n) {
return n * 15 + 7;
}
// Us hijacking it:
var oldFunction = nameOfFunction;
nameOfFunction = function() {
return oldFunction.apply(this, arguments) + 5;
};
// All calls to it will now see the new return value:
console.log(nameOfFunction(2)); // 42
Store in a temporary variable whatever your nameOfFunction returns and add whatever value you want to add to that.
let nameOfFunction = function() {
return 10;
}
let temp= nameOfFunction();
let ans = temp+5;
console.log(nameOfFunction()+5);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to write a function that given an array like
var a = [
0.0015974718789698097
,0.755383581038094
,0.13950473043946954
,0.0011978091842754731
,0.005126875727346068
,0.0042250281407886295
,0.0001720958819913952
,0.0047584144830165875
,0.0835073272489086
,0.00016098907002300275
,0.0028037075787230655
,0.0014378579473690483
,0.00012411138102484662
]
or
var a = [
0.33333333333333333
,0.33333333333333333
,0.33333333333333333
]
or
var a = [
0.166666666666666
,0.166666666666666
,0.3
,0.3333333333333333
]
It round each number to 3 decimal places while keeping the sum of all the values is still equal to 1.0.
The way I imagine it would do this is by taking the difference of the new sum and the expected sum and distribute the difference while maintaining the relative distribution as close as possible. I can only think of an iterative approach and wanted to see what other solutions people can come up with
It's important to notice that the very last value of 0.00012411138102484662 will round to 0.000 but that doesn't it mean it should never get a piece of the difference, because the distribution it wants to maintain is the unrounded distribution, not the current distribution after rounding to 3 decimal places nor after iteration of balancing
If you are planning on rounding each of the values in the array to the 3rd decimal and adding them all up, Then here's what you need to do. You will need to get each number of the array into a loop and make that number to the fixed 3rd decimal by doing .toFixed(3) and parsing that to a float and adding it to a variable which will loop and the variable's value will change. Like this:
var int = 0;
a.forEach(number => { int += parseFloat(number.toFixed(3)) })
int // 1
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In this exercise, you will roll a pair of dice until the numbers add up to a given number. You can assume that the given number is 2, 3, 6, or 12. Using pseudocode, write an algorithm that returns the number of times the dice is rolled to achieve this number.
I have absolutely no idea how to start doing this. Can you guide me a bit?
Also what does the last sentence mean?
This should get you started. The detail the assignment calls for is likely one or two levels refined from here. For example, what does "roll a die" mean. Probably something to do with saving a random number of some sort to a variable....
define rollRequiredForA(target) {
if target is not an integer or is outside the valid bounds abort
initialize a counter to 0
loop
increase the counter by one
roll two dice
add results together
if the result equals target return counter
end loop
}
First let me address your question about the last sentence of the problem:
I'll break it down in parts.
First pseudocode is a simplification of the steps that you would need to take in solving a problem in a format that is very representative of code but is not actual code written in any programming language. For example pseudocode could be something like this:
if the earlier result is 2 then
use this list: Britney, Caitie, Sierrah
else
use this other list: Brooke, Josh, Zach
Secondly an algorithm is a set of rules to followed in calculating or solving a problem. It's like a formula for solving a problem. Some everyday examples could be:
Driving home: what route should you take? Will there be traffic on the shortest route? If so, will it slow you down more than taking a slightly longer route? These are all questions that would be asked in an algorithm.
Sorting: Typically when you sort something, you do it in a specific way even though you may not realize it such as checking each one and pulling the first out of the pile and putting it on top and then the second and then the third and so on and so forth.
Dividing and conquering: This is another very common algorithm in everyday life.
For more examples check out this quora post
So in other words, the last sentence is asking you to write a simplification of the steps that you would need to take to calculate the amount of rolls of the dice it takes to get those two dice to add up to the given number.
Now that that is out of the way, lets tackle the actual problem
To get you started, you'll have to run some sort of loop (maybe use a do-while loop?), and probably best to do it inside some sort of method. You'll need to have a counter if your dice don't add up to the target roll again and increase the counter until your roll adds up to the target, then return that value of the counter
define rolls needed(target)
initialize counter as 0
initialize sum
do this loop
increase your counter
roll your dice
add results together
while sum does not equal target
return your counter
end
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Recently i've been trying to do a repetitive random number in JS, but the problem is that always i have to reload the page to get a new random number, even i try to show it multiple times but the problem is that the number is the same until i refresh the page.
<?php
<script type="text/javascript" charset="utf-8">
function getNumber(){
var number = Math.random()
return number;
}
document.write(getNumber()); // NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
document.write(getNumber()); // SAME AS NUMBER 1
</script>
?>
I think it might be because you are using document.write. Use console.log instead and take a look at the console.
console.log(getNumber());
console.log(getNumber());
If you want your results in the browser get a reference to an element, or make and append one.
Math.random() returns a number between 0 and 1. Please read the docs for more information.
Rather than using document.write just update the content of your element like this:
function getNumber(){
var number = Math.random()
return number;
}
var div = document.getElementById('result');
div.innerHTML = getNumber();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've made this small tool but I'm not sure how to achieve what I need.
I would like it to subtract from the "Points Left" when adding to the others.
(Not going below zero into the negative, only 30 points).
I would also like to prevent going BELOW the initial numbers in "Weapon Power" and "Magic Power".
(I would like to be able to only spend a maximum of 25 points into one "power")
I think it kind of explains itself so maybe I'm just confusing you more.
Any ideas?
DEMO
You need to give your number input elements distinct ids, because when you do document.getElementById, it will only return you the first element with the given ids.
Then, you need to give another distinct ID to the "points left" field for each character, and update that one. To do that, you'll need to pass to add and substract the correct value ( add(warrior, 'weapon'), add(wizard, 'magic')).
You need to be able to get your IDs from your warrior or wizard object, so you could try doing this:
var wizard = {
weapon:"idOfWeaponField", magic:"idOfMagicField", points:"idOfPointsField"
};
where the string values are the ids of your elements.
Then, within your add function, you can access your id like this
function add(character, statName){
var myID = character[statName];
}
and update the correct input value.
EDIT: code here.
I would also like to prevent going BELOW the initial numbers in "Weapon Power" and "Magic Power". >(I would like to be able to only spend a maximum of 25 points into one "power")
Basically, you've seen what I did with the points left, when I said if(pointsVal.value == 0) return; ? You should be able to implement any constraint you like using that.
I modified mine to give an example where the limits are at their initial values.
If you only want to spend a given number of points on one of the powers, you'll have to substract the limit from the current number and return from add() without changing the value if the number exceeds the threshold. That should be pretty easy with what you have now, since you don't have to change the character object to do it.