I am having trouble with calculating the mean value of an array of 1000 random numbers. The array holds 1000 random number between 1 and 30.
I also want to be able to count how many of each number occurred in the array and print the amount of each number in a frequency distribution table.
<script type = "text/javascript">
var arr = [];
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
for (var i = 0; i < 1000; i++) {
arr.push(getRandom( 30 ));
}
document.write(arr);
document.write("<br/>");
for (var i = 0; i <= 1000; i++){
sum += parseInt(arr[i]);
}
var mean = sum/arr.length;
document.write("The sum of all the elements is: " + sum + " The mean is: " + mean);
</script>
You don't have to run the cycle twice. Do everything on the fly:
var distrTable = {};
for (var i = 0; i < 1000; i++) {
var rnd = getRandom(30);
sum += rnd;
arr.push(rnd);
if (!distrTable[rnd]) {
distrTable[rnd] = 0;
}
distrTable[rnd]++;
}
Now the variables contain the following information:
arr - all random numbers.
distrTable - each random number with frequency.
sum - the sum of all random numbers.
jsFiddle example
By the way, if you're wondering why your code is not working... Here are the reasons:
First of define the variable sum. Before the loop just put sum = 0;
Second of all, while the array is long 1000 items, in the second for you loop for 1001 times. The declaration should be as follows:
for (var i = 0; i < 1000; i++) // not i <= 1000;
Then the code should work.
The trivial error in your code is that in your second loop you are running up to element 1001 instead of element 1000.
Since that element is undefined, it causes a sum of NaN and the mean, likewise.
To fix, change the <= 1000 to just < 1000
You should also remove the parseInt call - that's only necessary if your input values are strings, but your array already contains numbers.
Beware when you generate random numbers like this:
function getRandom( num ){
return Math.round(Math.random() * num)+1;
}
... this code can generate numbers from 1 to 31! It's because of the Math.round -- if Math.random() generates 0.99, 0.99 * 30 will equal 29.7, that will be rounded to 30, and then 1 will be added!
The solution is to replace Math.round with Math.floor.
Related
As you can see int he code below I separate the n variable and convert back to an integer array. When I put these numbers into my for loop they come out in the billions. Any help would be greatly appreciated.
var n = [86]
var p = [1]
n = n.toString().split("").map(function(value) {
return(parseInt(value))
})
var total = 0;
for(i=0;i<n.length;i++) {
total += (Math.pow(n[i],(p+i))
}
console.log(total)
You need the conversion from strings to numbers and you are adding an array to numbers.
You cannot sum an array to an integer [1]+0, it doesn't result in a number. It will do a concatenation.
var n = [86]
var p = [1]
n = n.toString().split("").map(val => Number(val))
var total = 0;
for (i = 0; i < n.length; i++) {
total += Math.pow(n[i], (p[0] + i))
}
console.log(total);
p is an array not an individual number, in your for loop, when it is running (p+i), that value ends up being 10 and 11. So your first loop is running Math.pow(8,10) and the second time it runs it is running Math.pow(6,11), which, will result in a number in the billions
So I need to use a loop to fill an array with the total amount. The total amount will be the amount spent plus a gift card that is a percentage. So
total = amountSpent + amountSpent*(1+giftCard)
I am having trouble getting the total. The spent and gift card amounts are all randomly generated using math.random. The spent and gift card amounts are each found in separate arrays, with the spent amount being anywhere between 0 to 500, and gift card amount being anywhere from 0 to 50.
var spent = new Array(5);
for (var i = 0; i < 5; i++)
{
randS = Math.floor(Math.random() * 500);
spent[i] = randS;
}
var gifts = new Array(5);
for (var i = 0; i < 5; i++)
{
randG= Math.floor(Math.random() * 50);
gifts[i] = randG;
}
These are how I fill the arrays using a for loop. I am now supposed to create a new array and use a loop to calculate the total. I defined 2 variables for spent and gift card amount, but I am unsure if they are calling the correct numbers.
var totals = new Array(5);
var tSpent = spent;
var tGifts = gifts;
for (var i = 0; i < 5; i++)
{
totals[i] = tSpent + (1 + (tGifts / 100)) * tSpent;
totals[i] = totals[i].toFixed(2);
}
I know this array is the problem since the other two arrays are displaying the numbers fine. I also have to convert the gift card amount to a decimal and make sure the total is to 2 decimal places.
you can write the whole code in one loop like this:
var spent=[],gifts=[],totals=[];
for(let i = 0; i < 5; i++){
spent[i] = Math.floor(Math.random() * 500);
gifts[i] = Math.floor(Math.random() * 50);
totals[i] = spent[i] + (1 + gifts[i]/10)*spent[i]
totals[i] = totals[i].toFixed(2);
}
As far as I am able to understand your question, I feel you are doing it correct, just a small correction needs to be done in your code.
var totals = new Array(5);
var tSpent = spent;
var tGifts = gifts;
for (var i = 0; i < 5; i++)
{
totals[i] = tSpent[i] + (1 + (tGifts[i] / 100)) * tSpent[i];
totals[i] = totals[i].toFixed(2);
}
Also, your arrays tSpend and tGifts are calling correct numbers, although they seem redundant, unless you have something planned for them later in code. If not, they are just directly referencing your actual variable spend and gifts.
I have a <p id="rabbits">1 2 9 4</p>' And i'm trying to calculate all the 1,2,9,4
However, I'm stuck at this part:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
for (i in rabbits_array) {
console.log(i) // prints 1,2,9,4
}
How do add all of these numbers together (which is 16 if you count manually) in javascript?
Can map array to number and use reduce
var rabbits = $('#rabbits').text()
var total = rabbits.split(" ").map(Number).reduce((a,c) => a + c)
console.log(total)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="rabbits">1 2 9 4</p>
There are a variety of ways to do this.
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
var total = 0;
rabbits_array.forEach(function(element) {
total += element * 1;
});
console.log(total);
You could use a standard for loop:
for (var i = 0; i < rabbits_array.length;i++) {
total += rabbits_array[i] * 1;
}
You could replace the "multiply by 1" (which would have to validate beforehand that it's actually a number and not a letter), with parseInt or parseFloat. Using these methods can do some of this validation for you, but may also give you odd results.
total += parseFloat(rabbits_array[i]);
https://www.w3schools.com/jsref/jsref_parseint.asp
There are other ways to do this as well, but these are just a few examples to get you going. I'd suggest Googling "javascript loops" to read more about this kind of thing.
Try this:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(" ");
var total = 0;
for (var i = 0; i < rabbits_array.length; i++) {
total = total + parseInt(rabbits_array[i]);
}
console.log(total)
You need to convert the string version of the number (from your split function) to an actual number before adding them together
I am wanting to generate a random number between 1-100, but I am only wanting to generate those numbers once each time. I have a loop that runs 3 times to run the .Math and then push that into an array. But I dont want the situation where it generates the same number more than once.
I have put 21 in the allAnswers[] array as that is something that will stay consistent. Is there a way to generate and then check that array if that number exists and then run the .math again?
function buttonGenerator(){
var allAnswers = [21],
randomizer = [];
// Generates 3 random answers
for(a = 0 ; a < 3; a++) {
wrongAnswers = Math.floor((Math.random() * 100) + 1);
allAnswers.push(wrongAnswers);
}
// Generates random buttons while inputting the correct and incorrect answers randomly
for(i = 0 ; i < 4; i++) {
var buttonArea = $("#answerOptions");
input = $('<button class="col-xs-6 btn btn-primary"></button>');
input.appendTo(buttonArea);
}
shuffle(allAnswers);
console.log(allAnswers);
}
buttonGenerator();
Use indexOf to check if the array has the value before pushing:
if (allAnswers.indexOf(wrongAnswers) === -1) {
allAnswers.push(wrongAnswers);
}
I have:
function getRandomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
But the problem is I want randomise the population of something with elements in an array (so they do not appear in the same order every time in the thing I am populating) so I need to ensure the number returned is unique compared to the other numbers so far.
So instead of:
for(var i = 0; i < myArray.length; i++) {
}
I have:
var i;
var count = 0;
while(count < myArray.length){
count++;
i = getRandomInt(0, myArray.length); // TODO ensure value is unique
// do stuff with myArray[i];
}
It looks like rather than independent uniform random numbers you rather want a random permutation of the set {1, 2, 3, ..., N}. I think there's a shuffle method for arrays that will do that for you.
As requested, here's the code example:
function shuffle(array) {
var top = array.length;
while (top--) {
var current = Math.floor(Math.random() * top);
var tmp = array[current];
array[current] = array[top - 1];
array[top - 1] = tmp;
}
return array;
}
Sometimes the best way to randomize something (say a card deck) is to not shuffle it before pulling it out, but to shuffle it as you pull it out.
Say you have:
var i,
endNum = 51,
array = new Array(52);
for(i = 0; i <= endNum; i++) {
array[i] = i;
}
Then you can write a function like this:
function drawNumber() {
// set index to draw from
var swap,
drawIndex = Math.floor(Math.random() * (endNum+ 1));
// swap the values at the drawn index and at the "end" of the deck
swap = array[drawIndex];
array[drawIndex] = array[endNum];
array[endNum] = swap;
endNum--;
}
Since I decrement the end counter the drawn items will be "discarded" at the end of the stack and the randomize function will only treat the items from 0 to end as viable.
This is a common pattern I've used, I may have adopted it into js incorrectly since the last time I used it was for writing a simple card game in c#. In fact I just looked at it and I had int ____ instead of var ____ lol
If i understand well, you want an array of integers but sorted randomly.
A way to do it is described here
First create a rand function :
function randOrd(){
return (Math.round(Math.random())-0.5); }
Then, randomize your array. The following example shows how:
anyArray = new Array('1','2','3','4','5');
anyArray.sort( randOrd );
document.write('Random : ' + anyArray + '<br />';);
Hope that will help,
Regards,
Max
You can pass in a function to the Array.Sort method. If this function returns a value that is randomly above or below zero then your array will be randomly sorted.
myarray.sort(function() {return 0.5 - Math.random()})
should do the trick for you without you having to worry about whether or not every random number is unique.
No loops and very simple.