Recursive Collatz conjecture in PHP

May 18th, 2010

I stumbled across a blog post by Brie Gordon about the Collatz conjecture, so naturally I had to Wikipedia it. The simple story is that for any given integer, if it is even you divide it by 2 and if it is odd you multiply it by 3 and add 1. You continue this pattern with the returned numbers, and eventually the number will reach 1.  I’ve heard of it before, but not since one of my earlier computer science classes, so to commemorate the re-discovery I wrote a recursive PHP function to display the progression.  Here is the function:

  1. function collatz($num)
  2. {
  3.     if($num == 1)
  4.     {
  5.         echo "<p style='color: red'>" . $num . "</p>n";
  6.         return;
  7.     }
  8.  
  9.     if($num % 2 == 0) //even
  10.     {
  11.         echo "<p style='color: green'>" . $num . "</p>n";
  12.         return collatz($num / 2);
  13.     }
  14.     else
  15.     {
  16.         echo "<p style='color: red'>" . $num . "</p>n";
  17.         return collatz(3 * $num + 1);
  18.     }
  19. }

View Demo

Creating a simple, extensible CodeIgniter authentication library

May 10th, 2010

While it is true that there are a whole slew of third party CodeIgniter authentication systems, there are a few compelling reasons to write your own. In my own experience, third party authentication systems are too feature-rich and complex for a particular application or they are not currently being supported, which means they may not work with newer versions of CI or may have outstanding functional and security bugs. Instead of tackling a new codebase to fight these issues, you may be better off rolling your own solution. This tutorial is for those of you who may need some help starting out.
Read the rest of this entry »

External anchors in CodeIgniter

May 7th, 2010

When using CodeIgniter, I almost never use bare anchor elements to create links.  Instead, I use the anchor(“controller/function”, “text”) function in the url helper.  At first glance, however, it appears that you cannot use the anchor() function to link to external urls and thus have to write the anchor html element yourself.

This is not true. Instead of using the bare html element, I decided that I would extend the helper to include the functionality I wanted.  When I looked into the helper, though, it appears that the CodeIgniter team had already done it!  However, as of CI 1.7.2, the functionality is undocumented. Luckily, it is easy to do.

<?php echo anchor("http://www.codeigniter.com", "CodeIgniter"); ?>

Read the rest of this entry »