Begin main content

Fibonacci Perl Golf

There are plenty of Perl golf O(N) implementations of Fibonacci generators (and in other languages also), but I wondered in the shower today if I could do it without either an explicit initialisation or explicit previous variables. While I feel tracking both values in a single string is kindof cheating, this is the best I have come up with so far:

perl -le 'print$2while s/(\d*):?(\d*)/($1+$2||1).":$1"/e' |head -10

At 45 characters it's not a size winner (see this thread for implementations as short as 27 characters and 21 in Ruby) but I like it for a few reasons: it is complete (many other implementations skip the leading 1); it contains no initialisation (or indeed any implicit assigment operations); it uses only one state variable ($_).

Update: Perl golf is addictive! I had to let go of my "no implicit assignment" rule, but here is a similar 37 character solution. A weakness this version suffers from is that since it requires both single and double quote characters it's tough to fit into a shell one liner:

$_="$':".($'+$`||1),print$`while x./:/

Update 2: As pointed out on the related perlmonks thread, I can save a few chars with perl 5.10 using say:

perl -E 'say$2while s/(\d*):?(\d*)/($1+$2||1).":$1"/e' |head -10
$_="$':".($'+$`||1),say$`while x./:/

05:33 PM, 05 Oct 2008 by Mark Aufflick Permalink | Short Link | Comments (2)

XML

Blog Categories

software (39)
..cocoa (21)
  ..heads up 'tunes (5)
..ruby (6)
..lisp (3)
..perl (4)
..openacs (1)
mac (20)
embedded (2)
..microprocessor (2)
  ..avr (1)
electronics (3)
design (1)
photography (25)
..black and white (6)
..A day in Sydney (18)
..The Daily Shoot (6)
food (2)
Book Review (2)

Notifications

Icon of Envelope Request notifications

Syndication Feed

XML

Recent Comments

  1. Unregistered Visitor: An other Script
  2. Unregistered Visitor: A message in there?
  3. Unregistered Visitor: using Amazon S3
  4. Unregistered Visitor: Thank you ! Thank you ! Thank you !
  5. Unregistered Visitor: Umbrello on leopard
  6. Unregistered Visitor: Script gor generate for library
  7. Unregistered Visitor: Similar but different
  8. Unregistered Visitor: Thanks for fixing my problem!
  9. Unregistered Visitor: Pop up once the category is been defined
  10. Unregistered Visitor: smal amendment