I am trying to understand superficially the syntax in this pretty piece of coding posted here:
t=0,draw=e=>{for(t++||createCanvas(w=400,w,WEBGL),background(w),fill(x=0),rotateX(d=t/120),rotateY(d),rotateZ(d);x<1331;)push(r=r=>(r-5)*(10+w*(o=1-sin(t%120/240*PI)))),translate(r(a=x%11),r(b=x%121/11|0),r(c=x++/121|0)),pop(box(10+o*(666==x?90:-10)))};//
I think that because of Twitter's constraints in number of characters it was posted as one single line, and using some shortcuts for loops. The part I am asking about may be a loop. I tried unfolding the code into something more readable as follows:
t=0,draw=e=>{for(t++||
createCanvas(w = windowWidth,w,WEBGL), background(w), fill(x=0),
rotateX(d=t/120),
rotateY(d),
rotateZ(d);
x<1331;)
push(r=r=>(r-5) * (10 + w * (z = 1 - sin(t%120/240*PI)))),
translate(r(a=x%11),
r(b=x%121/11|0),
r(c=x++/121|0)),
pop(box(10+z*(666==x?90:-10)))};//
What is r=r=>(r-5) purpose? I have looked up push() and pop(), and I have a vague idea, but that expression is confusing.
This whole callback starts at t=0,draw=e=>
This e is probably an event, the letter e is often used for event
this is a callback function, which is assigned to 'r'
r = (r) => (r * 5) * (10 + w * (z = 1 - sin(t%120/240*PI)))),
translate(r(a=x%11),
r(b=x%121/11|0),
r(c=x++/121|0)),
pop(box(10+z*(666==x'90:-10))};
it's something like
number = (num) => num * 2
number(4) // will multiply four by two
Related
I have the following function fn(n).
function fn(n) {
if (n < 0) return 0;
if (n < 2) return n;
return fn(n - 1) + fn(n - 2);
}
I understand how this code works, but don't how to calculate time complexity for it.
Let’s do some examples:
For n = 3, you have 5 function calls. First fn(3), which in turn calls fn(2) and fn(1) and so on.
For n = 4, you have 9 function calls. First fn(4), which in turn calls fn(3) and fn(2) and so on.
Graphical representation of the 2 examples:
The leftmost nodes go down in descending order: fn(4), fn(3), fn(2), fn(1), which means that the height of the tree (or the number of levels) on the tree will be n.
The time complexity of this code is 2^n - 1. Although, if we count all calls will be just 9 calls for n = 4.
And the question is how we get 2^n - 1? I don't understand
One of the ways of calculating recursive algorithm's time complexity is using the Recursion Tree Method. For this particular case, we can write T(n)=T(n-1)+T(n-2)+2*O(1), where O(1) means constant time, since we have two comparison checks of n values using if. The recursion tree would look something like this:
1 n
2 (n-1) (n-2)
4 (n-2) (n-3) (n-3) (n-4)
8 (n-3)(n-4) (n-4)(n-5) (n-4)(n-5) (n-5)(n-6)
...
2^i for i-th level
Total work done will be the sum of all of the work done in each level, so we can write T(n)=1 + 2 + 4 + 8 + 16 + 32 + ... = 2^0 + 2^1 + 2^2 + 2^3 + 2^4 + ... + 2^i. This is a geometric series which means that the T(n) is equal to (1-2^n)/(1-2) = (1-2^n)/(-1) = 2^n - 1. Because of that the time complexity of the function fn(n) is O(2^n).
You could also approach this using Back Substitution method. We know the following:
T(0)=1
T(1)=1
T(2)=1
T(n)=T(n-1)+T(n-2)+2*O(n)≈2*T(n-1)
Substituting T(n-2) with T(n-1) is allowed. In doing so you will get a higher bound which is still true for T(n-1)+T(n-2).
After the substitution you can also write T(n-1)=2*T(n-2), T(n-2)=2*T(n-3), ...
Using these values and substituting them recursively in to the T(n) you will get:
T(n)=2*2*T(n-2)
=2*2*2*T(n-3)
=2*2*2*2*T(n-4)
=...
=2^i * T(n-i)
From there you can write n-i=1 => i=n-1 and substitute the i value in T(n). You can do this because T(1)=1 is one of the base conditions.
=> T(i)=2^(n-1) * T(n-(n-1))=2^(n-1) * T(n-n+1)=2^(n-1) * T(1)=2^(n-1)
This means that the time complexity is O(2^n).
I participated on a proggramming contest last week. I used javascript to solve the problems, but I found an error working with big integers. First, this is the code:
const solve03 = (n) => {
n++;
const times = Math.floor(n / 4);
return n - 2 * times;
};
console.log(solve03(87123641123172368));
console.log(solve03(81239812739128371));
The output with js are:
43561820561586184
40619906369564184
I tested the same code with python (that supports large integers):
def solve03(n):
n += 1
times = n // 4
return n - 2 * times
print(solve03(87123641123172368))
print(solve03(81239812739128371))
And the outputs are:
43561820561586185
40619906369564186
I need a way to rewrite the code in js to solve the error calc problem, also, I known there are many libraries to support bigintegers operations, but the contest doesn't allow them.
Check out this snippet using BigInt! It will handle the large integers well 👍
const $ = str => document.querySelector(str);
$("input").addEventListener("keyup", e => {
let aBigInt = BigInt(e.target.value);
aBigInt++;
const times = aBigInt / BigInt(4); //always returns floored
const result = aBigInt - BigInt(2) * times;
$("div").innerText = result;
});
<input type="number">
<div></div>
Whats the best approach with javascript to evaluate an expression like 3+1*sin(20)*e^3?
First of all, I do not want to use built-in math-functions. In fact, I have already defined my own functions for power, square root, sin, cos, exponential, etc.
What I'm looking for, is a good way to parse an expression so I can pass them to these functions I created. I know there is an eval() function available in JavaScript for evaluating input expressions, but I'm not sure if that's suitable for this context.
Should I use eval()? If yes, how do I use it in this context? If no, what's a more suitable way to parse mathematical expressions?!
It's not an school assignment, its just a doubt.
Using a third party library
In a real life situation, you'd want to use a library like math.js to do the calculations for you.
To use this library, first include it in your HTML :
<script src='path/to/math.js'></script>
Then, you can just use the math.eval method to evaluate your expression :
math.eval('3+1*sin(20)*e^3');
That is, if 20 is a value expressed in radians. As it's probably a value expressed in degrees, you'd need to make this small adjustment :
math.eval('3+1*sin(20 deg)*e^3');
Because you explicitly said that you do not want to use the built-in math-functions, I suspect you're working on a school assignment. Note that submitting school assignments on StackOverflow is frowned upon, as it is considered a form of cheating.
But let's just ignore this and move on, shall we?!
Doing it on your own
Step 1 : Calculation with built-in math functions
In real life projects you should ALWAYS use built-in math functions or third party libraries (like math.js) that use built-in math functions under the hood. That's because built-in math functions are both 100% reliable and performance optimized.
It's impossible to create your own equivalent of built-in math functions in a way that is both as reliable and as performance optimized as the built-in functions, so there is NEVER a good reason NOT to use the built-in functions. But since you explicitly asked for it, let's ignore that and look at how to do things WITHOUT the built-in math functions. I assume this also implied you do not want to use math.js or any other library.
Using JavaScript's built-in functions, you'd calculate your expression like this :
3+1*Math.sin(20)*Math.pow(Math.E,3)
Built-in functions used :
Math.sin(x) can be used to calculate the sin of x
Math.pow(x, n) can be used to calculate xⁿ
Math.E() is a constant that represents e
Here, again, it's important to state this is true only if 20 is a value in radians. As 20 is probably a value in degrees, you probably want to define your own degree based sin function like this :
var dsin = function() {
var piRatio = Math.PI / 180;
return function dsin(degrees) {
return Math.sin(degrees * piRatio);
};
}();
Now, replace Math.sin with dsin
3+1*dsin(20)*Math.pow(Math.E,3)
In any real world application, this would be the best was to calculate 3+1*sin(20)*e^3!
Step 2 : Replacting built-in math functions with your own
Now, as you REALLY, REALLY, REALLY seem to want to go without built-in functions, just the next step is to replace every built-in function with a self-written equivalent. Often, there are multiple mathematical paths towards the same goal.
For example, you could write your pow function recursively like this :
var pow = function(base, exp) {
if (exp == 0)
return 1;
else
return base * power(base, exp - 1);
}
An iterative implementation :
var pow = function(base, exp) {
var result = 1;
while(exp--) {
result *= base;
}
return result;
}
So now what, you ask?! How can you implement dsin without relying on Math.sin, you ask?!
Well... A little bit of research tells you that you can calculare sin, using the formula sin(x) = x - x^3 / 3! + x^5 / 5! - x^7 / 7! + x^9 / 9! - ...
In JavaScript, that would be something like this :
var sin = function(x) {
var t1 = -1,t2 = 3,v1 = x,v2 = v1 + 1,it = 0;
while (it < 10) {
v2 = v1 + (t1 * pow(x, t2) / function(n){
j = 1;
for(i=1;i<=n;i++)
j = j*i;
return j;
}(t2));
t1 = -1 * t1;
t2 += 2;
v1 = v2;
it++;
}
return v2;
}
You might notice that I put my factorial calculation in a lambda function. A more elegant solution would be to put your lambda function in a separate function, as you're likely to need it elsewhere.
Now, you just need to puzzle all the pieces together and wrap them in a nice object :
var Calc = (function(){
return {
E : 2.718281828459045,
pow : function (base, exp) {
var result = 1;
while (exp--) {
result *= base;
}
return result;
},
fact : function(n){
j = 1;
for(i=1;i<=n;i++)
j = j*i;
return j;
},
sin : function(x) {
var t1 = -1,t2 = 3,v1 = x,v2 = v1 + 1,it = 0;
while (it < 10) {
v2 = v1 + (t1 * this.pow(x, t2) / this.fact(t2));
t1 = -1 * t1;
t2 += 2;
v1 = v2;
it++;
}
return v2;
},
dsin : function() {
var piRatio = Math.PI / 180;
return function dsin(degrees) {
return Math.sin(degrees * piRatio);
};
}()
};
})();
You can use the methods of these objects like this :
3+1*Calc.dsin(20)*Calc.pow(Calc.E,3)
Step 3 : Parsing
If you actually want your application to read an expression like 3+1*sin(20)*e^3 directly, you should NOT use eval(). Instead, you should write your own parser.
The proper way to do this, is to first write a tokenizer that converts your expression to a syntax tree. Then, you pass your syntax tree to an interpreter that processes your syntax tree by running the calculation functions you've created in step 1.
For an in depth look into how to build a syntax tree and interpreter, you could take a look at this tutorial.
I wrote a parser that does what you need. It's called SwanJS and it doesn't use eval or new Function.
Installation:
npm install #onlabsorg/swan-js
Usage:
const swan = require('#onlabsorg/swan-js'); // It works also in the browser
const evaluate = swan.parse("3 + 1 * sin(20) * e**3");
const context = swan.createContext({
sin: Math.sin, // or your own sin function
e: Math.E
});
const value = await evaluate(context);
If you don't like ** as power operator, you may change it, but that's not well documented. Look at /lib/interpreter.js to see how to define a new grammar or ask me if you prefer.
If you want more mathematical functionalities in addition to the standard JavaScript math library, then you may want to use a third party library like math.js.
To use this library, first include it in your HTML :
<script src='path/to/math.js'></script>
Then, you can just use the math.eval method to evaluate your expression :
math.eval('3+1*sin(20)*e^3');
I have a project I am working on and it needs to calculate mortgage calculations but I'm having trouble putting the formula into javascript.
the formula is:
M = P I(1 + I)^n /(1 + I )^n - 1
Any help is appreciated, thanks
P = loan princible
I = interest
N = Term
Break it down into a sequence of steps.
Multiplication is as straightforward as it gets: I*(1+I)
Division is the same: I/(1+I)
To the power of n is denoted by: Math.pow(3, 5); //3 to the power of 5
Math.pow() might be the only thing you didn't know yet.
Unrelated but useful,
Wrap your formula into a function and you have a mortgage-calculation function
calculateMortgage(p,i,n) {
result = //translate the formula in the way I indicated above
return result;
}
and call it like so:
var mortgage = calculateMortgage(300,3,2); // 'mortgage' variable will now hold the mortgage for L=300, I=3, N=2
Also, the formula you posted really doesn't make any sense - why is there a blank between P & I at the very beginning? Something's missing.
Try this: Math.pow(p*i*(1+i),n)/Math.pow(1+i,n-1)
Math.pow(a,2) is same as a^2
if P is not supposed to be with numerator then
this
p * (Math.pow(i*(1+i),n)/Math.pow(1+i,n-1))
or
p * (Math.pow((i+i*i),n)/Math.pow(1+i,n-1))
var M;
var P;
var I;
M = P*(Math.pow(I*(1+I),n)) / (Math.pow((1+I),n)-1);
Does this look right to you? I got the correctly styled formula from here.
Like what Nicholas above said, you can use functions to make it all the more easier.
var M;
function calculateMortgage(P, I, N){
M = P*(Math.pow(I*(1+I),n)) / (Math.pow((1+I),n)-1);
alert("Your mortgage is" + M);
}
And just call calculateMortgage(100, 100, 100); with your values for it to automatically give the answer to you.
I was wondering if anyone knew how to find the base of an exponential equation in Javascript.
I couldn't find any function that allows this to be done (e.g. using the Math functions).
For example, how do I find 'b' in the following equation:
y = b^t
Thanks in advance for any help you can provide.
If you know what are the values of y and t are, you can get the value of b by calculating the t-th root of y like this:
Math.pow(y, 1/t);
Source:
JavaScript: Calculate the nth root of a number
What you need is math and the logarithm.
y = b^t
=> t = log(y) / log(b)
=> log(b) = log(y) / t
=> b = 10 ^ ( log(y) / t )
So it would be something like
b = Math.pow(10, (Math.log(y) / t));
-Hannes