We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › math problem
Page Index Toggle Pages: 1
math problem (Read 587 times)
math problem
May 12th, 2009, 10:05am
 
Hello
I've been working on this:

int x=1;
int y =1;
int z=0;
for(int i=0;i<=7;i=i+1){
 
x=x*-1;
 y=y*x;

 if(i<4){
   z=-1;
 }
 else{
   z=1;
 }
 println("x="+x+"  y="+y+"  z="+z);
}

This program defines "x","y",and "z" coordinates for the vertices from a 3D cube. I think the way "x" and "y" coordinates are calculated is ok, but i can't figure out how to calculate "z" without using "if"and"else". Although the result is correct, i think the way isn't.

Can you help me please?
Thanks.
Re: math problem
Reply #1 - May 12th, 2009, 11:48am
 
Anyway giving the correct result is "right", as long as it isn't incredibly inefficient! Smiley

That said, you can make your code a bit more Java-esque, using some shortcuts:
Code:
int x = 1;
int y = 1;
int z = 1;
for (int i = 0; i < 8; i++) {
x *= -1;
y *= x;
z = i < 4 ? -1 : 1;
println("x="+x+" y="+y+" z="+z);
}

The ? : is actually a conditional in disguise.
If you really don't want a conditional, you can compute z as follow:

z = 1 - 2 * (i / 4);

Not going the readability road, though! Smiley
Re: math problem
Reply #2 - May 12th, 2009, 12:59pm
 
thanks
I think that solves my problem
Wink
Re: math problem
Reply #3 - May 12th, 2009, 1:06pm
 
As PhiLho suggested (in other words) "if it isn't broke, don't fix it."

BUT... Cheesy

I kinda like puzzles.
This was a bit of a challenge to do without comparisons.

It won't work in all cases.
Also, this is not good practice as it does not test for a div/zero condition.

If your goal was to confuse someone trying to take your code, it could throw them off. See http://en.wikipedia.org/wiki/Obfuscated_code

Code:
int x=1;
int y =1;
int z=0;
for(int i=-7;i<=8;i=i+2){//odd start value to skip over zero
x=x*-1;
y=y*x;

z = i / abs(i);

println("x="+x+" y="+y+" z="+z);
}


I think PhiLho's is easier to understand. Smiley
Re: math problem
Reply #4 - May 12th, 2009, 1:16pm
 
not that it matters, as problem already solved, but all three coords can be expressed as f(i) if you wish:
Quote:
  for (int i=0; i<8; i++) {
   int x = (i&1) * 2 - 1;
   int y = (i&2) - 1;
   int z = (i&4) / 2 - 1;
 }

Re: math problem
Reply #5 - May 12th, 2009, 1:36pm
 
davbol wrote on May 12th, 2009, 1:16pm:
not that it matters, as problem already solved

Hey, if we see the question as a puzzle, all answers are good! :D
I like your solution, I saw there was a binary enumeration, but I didn't thought of this way.
Page Index Toggle Pages: 1