Do a calculation x times depending on a value - javascript

Math.floor((1600 * Math.pow(1.4, 19))); // = 956208
Im doing a fansite for a game and im trying to make a calculation how how much mana you need to get + skill the formula above calculates from 19-20 skill
but i need to loop the calculation x amount of times so you can calculate from x (19 in the calculation above) to y need to raise x+1 each time until it reaches the final value y and add up the answeres from each loop like below
i have 2 text boxes that i take the values from
956208+1338692+1874168+2623836+3673371+5142719 = 15608994 so it would end up doing something like that thats from 19 to 25

If I am understanding the problem correctly (it's a bit unclear...) you want something like this.
var from = 19;
var to = 25;
var totalMana = 0;
for (var i = from; i <= to; i++) {
totalMana += Math.floor(1600 * Math.pow(1.4, i));
}
console.log(totalMana); // 22,808,801
You simply loop from your lower value, through to your upper value, evaluating your formula each time and adding it to a accumulation variable that persists through each iteration.
Also, just so you know, you are dipping your toe in calculus. You are getting the summation of a finite series. Math is fun, even if you dont know your doing it :)

Gonna throw this answer in for fun:
// generate an array with each value in the series, where callback evaluates
// the value at each step
Math.series = function(from, to, callback){
var out = [];
for (var i = from; i <= to; i++)
out.push(callback.call(null, i));
return out;
};
// add the things in an array.
Math.sum = function(arr){
var sum = 0;
for (var i = 0; i < arr.length; i++)
sum += +arr[i];
return sum;
};
With these utility functions, you can accomplish your task in a one-liner like so:
Math.sum(Math.series(19,25,function(i){return Math.floor(1600*Math.pow(1.4,i));}));

Related

Trying to optimize my code to either remove nested loop or make it more efficient

A friend of mine takes a sequence of numbers from 1 to n (where n > 0)
Within that sequence, he chooses two numbers, a and b
He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b
Given a number n, could you tell me the numbers he excluded from the sequence?
Have found the solution to this Kata from Code Wars but it times out (After 12 seconds) in the editor when I run it; any ideas as too how I should further optimize the nested for loop and or remove it?
function removeNb(n) {
var nArray = [];
var sum = 0;
var answersArray = [];
for (let i = 1; i <= n; i++) {
nArray.push(n - (n - i));
sum += i;
}
var length = nArray.length;
for (let i = Math.round(n / 2); i < length; i++) {
for (let y = Math.round(n / 2); y < length; y++) {
if (i != y) {
if (i * y === sum - i - y) {
answersArray.push([i, y]);
break;
}
}
}
}
return answersArray;
}
console.log(removeNb(102));
.as-console-wrapper { max-height: 100% !important; top: 0; }
I think there is no reason for calculating the sum after you fill the array, you can do that while filling it.
function removeNb(n) {
let nArray = [];
let sum = 0;
for(let i = 1; i <= n; i++) {
nArray.push(i);
sum += i;
}
}
And since there could be only two numbers a and b as the inputs for the formula a * b = sum - a - b, there could be only one possible value for each of them. So, there's no need to continue the loop when you find them.
if(i*y === sum - i - y) {
answersArray.push([i,y]);
break;
}
I recommend looking at the problem in another way.
You are trying to find two numbers a and b using this formula a * b = sum - a - b.
Why not reduce the formula like this:
a * b + a = sum - b
a ( b + 1 ) = sum - b
a = (sum - b) / ( b + 1 )
Then you only need one for loop that produces the value of b, check if (sum - b) is divisible by ( b + 1 ) and if the division produces a number that is less than n.
for(let i = 1; i <= n; i++) {
let eq1 = sum - i;
let eq2 = i + 1;
if (eq1 % eq2 === 0) {
let a = eq1 / eq2;
if (a < n && a != i) {
return [[a, b], [b, a]];
}
}
}
You can solve this in linear time with two pointers method (page 77 in the book).
In order to gain intuition towards a solution, let's start thinking about this part of your code:
for(let i = Math.round(n/2); i < length; i++) {
for(let y = Math.round(n/2); y < length; y++) {
...
You already figured out this is the part of your code that is slow. You are trying every combination of i and y, but what if you didn't have to try every single combination?
Let's take a small example to illustrate why you don't have to try every combination.
Suppose n == 10 so we have 1 2 3 4 5 6 7 8 9 10 where sum = 55.
Suppose the first combination we tried was 1*10.
Does it make sense to try 1*9 next? Of course not, since we know that 1*10 < 55-10-1 we know we have to increase our product, not decrease it.
So let's try 2*10. Well, 20 < 55-10-2 so we still have to increase.
3*10==30 < 55-3-10==42
4*10==40 < 55-4-10==41
But then 5*10==50 > 55-5-10==40. Now we know we have to decrease our product. We could either decrease 5 or we could decrease 10, but we already know that there is no solution if we decrease 5 (since we tried that in the previous step). So the only choice is to decrease 10.
5*9==45 > 55-5-9==41. Same thing again: we have to decrease 9.
5*8==40 < 55-5-8==42. And now we have to increase again...
You can think about the above example as having 2 pointers which are initialized to the beginning and end of the sequence. At every step we either
move the left pointer towards right
or move the right pointer towards left
In the beginning the difference between pointers is n-1. At every step the difference between pointers decreases by one. We can stop when the pointers cross each other (and say that no solution can be obtained if one was not found so far). So clearly we can not do more than n computations before arriving at a solution. This is what it means to say that the solution is linear with respect to n; no matter how large n grows, we never do more than n computations. Contrast this to your original solution, where we actually end up doing n^2 computations as n grows large.
Hassan is correct, here is a full solution:
function removeNb (n) {
var a = 1;
var d = 1;
// Calculate the sum of the numbers 1-n without anything removed
var S = 0.5 * n * (2*a + (d *(n-1)));
// For each possible value of b, calculate a if it exists.
var results = [];
for (let numB = a; numB <= n; numB++) {
let eq1 = S - numB;
let eq2 = numB + 1;
if (eq1 % eq2 === 0) {
let numA = eq1 / eq2;
if (numA < n && numA != numB) {
results.push([numA, numB]);
results.push([numB, numA]);
}
}
}
return results;
}
In case it's of interest, CY Aries pointed this out:
ab + a + b = n(n + 1)/2
add 1 to both sides
ab + a + b + 1 = (n^2 + n + 2) / 2
(a + 1)(b + 1) = (n^2 + n + 2) / 2
so we're looking for factors of (n^2 + n + 2) / 2 and have some indication about the least size of the factor. This doesn't necessarily imply a great improvement in complexity for the actual search but still it's kind of cool.
This is part comment, part answer.
In engineering terms, the original function posted is using "brute force" to solve the problem, iterating every (or more than needed) possible combinations. The number of iterations is n is large - if you did all possible it would be
n * (n-1) = bazillio n
Less is More
So lets look at things that can be optimized, first some minor things, I'm a little confused about the first for loop and nArray:
// OP's code
for(let i = 1; i <= n; i++) {
nArray.push(n - (n - i));
sum += i;
}
??? You don't really use nArray for anything? Length is just n .. am I so sleep deprived I'm missing something? And while you can sum a consecutive sequence of integers 1-n by using a for loop, there is a direct and easy way that avoids a loop:
sum = ( n + 1 ) * n * 0.5 ;
THE LOOPS
// OP's loops, not optimized
for(let i = Math.round(n/2); i < length; i++) {
for(let y = Math.round(n/2); y < length; y++) {
if(i != y) {
if(i*y === sum - i - y) {
Optimization Considerations:
I see you're on the right track in a way, cutting the starting i, y values in half since the factors . But you're iterating both of them in the same direction : UP. And also, the lower numbers look like they can go a little below half of n (perhaps not because the sequence start at 1, I haven't confirmed that, but it seems the case).
Plus we want to avoid division every time we start an instantiation of the loop (i.e set the variable once, and also we're going to change it). And finally, with the IF statements, i and y will never be equal to each other the way we're going to create the loops, so that's a conditional that can vanish.
But the more important thing is the direction of transversing the loops. The smaller factor low is probably going to be close to the lowest loop value (about half of n) and the larger factor hi is probably going to be near the value of n. If we has some solid math theory that said something like "hi will never be less than 0.75n" then we could make a couple mods to take advantage of that knowledge.
The way the loops are show below, they break and iterate before the hi and low loops meet.
Moreover, it doesn't matter which loop picks the lower or higher number, so we can use this to shorten the inner loop as number pairs are tested, making the loop smaller each time. We don't want to waste time checking the same pair of numbers more than once! The lower factor's loop will start a little below half of n and go up, and the higher factor's loop will start at n and go down.
// Code Fragment, more optimized:
let nHi = n;
let low = Math.trunc( n * 0.49 );
let sum = ( n + 1 ) * n * 0.5 ;
// While Loop for the outside (incrementing) loop
while( low < nHi ) {
// FOR loop for the inside decrementing loop
for(let hi = nHi; hi > low; hi--) {
// If we're higher than the sum, we exit, decrement.
if( hi * low + hi + low > sum ) {
continue;
}
// If we're equal, then we're DONE and we write to array.
else if( hi * low + hi + low === sum) {
answersArray.push([hi, low]);
low = nHi; // Note this is if we want to end once finding one pair
break; // If you want to find ALL pairs for large numbers then replace these low = nHi; with low++;
}
// And if not, we increment the low counter and restart the hi loop from the top.
else {
low++;
break;
}
} // close for
} // close while
Tutorial:
So we set the few variables. Note that low is set slightly less than half of n, as larger numbers look like they could be a few points less. Also, we don't round, we truncate, which is essentially "always rounding down", and is slightly better for performance, (though it dosenit matter in this instance with just the single assignment).
The while loop starts at the lowest value and increments, potentially all the way up to n-1. The hi FOR loop starts at n (copied to nHi), and then decrements until the factor are found OR it intercepts at low + 1.
The conditionals:
First IF: If we're higher than the sum, we exit, decrement, and continue at a lower value for the hi factor.
ELSE IF: If we are EQUAL, then we're done, and break for lunch. We set low = nHi so that when we break out of the FOR loop, we will also exit the WHILE loop.
ELSE: If we get here it's because we're less than the sum, so we need to increment the while loop and reset the hi FOR loop to start again from n (nHi).

Sum of Odd Fibonnaci failing with Higher values?

So im running into an odd error, where im summing all fibonnaci numbers that are odd and LESS than a number.
the odd thing is this works with low values, but when I get to upper values past 10 or so.....it'll crash codepen.io
here is what I have so far:
function f(n)
{
if(n <= 1)
return n;
return f(n-1)+f(n-2);
}
function sumFibs(num) {
var counter = 0;
var arr = [];
//Get all Fibbonaci Numbers up to num
for(let i = 1;i <= num;i++)
{
arr.push(f(i));
}
for(let j = 0;j < arr.length;j++)
{
if(arr[j] % 2 != 0 && arr[j] <=num)
{
counter+= arr[j];
}
}
console.log(counter);
return counter;
}
sumFibs(10);
Basically I calculate fib up to the num and then I go through each odd one thats less than or equal to num and add those up.
Im getting correct values (IE for 10 i get 10, for 4 i get 5....etc...)
but if I put in something like 1000 it seems to just crash? and I can't seem to figure out any reason why?
The recursive f() function is a logical way to express a Fibonacci number calculation, but it isn't very efficient compared to an iterative approach, especially because you are calling it repeatedly from inside a loop. I think this is bringing your browser to a halt. Within the loop each time you call f() it is calculating the specified Fibonacci number from scratch by recursively calling itself. So, say, to get f(10), it calls itself twice with f(9) + f(8) (and then they in turn call f(8)+f(7) and f(7)+f(6), etc., so even that is pretty inefficient), but in fact you already know what f(9) and f(8) are because you've stored those values in your array on previous loop iterations.
If you change your loop to calculate each subsequent number directly rather than calling another function you get much faster code:
var arr = [1, 1]; // start with the known first two numbers
//Get all Fibbonaci Numbers up to num
for(let i = 2; i < num; i++) // start the loop at index 2 for the third number
{
arr[i] = arr[i-2] + arr[i-1];
}
With that change in place, your sumFibs() function can give you results even for sumFibs(1000000) in a matter of milliseconds:
function sumFibs(num) {
var counter = 0;
var arr = [1, 1];
//Get all Fibbonaci Numbers up to num
for (let i = 2; i < num; i++) {
arr[i] = arr[i - 2] + arr[i - 1];
}
for (let j = 0; j < arr.length; j++) {
if (arr[j] % 2 != 0) {
counter += arr[j];
}
}
return counter;
}
console.log('10: ' + sumFibs(10));
console.log('100: ' + sumFibs(100));
console.log('1000: ' + sumFibs(1000));
console.log('10000: ' + sumFibs(10000));
console.time('High fib');
console.log('1000000: ' + sumFibs(1000000));
console.timeEnd('High fib');
Note that you also had a logic error in your second loop, the one that adds up the odd numbers: the && arr[j] <=num part needed to be removed. The values in arr are the actual Fibonacci numbers, but num is the sequence number, so it doesn't make sense to be comparing them. You just want every odd number in the whole array.
However, the return value from your function is still going to be incorrect if num is too large. That's because by the time you get to the 80-somethingth Fibonacci number it is larger than JavaScript can handle without losing precision, i.e., larger than Number.MAX_SAFE_INTEGER, 9,007,199,254,740,991 (which is 2^53 - 1). Numbers above that start getting rounded so your tests for odd numbers aren't reliable and thus the total sum doesn't include all of the numbers it should have, or if you add too many JS considers your result to be Infinity.

Why does my factorial function always return one?

I am trying to write a piece of code to solve a Coderbyte challenge, to calculate a number's factorial. Every time I run it, the factorial generated is one. What am I doing wrong?
var num
var array1 = new Array();
function FirstFactorial(num) {
for (var i = num; i>0; i--){ // 8 , 7, 6 , 5
for (var y = 0; y<num ; y++){ // 0, 1, 2, 3, 4
array1[y]=i; // we have an array that looks like [8,7,6,5,4,3,2,1]
};
};
var sum = 1
for (var x = 0; x<array1.length; x++){ // now I want to run up that array, reading the #s
sum = sum * array1[x];
return sum;
};
return sum
};
A few issues.
1/ This is minor but, when you multiply two numbers, you get a product, not a sum.
2/ You returned the value from within the loop which would mean, even if you fixed the other problems, it would return prematurely without having multiplied all the numbers.
3/ Your nested loop does not fill your array the way you describe, you should check it after population. Think about your loops expressed as pseudo-code:
for i = num downto 1 inclusive:
for y = 0 to num-1 inclusive:
array1[y] = i
You can see that the inner loop is populating the entire array with the value of the current i. So the last iteration of the outer loop, where i is one, sets the entire array to ones.
4/ In any case, you don't need an array to store all the numbers from 1 to n, just use the numbers 1 to n directly. Something like (again, pseudo-code):
def fact(n):
prod = 1
for i = 2 to n inclusive:
prod = prod * i
return prod
This is a much easier way to calculate the factorial of a number.
function factorial(num)
{
if(num === 1)
{
return num;
}
return num * factorial(num - 1);
}
However to fix your code you need to fix the initial loop that loads the numbers into the array. as well as remove the return statement in the bottom loop. Like so.
function FirstFactorial(num) {
for (var i = num; i>0; i--) {
array1[num - i] = i;
};
var sum = 1
for (var x = 0; x < array1.length; x++){ // now I want to run up that array, reading the #s
sum = sum * array1[x];
};
return sum
};

d3 how to turn a set of numbers into a larger set representative of the first set

Say I have array [1,2,5,18,17,8] and I want to turn that into an array of length 40 that follows the same path.
a = [1,2,5,18,17,8];
stepSize = 1 / (40 / a.length);
then i think i could do something like
steps = [];
for( var i = 0; i < 1; i+= stepSize) {
steps.push(d3.interpolate(a[0],a[1])(i));
}
and then repeat that for all the elements. My question is there a better way to do this?
I can only guess what your real problem is but I think you want to plot these values and have a smooth curve. In that case use line.interpolate() https://github.com/mbostock/d3/wiki/SVG-Shapes#line_interpolate
In case you DO know what you need and your solution works for you, take this tip:
Never iterate over stepSize. Calculate it once and multiply it with i in every loop where i goes from 0 to 40. This way you work around precision problems.
Your algorithm cleaned up, tested and working:
var a = [1,5,12,76,1,2];
var steps = 24;
var ss = (a.length-1) / (steps-1);
var result = new Array(steps);
for (var i=0; i<steps; i++) {
var progress = ss * i;
var left = Math.floor(progress);
var right = Math.ceil(progress);
var factor = progress - left;
result[i] = (1 - factor) * a[left] + (factor) * a[right];
// alternative that actually works the same:
//result[i] = d3.interpolateNumber(a[left], a[right], factor);
}
console.log(result);

for loop variable expressions mathematical manipulating

I'm writing a program in JS and im feeling i'm repeating code, which is not good. I'm trying to avoid an if then else block that has two similar for loop and re-write it without an if then else using just one for loop.
Consider this: minimum has value 0. maximum has value 10. if new_value is less than old_value i wanna execute a for loop from minimum to new_value, else i wanna execute it from maximum DOWNto new_value
Lets see it in action, lets say javascript (language-agnostic answers are welcome and upvoted -but will not grant you an extra cookie)
var minimum = 0;
var maximum = 10;
var old_value = 5;
/* var new_value = taken from user input whatever ... */
if(new_value<old_value)
{
for(i=minimum;i<new_value;i++)
{
// whatever
}
}
else
{
for(i=maximum;i>new_value;i--)
{
// whatever
}
}
I have a feeling these two for loops are similar enough to be written as one in a mathematical approach maybe. Have tried a bit using absolute values Math.abs() Math.max.apply() but had no luck.
I don't want to set other helping variables using if then else to give appropriate values.
So, whats the question: I'm wondering if this can be rewritten in one for ... loop without being nested in an if then else.
A complete solution using built-in js functions will grant you an extra cookie.
Edit: Didn't see your original thing about not using the if/else with variables. Why not do something like this then? Just go from 0 to 10, using that value or 10 minus that value depending on the conditional.
for(var j = 0; j <= 10; j++) {
var i = new_value < old_value ? j : 10 - j;
// whatever
}
Assign your min, max and increment as variables, define them based on your if condition and then use them in the for loop:
var old_value = 5, start, end, inc;
if(new_value<old_value) {
start = 0;
end = 10;
inc = 1;
} else {
start = 10;
end = 0;
inc = -1;
}
for( i = start;i >= start && i <= end; i += inc) {
// whatever
}
You could abuse of the ternary operator just for fun:
var minimum = 0;
var maximum = 10;
var old_value = 5;
var new_value = 7;
/* var new_value = taken from user input whatever ... */
var check =(new_value<old_value);
var foo1 = function () { console.log("foo1") }
var foo2 = function () { console.log("foo2") }
for(i=check?minimum:maximum;
check?(i<new_value):(i>new_value);
check?i++:i--)
{
check?foo1():foo2();
}
Does the second loop have to iterate in reverse? If not you can simply use
var i0 = new_value<old_value ? minimum : new_value+1;
var i1 = new_value<old_value ? new_value : maximum+1;
for(i=i0;i<i1;++i)
{
//whatever
}
Edit: In the light of your comment, if you can be sure that you're dealing with integers you can use
var i0 = new_value<old_value ? minimum : maximum;
var d = new_value<old_value ? 1 : -1;
for(i=i0;i!=new_value;i+=d)
{
//whatever
}
If not
var i0 = new_value<old_value ? minimum : maximum;
var d = new_value<old_value ? 1 : -1;
for(i=i0;d*i<d*new_value;i+=d)
{
//whatever
}
I did it!
With this +(old_value>new_value) instead of getting true/false i am getting 1/0. I am using the 1 and 0 as multipliers to emulate the if then else functionality.
lets assume
var minimum = 0;
var maximum = 10;
var old_value = 5;
for(expression1;expression2;expression3)
For expression1:
if new value is bigger than old value then we need minimum
if new value is smaller than old value then we need maximum
I am multiplying be zero the maximum depending the above conditions with (maximum*(+(old_value>new_value)))
I am multiplying by zero the minimum depending the above conditions with (minimum*(+(old_value<new_value))
by adding these two the sum is what i am supposed to get! (maximum*(+(old_value>new_value)))+(minimum*(+(old_value<new_value)))
This will give minimum if new_value > old value and maximum if new_value < old_value
For expression2:
while i!=new_value; simple. (we just have to be sure the maximum is bigger than new_value and minimum is smaller than new_value or we have an endless loop.)
For expression3:
if new value is bigger than old value then we need i=i +1
if new value is smaller than old value then we need i=i -1
this
(+(old_value<new_value)+1)+(-1*(+(old_value>new_value)+1))
will give either 2+-1=1 or 1+(-2)=-1 so we simply use it in expression3 as
i=i+(+(old_value<new_value)+1)+(-1*(+(old_value>new_value)+1))
complete code:
http://jsfiddle.net/eBLat/
var minimum = 0;
var maximum = 10;
var old_value = 5;
var new_value = 3; // change this value
// if new value is bigger than old value then for loop from maximum downto new_value (dont include new value)
// if new value is smaller than old value then for loop from minimum upto new_value (dont include new value)
for(i=(maximum*(+(old_value>new_value)))+(minimum*(+(old_value<new_value)));i!=new_value;i=i+(+(old_value<new_value)+1)+(-1*(+(old_value>new_value)+1)) )
{
alert("Iteration:"+i);
}
Another question would be if this is actually better than just write two for in a if then else ... anyway i had fun. And i got the cookie :D :D
Hope someone will find useful in some way the fact that +true gives 1 and +false gives 0 in javascript

Categories

Resources