Re: Fibonacci Spiral Help?
Inspect the way the code determines the location of a Fibonacci square (eg the uses of modulus). My understanding is that the squares are repetitive in fours, and so checking the remainder from dividing by 4 may be more appropriate. Also, I assume the getFibonacci method returns the value at position x in the series? Because that code isn't listed I'll just comment that this is in the loop of a drawing routine so it should be fast (precalculated)
Re: Fibonacci Spiral Help?
Calculating Fibonacci can be fast... O(n) with O(1) memory space :)
It might be easier to work with the corners rather than the centers because they are always aligned by at least one axis (either x or y), so there's no need to calculate offsets between different centers. Maybe stick to the top-left corner? Also, in your modulus section, you don't want to modulate with different numbers, but rather with 4 all the time and check to see what the remainder value is.
Code :
for(int x = 1; x < 5; x++)
{
if (x % 4 == 0)
{ }
else if (x % 4 == 1)
{ }
else if (x % 4 == 2)
{ }
else if (x % 4 == 3)
{ }
}
Re: Fibonacci Spiral Help?
Quote:
Originally Posted by
helloworld922
Calculating Fibonacci can be fast... O(n) with O(1) memory space
I dislike big O notation, mainly because I stink at calculating it #-o...but do that in a loop it becomes something like O(n*n) (I know I know, we're talking a loop of five here though ;) )
I'll second Helloworld's advice on working with corners, especially if you plan to do the drawing using g.drawArc(...)
Re: Fibonacci Spiral Help?
Code :
public static int fib(int n)
{
if (n < 3)
{
return 1;
}
int num1 = 1, num2 = 1;
for (int i = 3; i < n; i++)
{
int temp = num1 + num2;
num1 = num2;
num2 = temp;
}
return num2;
}
In a loop, still O(n) time. True dat it's only a loop of 5, but it's still nice to be efficient :)
Re: Fibonacci Spiral Help?
Quote:
Originally Posted by
helloworld922
In a loop, still O(n) time. True dat it's only a loop of 5, but it's still nice to be efficient :)
Sorry, I meant to calculate the series over and over again in a loop. For example (using your fib example function)
Code :
int n = 5;
for ( int i = 0; i < n; i++ ){
int fib = fib(i);
}
As the loop goes through, it recalculates the previously calculated fibonacci values, doing so in a drawing routine which may be called often. Of course, for 5 its not a big deal, but larger values the computation time starts to pile up
This is as opposed to previously computing the series up to n, then accessing these as needed
Code :
/**
*Returns an array containing the Fibonacci sequence up to n in the series
*/
public static int[] fib(int n)
{
int fib[] = new int[n];
if (n < 3)
{
fib[0] = 1;
if ( n == 2 )
fib[1] = 1;
}
for (int i = 3; i < n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
return fib;
}
int fib[] = fib(n);//even better to do this upon construction or whenever the value of n is set
for ( int i = 0; i < n; i++ ){
int num = fib[i];
///do the calculations and drawing
}