Javascript shift() unshift() mnemonics? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am having hard time remembering what Array.shift() and Array.unshift() do.
After few years, I still have too check out reference from time to time when I need to use one of them. Can anyone explain why those names are choosen and how to memorize which one does what?
I have no such problem with Array.push() and Array.pop()

As I known.
The shift command is come from the binary bit shift [1]. for Example.
001100
0 < 011000 // when you shift left
|
Yay!
I think it is quite simple it is just like you push it from behind. So this makes sense for me.
The unshift is the opposite way of shift.
001100
1 > 001100 // they called it unshift
1001100
|
Yay!
So that's it, Hope this helps!
[1] http://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts

a.push(e) pushes e onto the end of a.
e = a.pop() pops the last element from a, to e.
a.unshift(e) enqueues e to the start of a.
e = a.shift() gets the first element from a to e.
Use push and pop for stacks.
Use unshift and pop for queues. (Or push and shift)
I remember the difference between shift (destructive) and unshift (constructive) simply by remembering that I use un-shift for en-queueing, and shift is the opposite to unshift.

Just think of your keyboard:
Shift gets a capital version of the first key you press.
.shift() gets the first item off the array.

This is certainly the most confusing pair of function names. The only salvation I can offer is to remember one of the following two things:
Shift can be thought of as "moving something around," and perhaps you can picture that if you "shift" an array around a bunch, something is liable to fall off the end (or in this case, the beginning). Unshift puts things back the way they were.
It's the opposite of what it sounds like it should be. unshift sounds like undoing something, but in fact, it's putting something onto the array.
Good luck!

How about:
SHIFTer makes a drifter
It returns the first entry to the variable.
and -
UNSHIFTer is a weenier that sneaks in line
Inserts argument as first entry in array
Oh, there are deep psychological techniques at work here!! :-o But seriously, you will remember it for its peculiarity :-)

Related

Qualtrics scoring Loop & Merge questions

I'm setting up a simple Qualtrics survey with one question with a Loop & Merge function (in this one block); in Loop & Merge field 1, I've provided the URLs to my media files. The respondents have to select the right answer from two answer options (let's say Yes/No). All all my files are set up as a Loop & Merge within one question so that I won't have to create 100 separate questions for each individual media file.
This works great, however, I would also like to score my respondents' answers. The regular "scoring" feature in Qualtrics doesn't seem to work for me, since I can only provide one scoring option per question (i.e. I could only say that the first answer is always 1 point, and the second answer is always 0 points). However, the correct answer varies between my files (sometimes it's Yes/the first option; sometimes it's No/the second option).
I'm thinking there might be a way to list the correct answer (=i.e. the answer that should receive 1 point) in Field 2 in the Loop & Merge function; and then include some (javascript?) code in the question which would check the survey taker's answer choice against the "correct answer" in Field 2 of the Loop & Merge function for each media file. The code would assign "1" point if the participant's selected answer corresponds to Field 2 for each media file.
How would I write the (javascript) code to calculate a score for each question and an overall score at the end? (I don't need survey takers to see their score, but once a person is done, I would like to quickly see what their final overall score is, say 72 out of 100 possible points.)
Update: In the loop/merge function, I've added the right answer (for each file) in Field2, the incorrect answer in Field3. As suggested below, I've piped loop fields (2 and 3) into my question choices. I've added code in Field4 about whether or not the order of the answer options should be changed (0,1; 0= don't change order, 1= change order) so that the options always occur in the same order (for example, always Choice 1 = "Yes", Choice 2 = "No".) I've (unsuccessfully) tried to use the following JS code to refer to Field 4:
if (${lm://Field/4}==1) {
(choiceNum = ${lm://Field/3}, ${lm://Field/2})
}
If there is a way to work without JavaScript, I'd be glad to hear about that option as well.
Thank you so much!
How about this without JavaScript:
Include your two choices as loop fields: Field 2 is correct answer, Field 3 is incorrect answer
Pipe your loop fields (2 and 3) into your question choices
Randomize the choices
Score the question: Choice 1/Field 2 = 1 point, Choice 2/Field 3 = 0 points.

solving a trig equation numerically with in-browser JS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Given values for the variables s, v, and h, and given a library such as numeric.js how can I numerically solve the following equation for a within a given degree of accuracy?
I'm wanting a JS algorithm for use in-browser.
Separating variables and parameters
You could start by substituting b = a/h. That would turn your equation into
2b*sinh(1/(2b)) = sqrt(s²-v²)/h
That way you have all the inputs on the right hand side, and the variable on the left hand side, but unfortunately still occuring in several places in a transcendental form. The benefit is that we can now treat the right-hand side as a single number in order to gain some understanding of this function.
First look at a plot
The function seems reasonably well-behaved:
So you can do standard numerical root-finding methods, e.g. Newton's method, to find the position where this function takes a given value (i.e. the one you computed from the right-hand side). If you interpret root-finding as finding locations where a function is zero, then the function for which you want to find zeros is the difference, i.e.
2a*sinh(h/(2a)) - sqrt(s²-v²)
Using optimization from numeric.js
If you want to make use of numeric.js, numeric.uncmin would likely be your best bet. At least it's the best I could find in the docs so far. (Perhaps there is some bare root-finding implementation in there, but if so, I couldn't find it yet.) You'd try to find the minimum of the function
(2a*sinh(h/(2a)) - sqrt(s²-v²))²
interpreted as a function of a, and hope that that minimum is actually (close to) zero. You might get better results (i.e. faster convergence and/or lower error) by also providing the gradient (derivative) of that function as a separate argument. You can use Wolfram Alpha to find that derivative.
Further rewriting of the function
Let's define f as f(b) = 2b*sinh(1/(2b)). You are trying to find out at what position f assumes a given value. In order to make convergence faster, you can try to turn this f into a different function which will be close to linear. Toying around with plots, I've come up with this:
g(b) = (f(b) - 1)^(-1/2)
You can apply the same conversion to the right hand side to see the desired value for this function. For b > 0.06 this looks fairly linear, so it should converge really fast. Provided your parameters are expected to be in that range where it is almost linear, but even for smaller b it should be no worse than the original formulation. You could use the linear form to compute the starting position of your Newton's method, but I wouldn't bother: as long as you start with a reasonably big value, the first step of Newton's method will do just that.
this is transcendent equation
I assume real domain in that case you can not separate the unknown from it (in general) instead you still can solve it numerically (as you intended)
I am too lazy to do proper analysis of 2a.sinh(h/2a)=sqrt(s.s-v.v)
but if I see it right then 2a.sinh(h/2a) is monotone so let c=sqrt(s.s-v.v) for simplicity and speed up. As I see it c >= 0 so if h >= 0 then a = <0,+inf)
find value crossing
double a0,a1,da=initial accuracy step;
for (a1=0.0;2a.sinh(h/2a)<=sqrt(s.s-v.v);a1+=da);
now a1 holds approximate top bound solution
for (a0=a1;2a.sinh(h/2a)>sqrt(s.s-v.v);a0-=da);
now a0 holds approximate low bound solution
find solution in desired accuracy
if a0==a1 then you have found exact solution so stop
if fabs(a1-a0)<=accuracy you are inside your accuracy so stop and lower the da for example da*=0.01; this will boost accuracy 100 times. Now search for solution again but only on interval <a0,a1> and repeat this until solution is found
[notes]
Another example of solution of transcendent equation is here: solving Kepler`s equation. When nothing else works you still can try this:
How approximation search works

HTML5 - Collisions [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm working on a top down game, and this game is going to contain a lot of collisions simple and complex.
After doing some research, I understand that I have to always compare my character with 'object' within my code - and then check for collision calculations.
EG:
CheckCollisions(Player, Object);
Which means I have to add in every single collide-able object within my scene, into my code:
CheckCollisions(Player, Building1);
CheckCollisions(Player, Building2);
CheckCollisions(Player, Trash);
CheckCollisions(Player, Bench1);
CheckCollisions(Player, Bench2);
CheckCollisions(Player, Office1);
CheckCollisions(Player, Office2);
First off, my objects might not even be simple rects, they might be complex shapes. Secondly, some of them might have their own rotation. And thirdly, what happens if I have over tens of thousands of collie-able objects in my scene?
Ins't there an easier way to check for collisions within a HTML5/JS game?
Is this even possible? I'm really just looking for some advice and pointers.
Thanks
It's very uncommon to have a named variable for every single object in your game. Usually you store all objects in one data structure (like an array) and when you need to do something with all objects, you do a for-loop over this array.
Some important objects, like the player character, could have an own variable, but they should also be in the "all objects" array, so you don't need to program a special handling to include the player character.
Regarding performance: When you check everything against everything, the amount of collision checks which need to be performed increases quadratically. But you can reduce the effort when you only check collisions of those objects which are already close to each other. Before you check collisions, you:
divide the playing field into rectangular zones (the zones must be at least as large as the largest object).
Then you assign each object to the zone its upper-left corner is in.
Then you take each zone, and check collisions of each object in it with the other objects in the zone and with all objects the three zones right, down and rightdown from it (for objects which overlap zone borders).
When you have very complex shapes, you could also speed up collision-detection by calculating a bounding-rectangle for each shape (the smallest possible rectangle it fits into). Before you check the collision between two objects, you first check if their bounding rectangles intersect. When they don't, there is no chance for the complex shapes to intersect, and you can skip all the complex calculations.
As everyone so far has indicated, an array of objects is much better than naming all your objects individually.
A much easier method of collision detection that might work for you is to have a central object that tracks all occupied spaces. For instance, let's call it LocationTracker for now.
Assuming you're only using x and y axes, you can have a Point object that stores an X and a Y location, (and if you want to get fancy, a timestamp). Each object as it moves would send an array of all the Points that it is occupying. For example, you can call locationTracker.occupySpace(player[i], array(point(3,4), point(4,4), point(5,4)), etc.
If your call to occupySpace returns false, none of the Points match and you're safe, if it returns true, then you have a collision.
The nice thing about doing it this way is if you have x amount of objects, instead of checking x*x times per move, you check x times max.
You wouldn't need to pass in all points of the objects, just the outer most ones.
1 - you don't need to write a line of code for every object in your game. Put them into an array and loop over the array:
var collidableObjects = [Building1, Building2, Trash, Bench1, Bench2,Office1, Office2];
var CheckAllCollisions = function() {
for (var i=0; i<collidableObjects.length; i++) {
CheckCollisions(Player, collidableObjects[i]);
}
}
2 - if you have complicated collision check (ie rotated shape, polygon, etc) you can first check a simple rectangle check (or radius check) and do the more accurate check if the first one returns true.
3 - if you plan to have tens of thousands of objects you should have smarter data collections, for example objects sorted by X coordinate so you can quickly avoid checking everything larger than Player.X+100 and smaller than Player.X-100 (using binary search), or split the objects into a grid and just check the objects in the 3x3 grid cells around the player.
A much better way is to put all your scene objects into an array or a tree structure and then
for( var i=0; i<scene.length; i++ ) {
scene[i].checkCollision( player );
}
if you add a function .checkCollision() to every object, you can handle any special case in there.
It's a good idea to make the player a rectangle so the checking code doesn't become too complex.
Make the collision-checking-rectangle of the player object slightly smaller than the actual sprite; that makes the life easier for your players.
First of all, you should always have your objects in arrays. This includes things like enemies, bullets and other such things. That way your game can create and destroy them at will.
You seem to be talking about the actual frequency of the collision checks, and not the collision check method. To that my advice would be to only run collision checks on a finite number of the objects. Try using a grid, and only checking for collisions with objects in the same grid block as the player.
Another thing that helps is to have plenty of "short cuts" inside the method itself. These are things that can be checked quickly and easily before any complex math is done. For example, you could check the distances between the two objects. If the objects are farther away than their farthest corner, you don't have to check for a collision.
There are plenty of these methods that you can utilize in your own unique combination.

Ways to simplify an array of objects that is repeated several times

I wonder if I can simplify and use less lines of code for this purpose:
I have a class called "worker", and that class has a method that reads the properties (name, age, etc...) from a series of simple arrays.
Until there, everything is fine. Now, one of the properties that I want to add is a boolean value that makes reference to which months of the year the worker is active. For the moment, I have solved it like this:
var months_worker_1 = [{"jan":true},{"feb":true},{"mar":true},{"apr":false}] //and so on
And then, my property reads months_worker_1, but I have one array like that for each worker. I wonder if there is a way to do this that requires less lines of code, like for example, create a "master" array with all the months of the year, and in the array for each worker, specify just the months they are working. Those months become "true", and the rest of months become "false" automatically without specifying so... I have been scratching my head for some time, and for the moment only my current system is working fine, but I am guessing that there must be a simpler way...
Thanks very much!
Edit: I clarify, there is no "big picture". I am just doing some exercises trying to learn javascript and this one woke my interest, because the solution I thought seems too complicated (repeating same array many times). There is no specific goal I need to achieve, I am just learning ways to do this.
A really nice trick that I use sometimes is to use a binary number to keep track of a fixed amount of flags, and convert it to a decimal for easier storage / URL embedding / etc. Let's assume Mark, a user, is active all months of the year. Considering a binary number, in which 1 means "active" and 0 inactive, Mark's flag would be:
111111111111 (twelve months)
if Mark would only be active during january, february and december, his flag value would be:
11000000001
Checking if Mark is active during a specific months is as simple as checking if the character that corresponds to that month's index in Mark's flag is 1 or 0.
This technique has helped me in the past to send values for a large number of flags via URLs, while also keeping the URL reasonably short. Of course, you probably don't need this, but it's a nice thing to know:
Converting from binary to decimal is easy in JS:
parseInt(11000000001, 2).toString(10); // returns 1537
And the reverse:
parseInt((1537).toString(2)); // returns 11000000001
Edit
You could just as easily use an array made out of the month numbers:
var months_worker_1 = [1, 2, 3]; // this would mean that the user is active during january, february and march

Need help temporarily modifying a variable [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am developing a pong redux in html5 and javascript. I need help modifying it so that upon holding down D, it will subtract 4 from the ball.speedModifier variable, and then add 4 upon releasing D. The reason I don't just set the modifier back to 0 when the key is released, is because I want to have multiple things changing the modifier at once that stack on top of one another. With my current system for detecting key presses, the addition and subtraction of the variable would repeat at 60 FPS, while I only want it to occur once until the amount is subtracted again.
Here is a pastie of my code:
HTML: http://pastebin.com/txeNftNT
Javascript: http://pastebin.com/scpBqGqx
I think the easiest way to do this would be to track additional properties for each key. Instead of checking just if a key is down or up, you also want to track if they key was down or up on the previous iteration of checkInput(). That way, if the "D" key is down, but it wasn't down the last iteration, you subtract 4 from ball.speedModifier. Alternatively, if the "D" key is up, but wasn't up on the last iteration, you then add 4 back to ball.speedModifier.
The final key to making this work is at the end of every checkInput loop, you save out whether each key was down or not. Then on the next loop of checkInput() you're ready to do your checks again.
The following is just pseudo code, but hopefully gives the idea.
function checkInput(){
if(d.isDown()){
if(!d.wasDown()){
ball.speedModifer -= 4;
}
}else{
if(d.wasDown()){
ball.speedModifier += 4;
}
}
d.wasDown = d.isDown;
}
Just in case, I also put together a working example. Do note the three changes. Your pressedKeys is no longer an array, but an object of KeyCodes which correspond to the VALUES of your existing KEY object. And then this key's value is an object itself with two keys of "wasDown" and "isDown". I then pre-populate this object at the end of init() and then perform your various checks and updates in checkInput using the new object instead of the array.
http://jsfiddle.net/gUgGf/
Hopefully that helps!
I can think of two fairly simple ways to do what you want:
Have a variable that stores the base value, and then each frame perform all your calculations for any applicable modifiers instead of editing the value directly.
Have an array named something like pressedThisFrame that you push keys in to from your keydown event, and in the main loop you move entries out of pressedThisFrame and in to your overall pressedKeys array, and part of that move involves performing whatever modifiers are appropriate.

Categories