The Daily Static
  The Daily Static
UF Archives
Register
UF Membership
Ad Free Site
Postcards
Community

Geekfinder
UFie Gear
Advertise on UF

Forum Rules
& FAQ


Username

Password


Create a New Account

 
 

Back to UserFriendly Strip Comments Index

You know your a carnivore when... by thephilosifer2005-02-14 17:14:45
  Check it for mad rabbit disease first. (n/t) by jiteo2005-02-14 17:22:03
    Mad rabbit's? like in Monty Python? by thephilosifer2005-02-14 17:24:19
      Teh One Mad Rabbit by jiteo2005-02-14 18:01:02
        Recursively! (n/t) by LionsPhil2005-02-14 18:03:45
          Phear Teh One Recursive Mad Rabbit! (n/t) by jiteo2005-02-14 18:10:05
            int rabbit(int i) by williamashbless2005-02-14 18:12:55
              Go Fibonacci's Rabbits. ;-) by bwkaz2005-02-14 18:42:40
                O(n) if it's written right. by williamashbless 2005-02-14 18:59:28
int rabbit(int n)
{
   int r1=1,r2=1;
   while (n>2)
   {
      int r=r1+r2;
      r1=r2;
      r2=r;
      --n;
   }
   return r2;
}

Of course, you can do the top-down data caching DP version of it, but it's O(n) too.

int rabbit(int n)
{
   int *p=new int[n+1]; 
   //assume exception thrown if out of mem
   int i;
   for (i=0;i<=n;++i)
      p[i]=0;
   int r=rabbit2(n,p);
   delete[]p;
   return r;
}

int rabbit2(int n,int *p)
{
   //if we've done this one, return it.
   if (p[n]!=0)
      return p[n];

   //generate value, but cache it.   
   p[n]=rabbit2(n-1,p)+rabbit2(n-2,p);

   //return cached item
   return p[n];
}


The former's way easier to write. Many DP problems can be written ground-up, but you can end up solving for more values than you need if the recursion doesn't hit every possible combination of parameters. It does in this case, and its simple.

The latter's the cached solution. It's harder to write, requires you to have or make a cache of the right size, get rid of it maybe if you're grabbing it from a heap like I am... but it looks just like the recursive version, and is easy to convert from a recursive version to the cached version.

Betcha didn't think you'd learn anything in THIS thread. :D


Yeah, the straight recursive one's pretty bad.

[ Reply ]
                  Yeesh, that's right, I forgot by bwkaz2005-02-14 19:02:31

 

[Todays Cartoon Discussion] [News Index]

Come get yer ARS (Account Registration System) Source Code here!
All images, characters, content and text are copyrighted and trademarks of J.D. Frazer except where other ownership applies. Don't do bad things, we have lawyers.
UserFriendly.Org and its operators are not liable for comments or content posted by its visitors, and will cheerfully assist the lawful authorities in hunting down script-kiddies, spammers and other net scum. And if you're really bad, we'll call your mom. (We're not kidding, we've done it before.)