Javascript find intersections given two functions - javascript

I am trying today to solve for the coordinates where functions intersect. I am using the nerdarmer library right now, but it only returns only one solution out of all the possible solutions. For example, I want the code below to print -1, 0, 1 but it only outputs 0. Another example is if I want to find intersections between y = 0 and sin(x), I want the output to be ..., (-2pi, 0), (-pi, 0), (pi, 0), (2pi, 0), (3pi, 0), ...
intersect("x^3", "x")
function intersect(f1, f2){
var x = nerdamer.solve('f1', 'f2');
console.log(x.toString());
}
Is there any way to get all the possible solutions?

You've misunderstood the syntax of nerdamer.solve
The first argument is the formula or equation.
The second argument is the variable to solve for.
If the first argument is not an equation, it is assumed to be equal 0.
In your case x^3=0. which only has the solution 0.
If you want to intersect the equations you will need to set them equal to each other in the first argument. And in the second argument just specify x. (or change it to suit your needs if required).
intersect("x^3", "x")
function intersect(f1, f2){
var x = nerdamer.solve(f1+"="+f2, "x");
console.log(x.toString()); //outputs [0,1,-1]
}
Edit:
In your example you also directly put the strings "f1" and "f2" into the solve function which seems to just solve f=0;

Related

What is the fastest way to increase the value of a variable until it matches the value of another variable in Javascript?

I have a code that is increasing the value of a variable 'x' by 0.01 and do some calculations until it matches the value of another variable 'y'. While "X" is increasing, "y" is decreasing not linearly.
What would the best logic to find the value where 'x' and 'y' are the same or the closest? Increasing 'x' by 0.01 is doing the job, but as I'm really noob, I guess there is a clever way.
Thanks in advance
If I understand correctly, you want to find an x such that f(x) = y for a constant y, and f(x) is non-linear but has no other inputs. Is this correct?
Let us further assume that f(x) is strictly increasing or decreasing (that is: it does not wiggle up and down and cross y at several xs). Then, you can use a standard binary search to find the single intercept:
find values
x_lo such that f(x_lo) < y
x_hi such that f(x_hi) > y
look at the midpoint m = (x_hi + x_lo) / 2.
if f(m) < y, use x_lo = m, and repeat this step
if f(m) > y, use x_hi = m, and repeat this step
if f(m) == y, or it is close enough for your needs, you have finished!
A simple way to find initial values for x_hi and x_lo that is to test f(any) value, and assign x_hi=any or x_lo=any depending on whether it is larger or
smaller than y. Once you have one extreme, you can quickly find the other by quickly increasing or decreasing it. Say we have x_lo, we can test with x_hi = x_lo*(2^i) for i=1, 2, 3, ..., with ^ representing exponentiation.
If f(x) crosses y at several points, this does not work - because it can skip right over the important x in step 2.

What is this Javascript function parameter doing?

Consider the following code (shortened for clarity):
Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) {
radius = radius || [8];
if (!radius.length)
radius = [radius];
};
I'm reading the first part as (pseudocode):
if (radius array passed to function) then
radius = radius
else
radius = [8] // new array, single element of value 8
end if
but I don't get the second expression (the if(!radius.length) radius = [radius] part).
Could someone explain it to me?
Vertices.chamfer = function(vertices, radius, quality, qualityMin, qualityMax) {
// Set the radius to the value passed in.
// If the value passed in is undefined, set the radius to an
// array containing 8 (the "default")
radius = radius || [8];
// If radius isn't an array (i.e. length is 0 which evaluates to false),
// make it an array.
if (!radius.length)
radius = [radius];
};
The concept used here is known as duck typing - i.e. checking the type of a variable by looking for the presence (or absence) of some characteristic properties/methods. Author of this code assumed that if something has a length property it is an Array, and if not it can be converted to an Array by wrapping it in [].
The second part, converting x to a single-item Array containing x using x = [x] is totally OK.
The problem is there are other types in JavaScript that have a length so this test is not really reliable.
For example: "7".length returns 1, so if you passed the variable as a string instead of a number (easy enough to make this mistake for example by reading values from <input> fields) something would break down the line expecting an Array but getting a String.
Another type that has a length is a Function: (function(a,b){}).length == 2.
So yeah, this is not really good test but the basic idea makes sense. Should have used either Array.isArray or some other property/method that is unique to Arrays.
EDIT: I'd also point out the radius = radius || [8] construct is only OK if 0 is not allowed as the radius argument.
I'm reading the first part as (pseudocode):
if (radius array passed to function) then
radius = radius || [8] checks to see if radius is falsy, which might be not passed in at all (undefined), or passed in as undefined, or passed in as null, 0, "", NaN, or of course false.
But yes, it's probably intended to use [8] if no radius was specified.
but I don't get the second expression (the if(!radius.length) radius = [radius] part).
If radius was given but is either A) An array with no entries (radius.length is 0 and therefore falsy), or B) Not an array (radius.length is undefined and therefore falsy), we create an array and make it the first entry in that array.
That's not at all robust validation, lots of things have length (strings, for instance), but that's probably what it's meant to do.
The robust way to check if something is an array is to use Array.isArray, which was added in ES5 and which can be reliably shimmed/polyfilled for obsolete engines (like the one in IE8).
if imported radius is not an array and it has value, then it returns an array with the radius value inside.
if imported radius is empty then it returns an array with the number 8 inside: [8]
However, inside the pseudocode, it is not gonna get in if statement, if the imported radius is not an array.

Is it possible to convert A string that is an equation with a variable into a equation?

I need to convert a string returned from prompt into an equation, however the parseFloat returns as only the first number, and symbols in an equation, and stops at the variable. The variable will always = x. The program is designed to convert an algebraic expression say 15*x(5^4-56)*17/x=15 into an expression, and calculate the value of x. If someone could show me how to do this, it would help dramatically. I am currently using multiple prompts, having the user put in the equation before x, then the equation after x, then it inserts a variable in between the two, and calculates it's value.
Edit:
I have no variables predefined, and it must work in equations where x > 1000, or x != //an integer.
Thanks in advance!
Seems to be a complex problem...
This is a solution for a simple relaxed version of your problem. Hope you can use some components of this.
Constraints:
answer for x should be integers between 0 and 1000
the left hand side of the expression should be proper javascript syntax
var input = prompt("enter the equation"); //eg: x*x+x+1=241
var parts = input.split('=');
//solving equation starts
var x = 0;
var temp = eval(parts[0]);
while (temp != parts[1] && x<1000){
x++;
temp = eval(parts[0]);
}
var ans = (x<1000)?"answer is "+x:"this program cannot solve this";
//solving equation finishes
alert(ans);
You can replace the "solving equation" part with some numerical methods used in computer science to solve equations (more details here) . You will have to parse the left side of equation and map them to proper javascript expressions (as a string to execute with eval()) if you want to allow users to use your syntax.
Javascript can evaluate strings using the eval function, but the variable as to be defined before hand, and the equation has to be formatted in way that javascript can understand:
var x = 15
var string = "15*x*17/x"
eval(string)
Your example: "15*x(5^4-56)*17/x=15" would not run however, because it would evaluate x(5^4-56) as a javascript expression, which is invalid.
Using all the info, and other mehtods I found about this, I have put together a communinty answer. Anyone is invited to change and/or add their methods to this.
In order to do this with the least work possible for the user and coder, you would implement the following code.
var input = prompt("enter the equation"); //eg: x*x+x+1=241
var parts = input.split('=');
//solving equation starts
var x = 0; //Or the lowest possible value of "x"
var temp = eval(parts[0]);
while (temp != parts[1] && x<1000){ // && x < The highest number to evaluate
x++; //Add the increment (determines the maximum amount of digits) eg x+0.1 for tenths max, x+2 for only even integers etc.
temp = eval(parts[0]);
}
var ans = (x<1000)?"answer is "+x:"this program cannot solve this"; //make sure x< is the same as line 7.
//solving equation finishes
alert(ans);
But, this runs very slowly if you allow tenths, or a range larger than 2000.`
A faster way of running this would be to define arrays allowing any variable (instead of just x) and a different eveulation process such as here. (do the right click view html and click on the first js source to see code) but, this is 2k lines. Both are usable, but the second is more efficient, and can solve multivariate equations.

Heavily packed javascript, multiple questions from 219-byte (canvas, bitwise,...)

I came across a website today. It was a challenge of some developers about making the smallest game possible with certain requirements, and they released the final code of unbelievable size of 219 bytes and runnable on Chrome 17 (one of the requirements). I tried to explore the code (with the explanation provided from the site) and do researches on codes I didn't comprehend. However, the code was packed too heavily to my knowledge, so I am seeking for some helps.
Here is the code, after beautified:
<body id=b onkeyup=e=event onload=
z=c.getContext('2d');
z.fillRect(s=0,0,n=150,x=11325);
setInterval("
0<x%n
&x<n*n
&(z[x+=[1,-n,-1,n][e.which&3]]^=1)?
z.clearRect(x%n,x/n,1,1,s++)
:b.innerHTML='GameOver:'+s
",9)>
<canvas id=c>
The game is named "Tron", and just like classic snake game (without apple).
Anyway, here are my questions:
1) How can they select element with id 'c' without using getElementById() rather than a simple c
Look at the bottom of the code, there is a canvas with <canvas id=c>. I understand that advanced browsers will automatically fix the quotes "" for the id="c". However, when a function is called in onload event, it assigns z = c.getContent('2d'); and directly refers to the canvas without even applying anything such as document.getElementById(). Also the same when they referred to <body id=b>. How is that possible? Under which circumstances am I able to do similarly?
2) Will replacing parameters of a functions by quick assigning variables affect the function at all? If it does, how will it be calculated?
Particularly, take a look of the third line:
z.fillRect(s = 0, 0, n = 150, x = 11325);
I understand to the most basic level, fillRect() requires 4 parameters fillRect(x-cor, y-cor, width, height). However, the code above produces a rectangle 150x150. First of all, I read the description and they claimed that by default, the code would produce a rectangle 300x150, so I assumed that the assigning short functions would actually assign nothing to the parameters of the parent function. I did a test, and replaced n = 150 by n = 200. Weirdly enough, it produces a rectangle 200x150, so once again I agree that n = 150 did assign 150 to that slot. Hence, the code above can be written as:
z.fillRect(0, 0, 150, 11325);
However, another problem comes. Why isn't its height 11325px but 150px instead? I thought it was reset to default because 11325 excessed the handling of browsers, so I changed it to 500 instead; and it produced the same problem.
So generally, when you do short assigning inside a function (for instance: someCustomFunction.call(s = 1)), what really happens there? If nothing happens, why did the rectangle in the example above changed its size when replacing n = 200 but not when x = 200?
Additional question: this question is not the question I am really into, because it is too personal, but I would love to know. The source states that "x is going to be the tron's position, and is set to 11325 (11325 = 75 x 75 + 75 = center of the grid)", how does this kind of one-number-represents-position work?
3) What in the world does it mean?
This is the most headache part to me, because the author packed it too smartly.
&(z[x+=[1,-n,-1,n][e.which&3]]^=1)?
I broke it up, and figured that it was actually z[]^=1 in order to check the condition for the later ? : operators. But first:
What does ^=1 do?
Some people commented on the project and said it could be replaced by --. I think of it as a bitwise AND operator, but what does it have to do with --?
And next:
How did they use [e.which&3] together with the preset array to filter keystroke "i", "j", "k", "l" too effectively?
I notice the array has the length of 4, which is the length of the keys needs filtering. Also, pressing another key rather than "i", "j", "k", "l" also works. It leads me to believe that the &3 does something in filtering the 4 keys, but I don't know how.
Those are all I have to ask. The short but complicated code really excites me, and I really appreciate any help in understanding the code further.
Sidenote: I didn't actually look at the website, so if I'm covering anything they already have, I'm sorry. I realised there was a link to it halfway through my post.
Here is the code, unminified, with some adjustments.
HTML:
<body id=b>
<canvas id=c></canvas>
</body>
Javascript:
document.body.onkeyup = handleOnKeyUp;
document.body.onload = handleOnLoad;
function handleOnKeyUp(event) {
e = event;
}
function handleOnLoad(event) {
score = 0, n = 150, x = 11325;
context = c.getContext('2d');
context.fillRect(0, 0, n, n);
end = setInterval(function () {
if (typeof e === "undefined") return; // This isn't part of the original code - removes errors before you press a button
// Map key that was pressed to a "direction"
// l(76) i (73) j(74) k(75).
// If you AND those values with 3, you'd get
// l(0), i(1), j(2), k(3)
var oneDimDirs = [1, -n, -1, n];
var dirChoice = oneDimDirs[e.which & 3];
// Now add the chosen "direction" to our position
x += dirChoice;
if (x % n <= 0 || n * n <= x || // out of bounds
!(context[x] ^= 1) // already passed through here
) {
b.innerHTML = "GameOver:" + score;
clearInterval(end);
}
else {
score++;
context.clearRect(x % n,x / n, 1 , 1)
}
}, 9);
}
Generally, the code makes heavy use of a couple of hacks:
It makes heavy use of global variables and the fact that assigning to an undefined variable creates a global.
It also makes use of irrelevant function parameters to set or modify variables(this shortens the code length)
The code uses a one-dimensional representation of a two-dimensional space. Instead of moving you in two directions, x and y, it "flattens" the representation of the two-dimensional space(the gameboard) into a one-dimensional array. x represents your position on the overall game board. If you add 1 to x, you will move along the current "line"(until you get to its end). Adding n moves you a whole line forward, so it's similar to moving once down.
Your questions, one by one:
1) How can they select element with id 'c' without using getElementById() rather than a simple c
Kooilnc's answer already covers this. This is called "named access":
http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object
2) Will replacing parameters of a functions by quick assigning variables affect the function at all? If it does, how will it be calculated?
You misunderstood what is happening here. First, functions accept values as their parameters, and expressions produce values when they are evaluated. An assignment expression, n = 150, produces the value 150 when evaluated. As a side effect, it also assigns that value to the variable n. So calling a function func(n = 150) is almost equivalent to func(150), with the exception of that side effect. That side effect is used in the code to save space, instead of having to assign the variables on separate lines.
Now, for the canvas WTF - As far as I can tell, a canvas element's default width and height happen to be 300px and 150px. You cannot draw past those limits, so trying to execute z.fillRect(0, 0, 150, 11325); will not draw past the 150 height limit. The code authors use the fact that 11325 is bigger than 150 and is thus safe to pass as a parameter(the rectangle will still be drawn as 150x150). 11325 happens to be the one-dimensional coordinate of the starting position.
3) What in the world does it mean?
I hope I mostly answered it within the code. The inner part is unpacked and commented, which only leaves this part unexplained:
context[x] ^= 1.
(Note, ^ === XOR)
The idea is that the authors are using the context as an array to store which positions they've already visited. There are three reasons for doing it this way:
One, they want to assign some value to mark that they've passed through here. context[x] is usually undefined, undefined ^ 1 === 1, so they're assigning ones to the positions they pass through.
Next, they want to be able to check if they've passed through there. Coincidentally, 1 ^ 1 === 0, which makes it easy to check. Note what I mentioned about assignment expressions - the value of this assignment expression will be either 1, if the position has not been visited before, or 0, if it has. This allows the authors to use it as a check.
Since the check they use is something like expr & expr & expr, expressions which yield true/false or 1/0 values will work the same way as if it was expr && expr && expr(true and false are converted to the numbers 1 and 0 when used in &)
How did they use [e.which&3] together with the preset array to filter keystroke "i", "j", "k", "l" too effectively?
I hope I answered this sufficiently with comments in the code. Basically, using the onkeyup handler, they store the event which has the key that was pressed. On the next interval tick, they check e.which to determine which direction to go in.
About
1) How can they select element with id 'c' without using getElementById() rather than a simple c
In most browsers you can access an element using its ID as a variable in the global namespace (i.e. window). In other words, to retrieve <div id="c"> you can also use c, or window.c.
See also
The other questions I leave to smarter people ;)
1) How can they select element with id 'c' without using getElementById() rather than a simple c
I believe it was an old version of IE that originally allowed access of DOM elements in JS directly by their id, but a number of other browsers followed for compatibility with websites that rely on this. In general it's not a great thing because you can get weird bugs if you create variables with the same names as the element ids (not that that matters for this example).
2) Will replacing parameters of a functions by quick assigning variables affect the function at all? If it does, how will it be calculated?
You said within your point (2) that z.fillRect(s = 0, 0, n = 150, x = 11325); can be written instead as z.fillRect(0, 0, 150, 11325);, but that is true only in as far as having the function call to fillRect() work the same way. This change would break the overall program because the assignment statements are needed to create and set the n and x global variables.
In a general sense in JS the assignment operator = not only assigns the value from the right-hand operand to the variable on the left, but the whole expression gives the value of the right-hand operand. So someFunc(x = 10) sets the variable x to 10 and passes the value 10 to someFunc().
In the case of that fillRect(), the n and x variables have not previously been declared, so assigning a value to them creates them as globals.
3) What in the world does it mean? &(z[x+=[1,-n,-1,n][e.which&3]]^=1)?
Well, it's (obviously) kind of complicated. To answer the specific questions you mentioned about parts of it:
How did they use [e.which&3] together with the preset array to filter keystroke "i", "j", "k", "l" too effectively?
The keys "i", "j", "k", and "l" are a good choice for up/left/down/right controls in a game because their physical layout on a standard keyboard corresponds to up/left/down/right but also because those letters belong next to each other in the alphabet so they have contiguous keycodes too: 73, 74, 75, 76. So when you take those keycodes and do a bitwise AND with &3 you get the values 1, 2, 3, 0 which then act as appropriate indices into the [1,-n,-1,n] array.
What does ^=1 do? ... I think of it as a bitwise AND operator ...
It's not a bitwise AND operator. ^ is a bitwise XOR, and ^= is the bitwise XOR assignment operator. That is, x ^= 1 is equivalent to x = x ^ 1.

How to calculate the proper numbers without doing a switch?

I need an algorithm to calculate an offset based on an array length. I have manually got the number for each number, but if possible without doing a case/switch.
Given an array length x, I need to come up with something that calculates this:
20 if x == 5
25 if x == 4
35 if x == 3
50 if x == 2
Am I missing something? Do I have to use a switch here?
A random guess, but how about 105 div x?
Or maybe round(20 / x) * 5?
In fact, since you only gave four cases, there are a lot different methods you can use. But perhaps more importantly is - are there any patterns you could follow that enables your code to make more sense?
At first lets make clear that your mapping function not linear, because for the (linear) x the interval between your function results differ.
To find a non-linear function you need to apply some "more difficult" function interpolation (e.g. Lagrange).
My result with this nice online tool for the input [2, 50], [3, 35], [4, 25], [5, 20] is (5x^2-55x+190) / 2.
But to be honest for such few values I would use a switch - it might be more efficient and keeps your code understandable (e.g. if you look at it in a year or so ;-) ).
Hope that helps.
*Jost

Categories

Resources