How Do I Use Loops to Find Sums in Array? - javascript

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.

Related

Array of objects properties become NaN between function calls in Html Javascript

This code is done in HTML javascript.
The following functions (placero() and runro()) are called in that order. placero() seems to initialize the xs and ys of the object list correctly, but by the time the first line of runro() is called, all of the xs and ys have become NaN.
The goal of the code was to make a program that creates rooms and connects them with corridors. Previous steps have inititalized the rooms and corridor layout, but the job of placero() is to place each room somewhere random on the map.
the code is as follows:
runm does all the initial setting code(such as the room member initialization) and does all the other work before placero(). I have been clicking the buttons in the intended order(sequentially), so that shouldnt be the problem.
var roomes = new Array(0);
function randIntBetween(min, max) { // min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
//before any function calls, rooms is initialized as follows(well after the input has been entered, in most cases):
roomMax = document.getElementById("inp1").value; //this is the inputted number of rooms being made
for (var k = 0; k < roomMax; k++) {
var obj = {
ind: k,
x: -1,
y: -1,
neighb: Array(0)
}
roomes.push(obj);
}
//then some work is done, placing the indexes of other rooms in the neighbors array in each room.
//none of the in-between code edits x or y.
function placero() {
for (var kis = 0; kis < roomes.length; kis++) {
var x = randIntBetween(5, mapX - 5); //get a random x and y for room position
var y = randIntBetween(5, 5);
roomes[kis].x = x;
roomes[kis].y = y;
}
console.log(roomes); //prints a correct array
}
function runro() {
console.log(roomes); //prints an incorrect array
var iterCount = 2;
//this code aims to place rooms closer to their neighbors, by averaging a rooms position with that of its neighbors and moving it half the way in that direction.
for (var ki = 0; ki < iterCount; ki++) { //for each iteration in which the rooms are moved,
for (var kt = 0; kt < roomes.length; kt++) { //for each room
var coun = NeighbCount(roomes[kt]); //get number of neighbors(will be used for averageing)
console.log(coun);
var sumx = 0;
var sumy = 0;
for (var km = 0; km < coun; km++) { //for each neighbor,
sumx = sumx + roomes[roomes[kt].neighb[km]].x; //add its position to the sum position
sumy = sumy + roomes[roomes[kt].neighb[km]].y;
}
sumx = sumx / coun; //then divide by number of neighbors to get new position
sumy = sumy / coun;
console.log(sumx + " " + roomes[kt].x); //troubleshooting
console.log(sumy + " " + roomes[kt].y);
roomes[kt].x = sumx / 2 + roomes[kt].x / 2; //setting new positions
roomes[kt].y = sumy / 2 + roomes[kt].y / 2;
}
}
}
<div>
<input type="number" id="inp1" name="inp1"><br>
</div>
<button onclick="runm()">Make room map</button>
<button onclick="placero()">place rooms</button>
<button onclick="runro()">Make rooms</button>
You're probably getting the error because roomMax is of string type and not number type. To solve this, make the following modifications to your code:
roomMax = parseInt(document.getElementById("inp1").value);
The value from an input will always be a string. The code above changes the type.
Look through your code to see if you have any similar mistakes.

Javascript calculating in for loops

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

Setting up Javascript order price minimum

I am trying to set up a way so that if my total cart's price is under $125, it will charge $125. I have googled multiple ways of getting the order minimum added but nothing works with how this code was set up. Please view the code below:
function Recalculate() {
var total = 0;
$.each(cart, function(index, item) {
var options = {};
if (item.o) $.each(item.o, function(opt_ind, opt_item) {
options[opt_item.name] = opt_item.value;
options[opt_item.id] = opt_item.value;
});
var width_ft = parseInt(options.width_ft);
if (!width_ft || isNaN(width_ft)) width_ft = 0;
var width_in = parseInt(options.width_in);
if (!width_in || isNaN(width_in)) width_in = 0;
var width = width_ft + width_in / 12;
var length_ft = parseInt(options.length_ft);
if (!length_ft || isNaN(length_ft)) length_ft = 0;
var length_in = parseInt(options.length_in);
if (!length_in || isNaN(length_in)) length_in = 0;
var sq = width * length;
var inshop = options.type_of_cleaning == 'In_Shop_Cleaning';
var base_price = 0;
var base_min = 0;
switch (item.p) {
case 'livingroom':
base_price = LIVING_ROOM;
break;
case 'stair':
base_price = STAIR;
break;
}
var i_total = sq * base_price;
if (i_total < base_min) i_total = base_min;
$('span.isize').eq(index).html('$' + i_total.toFixed(2));
total += i_total;
if (options.SCOTCHGARD == 'on') total += Math.min(sq * SCOTCHGARD, 25.00);
if (options.DECON == 'on') total += Math.min(sq * DECON, 25.00);
if (options.DA == 'on') total += Math.min(sq * DA, 25.00);
if (options.clean_or_buy == 'buy') total += i_total * NEW_PAD_TAX / 100;
});
return [total];
}
If you want to charge a minimum of $125, the simplest thing you could do is simply set the total to that minimum just before you return it. e.g.
if (total < 125) { total = 125; }
return total;
(Note that this is returning total not [total], as it is not clear to me why you want an array of a single value returned.)
Your question includes the phrase "...getting the order minimum added". That doesn't make sense to me, i.e. if the real total is $100, I doubt that you want to add $125 (to make $225 total), but rather you simply want to set the total to the minimum. If that is correct, but you do want to keep track of the extra that you add, then perhaps you could do the following, again right before you return from the function:
var extraForMinimum = 0;
if (total < 125) { extraForMinimum = 125 - total; }
return {total: total, extraForMinimum: extraForMinimum };
In this case, the function is returning an object that contains both the actual total (which could still be less than $125) as well as the extra cost that is required to bring the charge up to the minimum. If you are doing this, however, you might want to change the variable name from total to, say, subtotal or something else similar.

Split an array into even chunks based on integer in javascript

This might be a duplicate, though I didn't find any questions specific to my problem here.
Say I have an array like this
var hundred = [1,2,3,4,5...100]
This array has 100 elements. From 1 to 100.
Based on an integer, how can I split this array into another array with the same amount of elements, except they've been evenly distributed like this?
var integer = 2;
var hundred = [50,50,50,50,50,50...100,100,100,100,100,100]
In this example, the array has 50 elements with the value 50, and 50 elements with the value 100, because the integer was 2.
I'm bad at math, so this might be incorrect, but I hope you understand what I mean. The array must have the same ammount of indexes after the calculation.
Edit (Due to me being very bad at formulating questions, I'm going to use the code I need this for here):
So I have a frequencybin array (from the AudioContext analyser):
var fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
This array has a set number of elements ( They are the frequencies of audio played ).
Now I have a spectrum analyser, which has a set number of "bars" so if I have only 3 bars, then how can I split the fbc_array so that each bar has the evenly distributed frequency in it? For example, with 3 bars, bar one would have the bass, bar two would have the mids, bar three would have the treble.
I'm using a for loop for iterating over each bar:
for (i = 0; i < bars; i++) {
bar_x = i * canspace;
bar_width = 2;
bar_height = -3 - (fbc_array[i] / 2);
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
Here's what I gathered from this craziness! Sorry you're having trouble conveying your problem. That's always a headache! Good luck.
//set integer to whatever you want
var integer = 3;
var randomNumber;
var output = new Array()
function getRandomIntInclusive(min, max) {
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
}
for(i = 0; i<integer;i++){
getRandomIntInclusive(1,100);
for(j = 1; j< (100/integer); j++){
output.push(randomNumber);
}
}
//note, you will not always get 100 array items
//you can check with console.log(output.length);
console.log(output);
(Written before your update, so guessing here).
You're looking for a way to approximate a graph so that it's divided into bands and each point within a band is replaced with that band's maximum:
Number.prototype.times = function(fn) {
var a = [];
for(var i = 0; i < this; i++)
a.push(fn(i));
return a;
}
function approximate(src, n) {
var res = [],
size = Math.ceil(src.length / n),
i = 0;
while(i < src.length) {
var chunk = src.slice(i, i += size)
var p = Math.max.apply(null, chunk);
// this gives you an average instead of maximum
// p = chunk.reduce((x, y) => x + y) / chunk.length;
res = res.concat(size.times(i => p));
}
return res;
}
src = 20..times(i => 10 + Math.floor(Math.random() * 80));
res = approximate(src, 4);
document.write('<pre>'+JSON.stringify(src));
document.write('<pre>'+JSON.stringify(res));

find the mean of an array of 1000 random integers javascript

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.

Categories