Order of operation for subtraction? [closed] - math

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This may be an uneducated question - or an odd one of the kind.
My question is why this code doesn't work:
if (up == true)
{
SDL_Delay(pause_t);
player.setY(player.velocity - player.getY());
}
if (left == true)
{
SDL_Delay(pause_t);
player.setX(player.velocity - player.getX());
}
However, this code does work:
if (up == true)
{
SDL_Delay(pause_t);
player.setY(player.getY() - player.velocity);
}
if (left == true)
{
SDL_Delay(pause_t);
player.setX(player.getX() - player.velocity);
}
The difference between the two codes is that in the first example, I am subtracting a part firstly (the velocity of the object) before calling the position function.
What happens when I run this code is that it doesn't move 1 on the axis, but rather 10.
The size of the Y axis is above 10, so I am not actually subtracting its own coordinates.
However, in the second piece of code, I am subtracting the velocity in the end, after having called my position function.
What happens with the second piece of code is that the object moves one pixel (velocity's integer value).
To those who should wonder what I am trying to do, these are controls for my openGL game. It's for moving an object.
And for the record, this is not an important question. My code does work. I am simply curious why it works the way it does.

in the first example, I am subtracting a part firstly (the velocity of the object) before calling the position function.
No, in the first version, you're subtracting the old location, not subtracting the velocity.
The code for what you describe is:
player.setY((-player.velocity) + player.getY());
and that will work.

Related

turn left turn right commands in map [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 have implemented a code that uses Dijktra's Algorithm. Thanks to Dijkstra I can print the shortest path from the desired source to desired destination. However, what I want to do is to add a feature that tells us directions with turn left , turn right commands.
Examples:
From A to D:
Let's say A is located in street 1 , B is located at street 2 and D is located 60 meters left of the street 2.
From A to D:
Go to Street 2 . Turn left . Go about 60 meters .It will be on your
left.
I need your ideas. Thank you!
To generate driving instructions from a path, you need to store additional information with the graph:
For each road, its length. This is straightforward
For each crossroad, the relation between each pair of incident roads.
You could store the azimuth of each road around the crossroad (road 1-2 goes west from intersection 1), then generate the driving instructions from the relative angle between two roads, type of the crossroad (normal / roundabout) and the topological ordering and relative angles of all other roads.
This approach has the benefit of more compact representation, but it needs more programming.
Alternatively, you could store the relation between each pair separately. This is more reliable (only a human could truly comprehend the complexities of each possible crossroad type in the world), but it's more manual to update (after all, a little AI could in theory defer the crossroad type, even if with errors).
If you have a huge map, you'll want to stick to the first approach. If you are building the map manually, you may prefer the second one - just be sure to not actually store strings with each road pair (unless they're interned by the language), or your memory demands might skyrocket. This needs extra attention when serializing the map to a file (again, a ZIP compression might alleviate that to a great extend, if you opt for that).
If your map is only concerned about simple 4-way crossroads, then the information stored with each pair is simply a left/straight/right enum (approach #2), or just an ordering of the edges around the crossroad (approach #1) where some roads may be null.
For example, your crossroad could (simplest case, approach #1) look like
private Road[] roads = new Road[4];
public enum Direction{
Left, Straight, Right, Back;
// utility methods
}
public Direction getDir (Road from, Road to){
// input checking stripped for clarity
int iFrom = roads.indexOf(from);
int iTo = roads.indexOf(to);
// more input checking
int iDiff = (iFrom - iTo) % 4;
if(iDiff < 0) iDiff +=4 ;
return Direction.getRelative90(iDiff);
//Direction.getRelative90 is just a switch statement.
}
For generating the directions, use the information stored with the map. Remember to concatenate roads (sum up their lengths) that logically follow (no instructions at that intersection = implicit "go straight" - several roads might follow into one, but only one should follow from each), the rest is straightforward.

Understanding the recursion here [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm looking at a recursive problem where a child can hop a staircase of steps n in 1,2 or 3 steps at one time.
The code I'm looking at is a function similar to the likes of fibonacci. However, what I don't get is if n==0 why does it return 1. If the total number of steps are 0, shouldn't there be zero ways of climbing it ? Why is there one way to climb it ?
int f(int n)
{
if(n<0)
return 0;
else if(n==0)
return 1;
else
return f(n-1) + f(n-2) + f(n-3);
}
This is more of a logic question. Suppose you stand there and do nothing. How many steps did you climb? The answer is zero. So, did you successfully climb zero steps? Yes.
How many ways are there to climb zero stairs? Just one way: you have to stand there and not climb any steps.
That isn't really a valid question.
Because this is a recursive implementation, you'll always have to provide a boundary case for f(nmin) where nmin is 1 less than the lowest valid n.
So the case n = 0 is a boundary condition that serves to ensure the correct result for all values where n > 0.
In other words, it (probably) doesn't mean anything, or, it probably means something different to what you think it means. All it has to do is ensure a correct result for f(1).
No, there is not 0 ways to go up 0 stairs, in the same way that 0/0 does not equal 0. It's an indeterminate result.

Ocaml operations are performed out of order [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
In Ocaml I have a "global" (ie. has file scope) array initialized with some numbers, then I do some operations on those numbers and then I call a function to sum those numbers together. Now because this array is "global" I didn't bother to pass the array as an argument and what ended up happening is that Ocaml calculated the sum of the initialized numbers (in compile time I guess) instead of after my operations on the array had happened. My question is, why does this happen? I spent about 3hrs trying to track down the bug! Does this have something to do with the no-side-effects part of Ocaml? And if so what are the rules for never having something like this happen?
Thanks
EDIT: You guys are very right, I had screwed up fundamentally. This was essentially my code
let my_array = Array.make 10 0;;
let sum_array = ...;;
let my_fun =
do_stuff_with_array args;
sum_array;;
So of course sum_array was being calculated beforehand. Changed it to this and it worked, is this the best solution?
let my_array = Array.make 10 0;;
let sum_array _ = ...;;
let my_fun =
do_stuff_with_array args;
sum_array ();;
OCaml did certainly not compute the sum of the elements of your array "at compile time". There is something you haven't understood about OCaml evaluation order. It's hard to answer your question because there is no question really, it just tells us that you're a bit lost on this topic.
This is fine if we can help you by explaining things to you. It would help, however, if you could help us in spotting where your incomprehension lies, by :
giving a small source code example that does not behave as you expect
and explaining which behavior you would expect and why
The general thing to know about OCaml evaluation order is that, in a module or file, sentences are evaluated from top to bottom, that when you write let x = a in b the expression a is always evaluated before b, and that a function fun x -> a (or equivalent form such as let f x = a) evaluates to itself, without evaluating a at all -- this happens at application time.
Some people like to have a "main" sentence that contains all the side-effects of your code. It is often written like that:
let () =
(* some code that does side-effect *)
If you write code that evaluates and produce side-effects in other part of your file, well, they will be evaluated before or after this sentence depending on whether they are before or after it.

Obfuscate multiplication by 2 [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Help me come up with an obfuscated way to multiply a number by 2, accurate to the second decimal.
Ideas:
use the Russian multiplication technique
trig / other mathematical identities
monte carlo methods
but of course bonus points for CS trickery
edit:
Just remembered that it's probably more appropriate to think of this in terms of significant figures, not accurate decimal places. So go for 4 matching leading digits.
The following perl one-liner doubles the first command-line argument:
perl -e '$/=$\=shift;map$\+=$//(++$|+$|)**$_,(++$...$=);print'
You may say that using perl is cheating because everything is obfuscated in perl. You would not be entirely wrong.
Here's a slightly different approach in (unobfuscated) python:
import math
def double(n) :
if n == 0 :
return 0
a = b = n
for i in range(1,100) :
a = 2 + 1.0/a
a = a - 1
for i in range(1,100) :
b = a * b
a = math.sqrt(a)
return b
If the goal is obfuscation for the sake of it, there is nothing like some red herrings and useless object structure to distract whoever is reading the code from your true goals. For example, instead of using any number directly, you could pull it from a dictionary, or get it from the length of another object (say a list of size two), or even better, hide the number 2 in some string, and then regex it out with an awkward-to-read pattern.
Since you want to make the simple complex, you could do some goofy things with complex numbers. Assuming you have any libraries available for complex arithmetic, you could, for example, leverage the most beautiful equation in mathematics: e^(pi*i) + 1 = 0. For instance in Java using Apache Commons Math (of course you would obfuscate the variable names):
Complex i = new Complex(0, 1);
double two = i.multiply(Math.PI).exp().getReal() + 3 + i.multiply(Math.PI).exp().getImaginary()*5;
The real part is -1, so adding 3 gives us 2. The imaginary part is 0, so multiplying it by 5 and adding it is a red herring that doesn't do anything.*
As long as this is for fun, you can try other variants using other similar identifies. However, I don't recommend relying on this type of thing to truly obfuscate code within a real product. There are packages that obfuscate code for you, and automatically changing variable names to gibberish goes a long way to deterring humans (while still letting the code stay readable for the sanity of developers).
*In floating point arithmetic the imaginary part might not be exactly 0, but you said you were interested in accuracy to two decimal places.
Since this is homework I don't want to just give you the answer but consider the number as it is represented in binary and what sort of binary operands are at your disposal that might help doing in doing multiplication.

Programming Theory - Proving Invariants [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have defined this pseudo-code for recognising strings using a relaxed-trie where the function Next[u,x] gives the set of nodes with u-edges from u ( basically the set of nodes such that (u,x,v) is an edge in T).
Here it is:
U := {1};
while s ≠ λ and U ≠ Ø do
U:= U in u Union Next [u, head(s)];
s:= tail(s)
od;
if U ≠ Ø then
if Final[u] for some u in U then
Accept
else reject
fi
else
reject
fi
Basically I have defined a postcondition for the loop, and given a loop invariant ( I think I have these elements covered, but if you think it will help to explain it go for it).
So I need to give a short argument stating why the invariant is invariant, (ie how it is preserved by the loop body, when the loop condition holds).
I then need to extend this pseudocode such that it can move to a new node without advancing the input :
(I think I would do this by adding another array (say Null) where Null[u] is the set of states it can move to from u without advancing the input)
It should also be changed such that each iteration before looking at the input all states can be reached from a state in U without advancing the input.
Thanks for all your help, am finding these two steps quite difficult, but think my psuedo-code for the first part is fine

Resources