Divide / Hand out random amount - javascript

Lets say I have 8 people and 5000 apples.
I want to hand out all the apples to all 8 people so i have no apples left.But everyone should get a different amount
What would be the best way to give them all out?
I started of with this:
let people = 8
let apples = 5000
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
while (people--) {
// last person get the rest
let x = people ? getRandomInt(0, apples) : apples
// subtract how many apples i got left
apples -= x
console.log(`Giving person ${people + 1} ${x} apples (got ${apples} left)`)
}
But the thing I don't like about this is that the last person get very few apples (sometimes less then 5 apples) and the first person gets way more then the others

If you need random yet 'balanced' results each time, you need to prioritize either balance - or randomness. Here's one possible solution following your 'widestGap' requirement:
function randomDeltas(length, widestGap, remToGet) {
// widestGap >= length * 2 - 1
let deltas = [];
let sum = 0;
let start = 0;
let origLength = length;
while (length--) {
start += 1 + Math.floor(Math.random() * widestGap);
deltas.push(start);
sum += start;
}
let rem = sum % origLength;
let correction = remToGet - rem;
if (correction !== 0) {
sum -= deltas[0];
deltas[0] += correction;
if (deltas[0] >= deltas[1]) {
deltas[0] -= origLength;
}
else if (deltas[0] < deltas[1] - widestGap) {
deltas[0] += origLength;
}
sum += deltas[0];
}
return {
deltas,
sum
};
}
function randomDistinctDistribute(apples, people) {
let rem = apples % people;
let { deltas, sum } = randomDeltas(people, people * 2 - 1, rem);
let div = (apples - sum) / people;
let distribution = [];
while (deltas.length) {
distribution.push(div + deltas.shift());
}
return distribution;
}
console.log(randomDistinctDistribute(5000, 8));
console.log(randomDistinctDistribute(2500, 6));
Here the idea is to randomize the deltas (to make sure that gap never becomes big), then apply those deltas to divisor.
Here's the original (deterministic) approach to get balanced distribution with distinct values:
function distinctDividents(apples, people) {
let distribution = [];
let div = Math.floor(apples / people);
let rem = apples % people;
if (people % 2) {
distribution.push(div);
people--;
}
let half = people / 2;
let i = 1;
while (i <= half) {
distribution.push(div - i);
distribution.unshift(div + i);
i++;
}
if (rem) {
distribution[0] += rem;
}
return distribution;
}
console.log(distinctDividents(5000, 8));

Think I figure it out. Was just a little tweeking.
let x = people ? getRandomInt(0, Math.floor(apples / people)) : apples
let people = 8
let apples = 5000
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
while (people--) {
// last person get the rest
let x = people ? getRandomInt(0, Math.floor(apples / people)) : apples
// subtract how many apples i got left
apples -= x
console.log(`Giving person ${people + 1} ${x} apples (got ${apples} left)`)
}
Still which nobody got less then 100 apples or more then 1000 but this will do. Otherwise it get just more complex. the next day i may only have 2500 apples and 6 people...

Related

How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?

How do i create a function, which takes one parameter - a number, and returns the sum of numbers from 1 -> number - without creating an infinite loop?
Example:
function(100)
= 5050
Ive come as far as creating a finite for loop as so:
let sum = 0
for (let i = 1; i <= 100; i++) {
sum = sum + i;
//thanks in advance
Well, it looks like you've got the basic premise sussed out for 1 to 100 - you're cycling through to the value and summing up. To put it into a bit of a nicer format:
const n = 100;
console.log(GetSumTo(n))
function GetSumTo(x) {
var sum = 0;
for (var i = 1; i <= x; i++) {
sum = sum + i;
}
return sum;
}
Another option would be do it recursively:
const n = 100;
console.log(RecursiveSum(n, 0));
function RecursiveSum(val, sum) {
if (val > 1) {
sum = val + RecursiveSum(val - 1, sum);
}
else {
sum = val;
}
return sum;
}
However, these can be time consuming when dealing with large values. Using a fancy bit of maths (explained here better than I can explain it: https://math.stackexchange.com/questions/1100897/sum-of-consecutive-numbers), we can find that the sum of consecutive numbers can be calculated with an easier formula: (n(n + 1))/2
Meaning we can just write a function to do that and save execution time:
const n = 100;
console.log(QuickSum(n));
function QuickSum(n) {
var sum = n + 1;
sum = sum * n;
sum = sum / 2; //You could shrink the calculation to sum = (n * (n + 1)) / 2 I just did it over a few lines for readability
return sum;
};
None of these options result in an infinite loop.

How to generated N numbers in array that sum of these numbers is equal to 0

I have a code like this:
function myArr(N){
let arr = [];
function randomNumber(min,max) {
if (min > max) {
let vMin = min;
min = parseInt(max,10);
max = parseInt(vMin,10);
}
return Math.floor(Math.random()*(max-min+1)+min);
}
for(let i = 0; i < N; i++) {
arr.push(randomNumber(100,-100));
}
return arr;
}
This function generates an array with N numbers. But I want that the sum of these generated numbers will be equal to 0. How to make it? I was thinking about conditional 'if' but I don't exactly know, how to use it in this case ... Maybe some of you know, how to do this? Thanks for any tips!
There are many ways to generate an array of randomly-generated values that add up to zero, but they all have different implications for the distribution of values.
For example, one simple approach is to first generate the values and compute their average, and then subtract that average from each value. The consequence of this is that the values may end up outside the range you originally wanted; for example, if you randomly generate [100, 100, 100, -100], then the average is 50, so you'd end up with [50, 50, 50, -150]. You can compensate for that by starting out with a narrower range than you really need; but then that means that values in or near that narrower range will be much more likely to appear than values near the end of your full range.
Another simple approach is to generate only n/2 values, and for each value that you generate, to include both that value and its arithmetic inverse (e.g., if you generate 37, then your result will include both 37 and -37). You can then randomly shuffle the result; so, for example, if you randomly generate [17, -84, 12], then your final array might be [-12, 17, -84, -17, 84, 12].
. . . all of which is to say that you need to figure out your precise requirements. Randomness is complicated!
While generating numbers you have to make sure that the numbers stay close to zero, then you generate N - 1 numbers and calculate the last one:
const arr = [];
let sum = 0;
for(let i = 0; i < N - 2; i++) {
let number;
if(sum >= 100) {
number = randomNumber(100 - sum, -100);
} else if(sum <= -100) {
number = randomNumber(100, -100 - sum);
} else {
number = randomNumber(100, -100);
}
sum += number;
arr.push(number);
}
arr.push(Math.floor(-sum / 2), Math ceil(-sum / 2));
Try it
(Won't work well for N < 4)
Here's another way. Start with zero and split a random array element N-1 times:
function myArr(N){
let arr = [0];
function randomNumber(min,max) {
if (min > max) {
let vMin = min;
min = parseInt(max,10);
max = parseInt(vMin,10);
}
return Math.floor(Math.random()*(max-min+1)+min);
}
function split(n){
let low = Math.max(-100, n - 100);
let high = Math.min(100, n + 100);
let r = randomNumber(low, high);
return [r, n - r]
}
for(let i = 0; i < N-1; i++) {
let idx = ~~(Math.random() * arr.length);
let newNums = split(arr[idx]);
arr[idx] = newNums[0];
arr.push(newNums[1]);
}
return arr;
}
console.log(myArr(5));
This is my solution, basically you do a for loop and start adding elements.
Whenever you add an element, just add the same element * -1
You will end up with an array of elements with sum 0.
function arrayOfSumZero(N) {
let sum = 0;
let i = N % 2 === 0 ? 0 : 1;
let output = [];
for (i; i < N; i++) {
if (output.length < N) {
sum += i;
output.push(i);
}
if (sum > 0) {
sum += i * -1;
output.push(i * -1);
}
}
return output;
}

How to divide number n in javascript into x parts, where the sum of all the parts equals the number?

I have a number which I need to divide into 5 parts. However, I want each part to be a random number. But when all the parts are added together, they equal the original number. I am unsure of how to do this with JavaScript. Furthermore, I don't want the min of the divided parts to be 0 or 1, I want to set the min myself.
For example, the number is 450. I want the divided parts to be no less than 60. So to start, the array would be [60,60,60,60,60]. But I want to randomize so that they all add up to 450. What would be the best way to go about doing this?
Thank you!
This is what I've tried so far:
let i = 0;
let number = 450;
let numArray = [];
while(i <= 5){
while(number > 0) {
let randomNum = Math.round(Math.random() * number) + 1;
numArray.push(randomNum);
number -= randomNum;
}
i += 1;
}
let your number be N, and let pn be the nth part. To get 5 parts:
p1 = random number between 0 and N
p2 = random number between 0 and N - p1
p3 = random number between 0 and N - p2 - p1
p4 = random number between 0 and N - p3 - p2 - p1
p5 = N - p4 - p3 - p2 - p1
Edit 2017
To make it seem more random, shuffle the numbers after you generate them
Edit 2020
I guess some code wouldn't hurt. Using ES7 generators:
function* splitNParts(num, parts) {
let sumParts = 0;
for (let i = 0; i < parts - 1; i++) {
const pn = Math.ceil(Math.random() * (num - sumParts))
yield pn
sumParts += pn
}
yield num - sumParts;
}
Fiddle Link
Sum the five minimums (eg min = 60) up:
var minSum = 5 * min
Then get the difference between your original number (orNumber = 450) and minSum.
var delta = orNumber - minSum
Now you get 4 different random numbers in the range from 0 to exclusive 1.
Sort these numbers ascending.
Foreach of these randoms do the following:
Subtract it from the last one (or zero for the first)
Multiply this number with the delta and you get one of the parts.
The last part is the delta minus all other parts.
Afterwards you just have to add your min to all of the parts.
This function generates random numbers from 0 to 1, adds them together to figure out what they need to be multiplied by to provide the correct range. It has the benefit of all the numbers being fairly distributed.
function divvy(number, parts, min) {
var randombit = number - min * parts;
var out = [];
for (var i=0; i < parts; i++) {
out.push(Math.random());
}
var mult = randombit / out.reduce(function (a,b) {return a+b;});
return out.map(function (el) { return el * mult + min; });
}
var d = divvy(450, 6, 60)
console.log(d);
console.log("sum - " + d.reduce(function(a,b){return a+b}));
You can use a do..while loop to subtract a minimum number from original number, keep a copy of original number for subtraction at conclusion of loop to push the remainder to the array
let [n, total, m = n] = [450, 0];
const [min, arr] = [60, []];
do {
n -= min; // subtract `min` from `n`
arr.push(n > min ? min : m - total); // push `min` or remainder
total += arr[arr.length - 1]; // keep track of total
} while (n > min);
console.log(arr);
To randomize output at resulting array select a number greater than min and less than n to create a random number within a specific range
let [n, total, m = n] = [450, 0];
const [min, arr, range = min + min / 2] = [60, []];
do {
let r = Math.random() * (range - min) + min; // random number in our range
n -= r; // subtract `min` from `n`
arr.push(n > min ? r : m - total); // push `r` or remainder
total += arr[arr.length - 1]; // keep track of total
} while (n > min);
console.log(arr);
I made a longer version for beginners.
const n = 450;
const iterations = 5;
const parts = [];
// we'll use this to store what's left on each iteration
let remainder = n;
for (let i = 1; i <= iterations; i += 1) {
// if it's the last iteration, we should just use whatever
// is left after removing all the other random numbers
// from our 450
if (i === iterations) {
parts.push(remainder);
break;
}
// every time we loop, a random number is created.
// on the first iteration, the remainder is still 450
const part = Math.round(Math.random() * remainder);
parts.push(part);
// we must store how much is left after our random numbers
// are deducted from our 450. we will use the lower number
// to calculate the next random number
remainder -= part;
}
// let's print out the array and the proof it still adds up
const total = totalFromParts(parts);
console.log(parts);
console.log('Total is still ' + total);
// this function loops through each array item, and adds it to the last
// just here to test the result
function totalFromParts(parts) {
return parts.reduce((sum, value) => sum + value, 0);
}
There are much more efficient ways to code this, but in the interest of explaining the logic of solving the problem, this walks through that step by step, transforming the values and explaining the logic.
// Set start number, number of fragments
// minimum fragment size, define fragments array
var n = 450
var x = 5
var minNumber = 60
var fragment = n / x
// stuff array with equal sized fragment values
var fragments = []
for (i = 0; i < x; i++) {
fragments[i] = fragment;
}
document.write("fragments: " + fragments);
var delta = [];
// iterate through fragments array
// get a random number each time between the fragment size
// and the minimum fragment sized defined above
// for even array slots, subtract the value from the fragment
// for odd array slots, add the value to the fragment
// skip the first [0] value
for (i = 1; i< x; i++) {
delta[i] = Math.floor(Math.random() * (fragment - minNumber));
document.write("<br />delta: " + delta[i]);
if((i % 2) == 1) {
fragments[i] -= delta[i]
}
else {
fragments[i] += delta[i]
}
}
// set the initial fragment value to 0
fragments[0] = 0
// defines a function we can use to total the array values
function getSum(total, num) {
return total + num;
}
// get the total of the array values, remembering the first is 0
var partialTotal = fragments.reduce(getSum)
document.write("<br />partial sum: " + partialTotal);
// set the first array value to the difference between
// the total of all the other array values and the original
// number the array was to sum up to
fragments[0] = (n - partialTotal)
// write the values out and profit.
document.write("<br />fragments: " + fragments);
var grandTotal = fragments.reduce(getSum)
document.write("<br />Grand total: " + grandTotal);
https://plnkr.co/edit/oToZe7LGpQS4dIVgYHPi?p=preview

Calculating Pi in JavaScript using Gregory-Leibniz Series

I have to calculate value of Pi using Gregory-Leibniz series:
pi = 4 * ((1/1 - 1/3) + (1/5 - 1/7) + (1/9 - 1/11) + ...)
I want to write a function in JavaScript that would take the number of digits that needs to be displayed as an argument. But I'm not sure if my way of thinking is fine here.
This is what I got so far:
function pi(n) {
var pi = 0;
for (i=1; i <= n; i+2) {
pi = 4 * ((1/i) + (1/(i+2)))
}
return pi;
}
How do I write the pi calculation so it calculates values till n?
You could use an increment of 4 and multiply at the end of the function with 4.
n is not the number of digits, but the counter of the value of the series.
function pi(n) {
var v = 0;
for (i = 1; i <= n; i += 4) { // increment by 4
v += 1 / i - 1 / (i + 2); // add the value of the series
}
return 4 * v; // apply the factor at last
}
console.log(pi(1000000000));
You may also do as follows; The function will iterate 10M times and will return you PI with n significant digits after the decimal point.
function getPI(n){
var i = 1,
p = 0;
while (i < 50000000){
p += 1/i - 1/(i+2);
i += 4;
}
return +(4*p).toFixed(n);
}
var myPI = getPI(10);
console.log("myPI #n:100M:", myPI);
console.log("Math.PI :", Math.PI);
console.log("The Diff :", Math.PI-myPI);

In javascript, how do I add a random amount to a user's balance while controlling how much gets given total?

I'm trying to make it to where when a user does a certain thing, they get between 2 and 100 units. But for every 1,000 requests I want it to add up to 3,500 units given collectively.
Here's the code I have for adding different amounts randomly to a user:
if (Math.floor(Math.random() * 1000) + 1 === 900) {
//db call adding 100
}
else if (Math.floor(Math.random() * 100) + 1 === 90) {
//db call adding 40
}
else if (Math.floor(Math.random() * 30) + 1 === 20) {
//db call adding 10
}
else if (Math.floor(Math.random() * 5) + 1 === 4) {
//db call adding 5
}
else {
//db call adding 2
}
If my math is correct, this should average around 4,332 units per 1,000 calls. But obviously it would vary and I don't want that. I'd also like it to add random amounts instead, as the units added in my example are arbitrary.
EDIT: Guys, Gildor is right that I simply want to have 3,500 units, and give them away within 1,000 requests. It isn't even entirely necessary that it always reaches that maximum of 3,500 either (I could have specified that). The important thing is that I'm not giving users too much, while creating a chance for them to win a bigger amount.
Here's what I have set up now, and it's working well, and will work even better with some tweaking:
Outside of call:
var remaining = 150;
var count = 0;
Inside of call:
count += 1;
if (count === 100) {
remaining = 150;
count = 0;
}
if (Math.floor(Math.random() * 30) + 1 === 20) {
var addAmount = Math.floor(Math.random() * 85) + 15;
if (addAmount <= remaining) {
remaining -= addAmount;
//db call adding addAmount + 2
}
else {
//db call adding 2
}
}
else if (Math.floor(Math.random() * 5) + 1 === 4) {
var addAmount1 = Math.floor(Math.random() * 10) + 1;
if (addAmount1 <= remaining) {
remaining -= addAmount1;
//db call adding addAmount1 + 2
}
else {
//db call adding 2
}
}
else {
//db call adding 2
}
I guess I should have clarified, I want a "random" number with a high likelihood of being small. That's kind of part of the gimmick, where you have low probability of getting a larger amount.
As I've commented, 1,000 random numbers between 2 and 100 that add up to 3,500 is an average number of 3.5 which is not consistent with random choices between 2 and 100. You'd have to have nearly all 2 and 3 values in order to achieve that and, in fact couldn't have more than a couple large numbers. Nothing even close to random. So, for this to even be remotely random and feasible, you'd have to pick a total much large than 3,500. A random total of 1,000 numbers between 2 and 100 would be more like 51,000.
Furthermore, you can't dynamically generate each number in a truly random fashion and guarantee a particular total. The main way to guarantee that outcome is to pre-allocate random numbers that add up to the total that are known to achieve that and then random select each number from the pre-allocated scheme, then remove that from the choice for future selections.
You could also try to keep a running total and bias your randomness if you get skewed away form your total, but doing it that way, the last set of numbers may have to be not even close to random in order to hit your total consistently.
A scheme that could work if you reset the total to support what it should be for actual randomness (e.g. to 51,000) would be to preallocated an array of 500 random numbers between 2 and 100 and then add another 500 numbers that are the complements of those. This guarantees the 51 avg number. You can then select each number randomly from the pre-allocated array and then remove it form the array so it won't be selected again. I can add code to do this in a second.
function RandResults(low, high, qty) {
var results = new Array(qty);
var limit = qty/2;
var avg = (low + high) / 2;
for (var i = 0; i < limit; i++) {
results[i] = Math.floor((Math.random() * (high - low)) + low);
//
results[qty - i - 1] = (2 * avg) - results[i];
}
this.results = results;
}
RandResults.prototype.getRand = function() {
if (!this.results.length) {
throw new Error("getRand() called, but results are empty");
}
var randIndex = Math.floor(Math.random() * this.results.length);
var value = this.results[randIndex];
this.results.splice(randIndex, 1);
return value;
}
RandResults.prototype.getRemaining = function() {
return this.results.length;
}
var randObj = new RandResults(2, 100, 1000);
// get next single random value
if (randObj.getRemaining()) {
var randomValue = randObj.getRand();
}
Working demo for a truly random selection of numbers that add up to 51,000 (which is what 1,000 random values between 2 and 100 should add up to): http://jsfiddle.net/jfriend00/wga26n7p/
If what you want is the following: 1,000 numbers that add up to 3,500 and are selected from between the range 2 to 100 (inclusive) where most numbers will be 2 or 3, but occasionally something could be up to 100, then that's a different problem. I wouldn't really use the word random to describe it because it's a highly biased selection.
Here's a way to do that. It generates 1,000 random numbers between 2 and 100, keeping track of the total. Then, afterwards it corrects the random numbers to hit the right total by randomly selected values and decrementing them until the total is down to 3,500. You can see it work here: http://jsfiddle.net/jfriend00/m4ouonj4/
The main part of the code is this:
function RandResults(low, high, qty, total) {
var results = new Array(qty);
var runningTotal = 0, correction, index, trial;
for (var i = 0; i < qty; i++) {
runningTotal += results[i] = Math.floor((Math.random() * (high - low)) + low);
}
// now, correct to hit the total
if (runningTotal > total) {
correction = -1;
} else if (runningTotal < total) {
correction = 1;
}
// loop until we've hit the total
// randomly select a value to apply the correction to
while (runningTotal !== total) {
index = Math.floor(Math.random() * qty);
trial = results[index] + correction;
if (trial >= low && trial <= high) {
results[index] = trial;
runningTotal += correction;
}
}
this.results = results;
}
This meets an objective of a biased total of 3,500 and all numbers between 2 and 100, though the probability of a 2 in this scheme is very high and the probably of a 100 in this scheme is almost non-existent.
And, here's a weighted random generator that adds up to a precise total. This uses a cubic weighting scheme to favor the lower numbers (the probably of a number goes down with the cube of the number) and then after the random numbers are generated, a correction algorithm applies random corrections to the numbers to make the total come out exactly as specified. The code for a working demo is here: http://jsfiddle.net/jfriend00/g6mds8rr/
function RandResults(low, high, numPicks, total) {
var avg = total / numPicks;
var i, j;
// calculate probabilities for each value
// by trial and error, we found that a cubic weighting
// gives an approximately correct sub-total that can then
// be corrected to the exact total
var numBuckets = high - low + 1;
var item;
var probabilities = [];
for (i = 0; i < numBuckets; i++) {
item = low + i;
probabilities[i] = avg / (item * item * item);
}
// now using those probabilities, create a steps array
var sum = 0;
var steps = probabilities.map(function(item) {
sum += item;
return sum;
});
// now generate a random number and find what
// index it belongs to in the steps array
// and use that as our pick
var runningTotal = 0, rand;
var picks = [], pick, stepsLen = steps.length;
for (i = 0; i < numPicks; i++) {
rand = Math.random() * sum;
for (j = 0; j < stepsLen; j++) {
if (steps[j] >= rand) {
pick = j + low;
picks.push(pick);
runningTotal += pick;
break;
}
}
}
var correction;
// now run our correction algorithm to hit the total exactly
if (runningTotal > total) {
correction = -1;
} else if (runningTotal < total) {
correction = 1;
}
// loop until we've hit the total
// randomly select a value to apply the correction to
while (runningTotal !== total) {
index = Math.floor(Math.random() * numPicks);
trial = picks[index] + correction;
if (trial >= low && trial <= high) {
picks[index] = trial;
runningTotal += correction;
}
}
this.results = picks;
}
RandResults.prototype.getRand = function() {
if (!this.results.length) {
throw new Error("getRand() called, but results are empty");
}
return this.results.pop();
}
RandResults.prototype.getAllRand = function() {
if (!this.results.length) {
throw new Error("getAllRand() called, but results are empty");
}
var r = this.results;
this.results = [];
return r;
}
RandResults.prototype.getRemaining = function() {
return this.results.length;
}
As some comments pointed out... the numbers in the question does not quite make sense, but conceptually there are two approaches: calculate dynamically just in time or ahead of time.
To calculate just in time:
You can maintain a remaining variable which tracks how many of 3500 left. Each time when you randomly give some units, subtract the number from remaining until it goes to 0.
In addition, to make sure each time at least 2 units are given, you can start with remaining = 1500 and give random + 2 units each time.
To prevent cases that after 1000 gives there are still balances left, you may need to add some logic to give units more aggressively towards the last few times. However it will result in not-so-random results.
To calculate ahead of time:
Generate a random list with 1000 values in [2, 100] and sums up to 3500. Then shuffle the list. Each time you want to give some units, pick the next item in the array. After 1000 gives, generate another list in the same way. This way you get much better randomized results.
Be aware that both approaches requires some kind of shared state that needs to be handled carefully in a multi-threaded environment.
Hope the ideas help.

Categories

Resources