Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Jun 8th, 2010  |  syntax: Perl  |  size: 1.66 KB  |  views: 112  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. use strict;
  2. use warnings;
  3.  
  4. my $NUM_RULES = 8;
  5. my $NUM_LINES = 15;
  6. my %rule_table = ();
  7.  
  8. sub log2($)
  9. {
  10.     return log($_[0]) / log(2);
  11. }
  12.  
  13. sub int2bitvec($$)
  14. {
  15.     my ($l, $n) = @_;
  16.     my @s = ();
  17.     unshift @s, ($n >> $l) & 1 while $l--;
  18.     return @s;
  19. }
  20.  
  21. sub bitvec2str($)
  22. {
  23.     return join '', reverse @{$_[0]};
  24. }
  25.  
  26. sub build_rules($)
  27. {
  28.     my @v = int2bitvec($NUM_RULES, $_[0]);
  29.  
  30.     for (my $i = 0; $i < $NUM_RULES; ++$i)
  31.     {
  32.         my @t = int2bitvec(log2($NUM_RULES), $i);
  33.         $rule_table{bitvec2str(\@t)} = $v[$i];
  34.     }
  35. }
  36.  
  37. sub print_rules()
  38. {
  39.     print "\n";
  40.     foreach my $key (sort keys %rule_table)
  41.     {
  42.         print "$key = $rule_table{$key}\n";
  43.     }
  44. }
  45.  
  46. sub line_length($)
  47. {
  48.     return 2 * $_[0] + 1;
  49. }
  50.  
  51. print "Enter a rule: ";
  52. my $n = <STDIN>;
  53.  
  54. ($n =~ /^\d+$/ and $n < 2 ** $NUM_RULES)
  55.     or die "Please specify a positive integer less than " .(2 ** $NUM_RULES). "\n";
  56.  
  57. build_rules($n);
  58. #print_rules();
  59. print "\n";
  60.  
  61. my $prev_line = "";
  62. my $curr_line = "1";
  63. my $pad_print = "";
  64. my $line_print = "";
  65. my $pad = "";
  66.  
  67. for (my $i = 0; $i < $NUM_LINES; ++$i)
  68. {
  69.     $prev_line = $curr_line;
  70.     $curr_line = "";
  71.     $pad = 0 x (((line_length($NUM_LINES) + 2) - line_length($i)) / 2);
  72.  
  73.     $pad_print = $pad;
  74.     $pad_print =~ s/0/ /g;
  75.  
  76.     $line_print = $prev_line;
  77.     $line_print =~ s/0/ /g;
  78.     $line_print =~ s/1/x/g;
  79.  
  80.     print $pad_print . $line_print . $pad_print . "\n";
  81.  
  82.     for (my ($c, $j) = (0, (line_length($NUM_LINES) - line_length($i)) / 2 - 1);
  83.         $c < line_length($i + 1); ++$c, ++$j)
  84.     {
  85.         $curr_line .= $rule_table{substr($pad . $prev_line . $pad, $j, 3)};
  86.     }
  87. }
clone this paste RAW Paste Data