Calculating average with prompt of an number - javascript

How can I make a function to find average from a number insert from prompt? Instead of an array of data.
It is different form all the tutorial on the site because the tutorial and solution here are having a set of data already but instead this question above wants us to calculate the sum of the input number form the prompt.

for example:
const size = parseInt(prompt("insert number")) + 1;
if(size > 0){
const arr = [...Array(size).keys()];
const sum = arr.reduce(function(a, b) { return a + b; }, 0);
alert(sum / size );
}

Related

How to smooth elevation gain from GPS Points

I have a big problem here:
I have an array of gps datas and it's necessary to calculate some informations, I did it all except for the total elevation gain in the route.
There's an array like this [825.23423, 827.39420, 828.19319, ...] that storage the elevation of each gps point passed and I need to calculate the full sum.
The problem is that gps is not so accurate and sometimes gives some incorrect elevations, and it's making the sum get wrong.
I tried many ways to smooth the data, here are some:
Set a minimum value to sum the elevation gain
Get "sub-arrays" and made the media of them to sum the elevation gain after.
Get "sub-arrays" and pop and shift the uncommon values to sum after that.
And the actual way I mixed all, it got better but not even close to the perfect:
const getMediaFixed = (values: number[]) => {
values.sort((a, b) => {
return a - b;
});
values.pop();
values.shift();
const media = values.reduce((a, b) => a + b) / values.length;
return media;
};
let last: number = elevations[0];
let elevationSum = 0;
// let countLimit: number = 1;
for (let i = 0; i < elevations.length - 5; i += 5) {
let media: number;
if (i <= elevations.length - 4) {
media = getMediaFixed([
elevations[i],
elevations[i + 1],
elevations[i + 2],
elevations[i + 3],
elevations[i + 4],
]);
} else {
media = elevations[i];
}
const temp = 0.75 * last + 0.25 * media;
if (temp - last > 0) {
elevationSum += temp - last;
}
last = temp;
}
The point is that it's not working anyway.
Here's a site that works perfectly calculating from a GPX File (I couldn't find the contact to ask for help):
https://www.trackreport.net
I appreciate any ideas to improve the code!
I made it using the exponential moving average to smooth the array with elevations and then I used 1 meter to ignore the bugs!
Thanks.

Javascript function get randomize numbers with incremental order ranging from 1 to 100

I am creating fake statistics real-time data for that I need to show the number of users available on the website for one game of 5 minutes,
I want to generate random numbers within a range of 1 to 100, but in incremental order. Which means every number that I get should be greater than the previous one.
Expected output:
Output at each function call will be like 1,5,12,25,...,98,100 in randomized and incremental order only.
Thanks in advance.
My code:
randomnumber(fixed,count,range){
return fixed+count*range;
},
function(){
var count = 1;
this.socketData( ({ data }) => {
count++
data.data.totalUsers += this.randomnumber(50,count,Math.abs(Math.floor(Math.random() * (100 - 1) +1)));
}
Assumptions
So, some assumptions to state:
no numbers can be duplicated
numbers must be ascending
numbers must be in range 1 - 100 (inclusive)
Which means we can have anywhere from 1x entry i.e. [100], up to 100 entries [0,1,2,...98,99,100].
So, to implement this strategy, we'll need to:
create X random entries (modify the seed as desired - 100x means we allow for all scenarios, I've chosen to randomise it)
sort the results
remove duplicates
TLDR;
Below is the implementation - works just as well for the range 50 - 200:
// range inclusive
const minRange = 1
const maxRange = 100
const rangePlusOne = maxRange - minRange + 1
// seed = [1 - 100]
const seedNumberOfEntries = parseInt(Math.random() * rangePlusOne) + 1
// generate, sort, unique
console.log([...new Set(
new Array(seedNumberOfEntries)
.fill(0)
.map(() => parseInt(Math.random() * rangePlusOne) + minRange)
.sort((a,b) => a-b)
)]
)
I suggest you create them in one loop and add to an array then sort that array. This should get you a sorted list of incremental random numbers.
You can then just pull 'next' whenever you want the next one.
let numbers = [];
for (let i =0, l = 100; i<l;i++){
let number = Math.floor(Math.random() * 100);
numbers.push(number);
}
numbers.sort(function (a, b) {
return a - b;
});
console.log(numbers);
const from = 0;
const to = 100;
const rand = Number(String(Math.random()).slice(2, 2 + 15));
const num = from + (rand % (to - from - 1)) + 1;
console.log(num);
Hope this will helps you can give range from & to

How to accumulate over each number? JavaScript [closed]

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 2 years ago.
Improve this question
This is my problem I am having a hard time onto what to do to solve this
The Task: We'll pass you an array of two numbers.
Return the sum of those two numbers plus the
sum of all the numbers between them. The lowest number will not always come first.
For example, sumAll([4,1]) should return 10 because
sum of all the numbers between 1 and 4 (both inclusive) is 10.
function sumAll(arr) {
Math.min(arr); //finds the lowest number and takes it 1
Math.max(arr); //finds the largest number 4
//must start at the 1st number and loops over until the max value is reached
//0 start at the 0th index of the array
//++ increament by one so 1 2 3 4
//multiply's each number
//.lenght until the lenght of the array is reached
var i;
for (i = 0; i < arr.length; i++) {
i * i;
}
return 1;
}
sumAll([1, 4]);
If its going to be always 2 numbers in an array, then you can easily do this and no more fancy code.
var arr = [1, 4];
arr.sort((a, b) => a - b);
var total = 0;
for (var i = arr[0]; i <= arr[1]; i++ ) {
total += i;
}
console.log(total);
You can grab the largest number from your input array using Math.max and the smallest number from the array using Math.min, you just need to spread the values from the array into the method calls so that the numbers from the input array are used as the arguments (rather than the array itself).
Once you have the largest and smallest number, you can find the sum between (and including) these two numbers. This can be done using a loop. However, a more efficient way would be to use a formula to compute it for you. If you call the smaller number a and the larger number b, you want to find:
res = a + (a+1) + (a+2) + ... + (b-1) + b
res2 = b + (b-1) + (b-2) + ... + (a+1) + a
As you can see above res2 and res are equal. So we can say res2 = res. So, if we perform res + res2, we will get 2*res. If we add the two together (adding by the columns), we get:
2*res = a+b + (a+1)+(b-1) + (a+2)+(b-2) + ... + (b-1)+(a+1) + b+a
= a+b + a+b + a+b + ... + a+b + a+b
As you can see 2*res results in a+b being repeated for every number in the original equation, which is b-a + 1 times. Thus:
2*res = (b-a + 1)*(a+b)
As we want to find what res is, we can divide both sides by 2 to get:
res = (b-a + 1)*(a+b)/2
So, we can use the above equation to find the sum of numbers between two numbers a and b, where a is the smaller number and b is the larger number.
Using both Math.max(), Math.min() and the above equation, we can do this using the following:
const sumRange = (a, b) => ((b - a + 1)*(a + b))/2;
function sumAll(arr) {
const smaller = Math.min(...arr);
const bigger = Math.max(...arr);
return sumRange(smaller, bigger);
}
console.log(sumAll([4, 1]));
You could do this a number of ways, in this case I am using a while loop.
function sumAll(arr) {
// Get the min/max values from the array,
// Note: you have to spread the array values as individual args using '...' notation
const min = Math.min(...arr);
const max = Math.max(...arr);
// Start at the min value
let current = min;
let sum = 0;
// Loop through all numbers between min and max inclusively
while (current <= max) {
sum += current;
current++;
}
return sum;
};
console.log(sumAll([1, 4]));
You can just find the lower number before running the loop for getting the sum of all inbetween numbers.
You can just add the condition:
if(arr[0]<arr[1]){
first= arr[0], last= arr[1]
}
else {
first=arr[1], last=arr[0] }
for (i = first; i <= last; i++){
let temp = temp + i;
}
return temp;
}
Just sort the array and run the loop to add the number , starting from first element ending at second element
function findSum(arr){
let sortedArr = arr.slice().sort((a,b) => a-b);
let total =0;
for(let i=arr[0];i<=arr[1];i++){
total+=i;
}
console.log(total);
}
findSum([1,4])
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
points[0]; // this is min value of the array values
You can check this link on w3schools

prevent rendering to page of duplicate random number generated when min and max are user defined [duplicate]

I ran into the challenge where I need a function that returns a random number within a given range from 0 - X. Not only that, but I require the number returned to be unique; not duplicating numbers that have already been returned on previous calls to the function.
Optionally, when this is done (e.g. the range has been 'exhausted'), just return a random number within the range.
How would one go about doing this?
This should do it:
function makeRandomRange(x) {
var used = new Array(x),
exhausted = false;
return function getRandom() {
var random = Math.floor(Math.random() * x);
if (exhausted) {
return random;
} else {
for (var i=0; i<x; i++) {
random = (random + 1) % x;
if (random in used)
continue;
used[random] = true;
return random;
}
// no free place found
exhausted = true;
used = null; // free memory
return random;
}
};
}
Usage:
var generate = makeRandomRange(20);
var x1 = generate(),
x2 = generate(),
...
Although it works, it has no good performance when the x-th random is generated - it searches the whole list for a free place. This algorithm, a step-by-step Fisher–Yates shuffle, from the question Unique (non-repeating) random numbers in O(1)?, will perform better:
function makeRandomRange(x) {
var range = new Array(x),
pointer = x;
return function getRandom() {
pointer = (pointer-1+x) % x;
var random = Math.floor(Math.random() * pointer);
var num = (random in range) ? range[random] : random;
range[random] = (pointer in range) ? range[pointer] : pointer;
return range[pointer] = num;
};
}
(Demo at jsfiddle.net)
Extended version which does only generate one "group" of unique numbers:
function makeRandomRange(x) {
var range = new Array(x),
pointer = x;
return function getRandom() {
if (range) {
pointer--;
var random = Math.floor(Math.random() * pointer);
var num = (random in range) ? range[random] : random;
range[random] = (pointer in range) ? range[pointer] : pointer;
range[pointer] = num;
if (pointer <= 0) { // first x numbers had been unique
range = null; // free memory;
}
return num;
} else {
return Math.floor(Math.random() * x);
}
};
}
(Demo)
You got some great programming answer. Here's one with a more theoretical flavor to complete your panorama :-)
Your problem is called "sampling" or "subset sampling" and there are several ways you could do this. Let N be the range you are sampling frame (i.e., N=X+1) and M be the size of your sample (the number of elements you want to pick).
if N is much larger than M, you'll want to use an algorithm such as the one suggested by Bentley and Floyd in his column "Programming Pearls: a sample of brilliance" (temporarily available without ACM's lock screen here), I really recommend this as they explicitly give code and discuss in terms of hash tables, etc.; there a few neat tricks in there
if N is within the same range as M, then you might want to use the Fisher-Yates shuffle but stop after only M steps (instead of N)
if you don't really know then the algorithm on page 647 of Devroye's book on random generation is pretty fast.
I wrote this function. It keeps its own array with a history of generated numbers, preventing initial duplicates, continuing to output a random number if all numbers in the range have been outputted once:
// Generates a unique number from a range
// keeps track of generated numbers in a history array
// if all numbers in the range have been returned once, keep outputting random numbers within the range
var UniqueRandom = { NumHistory: new Array(), generate: function(maxNum) {
var current = Math.round(Math.random()*(maxNum-1));
if (maxNum > 1 && this.NumHistory.length > 0) {
if (this.NumHistory.length != maxNum) {
while($.inArray(current, this.NumHistory) != -1) { current = Math.round(Math.random()*(maxNum-1)); }
this.NumHistory.push(current);
return current;
} else {
//unique numbers done, continue outputting random numbers, or we could reset the history array (NumHistory = [];)
return current;
}
} else {
//first time only
this.NumHistory.push(current);
return current;
}
}
};
Here's a working Fiddle
I hope this is of use to someone!
Edit: as pointed out by Pointy below, it might get slow with a large range (here is a
fiddle, going over a range from 0-1000, which seems to run fine). However; I didn't require a very large range, so perhaps this function is indeed not suited if you look to generate and keep track of an enormous range.
You may try generating the number using the current date and time value which would make it unique. To make it within the range, you may have to use some mathematical function.

Coin Change Algorithm JS

I have been trying to come up with a solution for this algorithm for 3-4 days but nothing seems to work and the available solutions are a bit more advanced for me. It has to be solved with conditionals only so no recursion or dynamic programming.
I need to determine the least amount of coins necessary to give change given the following denominations: 1, 0.5, 0.2, 0.1, 0.05, 0.02 and 0.01.
Input is the following:
Price of an item
Sum paid by customer
Current ideas:
let price = +gets();
let paidSum = +gets();
//gets is used to accept number input
let change = paidSum - price;
I figured I could use Math.floor to isolate the integer part and subtract it but then I have no idea what to do with the remaining sum.
Would modulo work to test whether the remaining sum contains any of the remaining values for change and then subtract again until I reach zero?
I do realize this isn't the best formulated question but I am at a loss here and I've done every other task apart from this. Thanks.
Simpler, reverse and map the denominations in cents and return a new array with the number of coins you need for each denomination.
const coinsCents = [1, 2, 5, 10, 20, 50, 100]
const getChange = (amountInCents) => {
return coinsCents.reverse().map(coin => {
let amountCoin = Math.floor(amountInCents/coin)
amountInCents -= amountCoin * coin
return amountCoin
}).reverse()
}
With the denominations you have specified, the problem is simpler than the general change making problem. In this actual case we can be sure that using the largest denomination, that is not greater than the amount to pay, always leads to an optimal solution.
So then there is no need for recursion or dynamic programming. Just a simple loop will do.
I will here ignore the additional "layer" of getting the price of the bill and the amount that the customer pays. In the end the only thing that counts is the change amount to pay back to the customer. So this snippet asks for that change amount and returns the coins that need to be given as change.
function getChange(amount) {
amount *= 100; // Convert to number of cents
var denominations = [1, 2, 5, 10, 20, 50, 100]; // cents
var result = [];
while (amount > 0) {
var coin = denominations.pop(); // Get next greatest coin
var count = Math.floor(amount/coin); // See how many times I need that coin
amount -= count * coin; // Reduce the amount with that number of coins
if (count) result.push([coin/100, count]); // Store count & coin
}
return result;
}
// I/O management
change.oninput = function () {
var coins = getChange(this.value);
result.textContent = coins.map(([coin, count]) => `${count} x $${coin}`).join(" + ");
};
To be paid to customer: <input id="change">
<div>Coins to pay: <span id="result"></span></div>
var coins;
var coinArray = {};
var output = {};
/* Method to get coin value without decimal point - it is required because
* javascript will consider 5.6 as 6 if we do Math.round()
*/
function getRoundFigureCoinValue(x) {
return (x * 10 - ((x * 10) % 10)) / 10;
}
// Method to calculate possible combination of coins
function calculateCoins(input) {
let largestPossibleCoin = 1;
if (input) {
coins.forEach((x) => {
if (input >= x) {
largestPossibleCoin = x;
}
});
let remainingCents = input % largestPossibleCoin;
output[largestPossibleCoin] = getRoundFigureCoinValue(
(input / largestPossibleCoin).toFixed(1)
);
if (remainingCents && input > 1) {
calculateCoins(remainingCents);
}
return largestPossibleCoin;
}
}
// Method to be called to get output.
function calculatePossibleCoinCombinations(value) {
if (isNaN(value) || +value <= 0) {
console.log('Invalid input');
return;
} else {
console.log('Possible combinations are:')
value = +value;
}
coins = [1, 5, 10, 25];
while (coins.length) {
let largestPossibleCoin = calculateCoins(value) || 0;
let outputString = '';
coins = coins.filter((x) => x < largestPossibleCoin);
Object.keys(output).forEach((key) => {
outputString += `${output[key]} - ${key} cents; `;
})
console.log(outputString);
output = {};
}
}
/*
Sample inputs:
calculatePossibleCoinCombinations('89');
calculatePossibleCoinCombinations(10);
calculatePossibleCoinCombinations(0);
calculatePossibleCoinCombinations('someString');
calculatePossibleCoinCombinations(-10)
*/

Categories