Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

↻ /prog/ Challenge [Vol. λfx.f x] ↻

Name: Anonymous 2011-02-13 12:14

THE CHALLENGE: Write a program that, given a number n, prints the expansion of (a+b)^n.

Example: 4a^4 + 4a^3b + 6a^2b^2 + 4ab^3 + b^4

HOWEVER: You must do the above in a language you do not have any experience with. Never programmed in Haskell before? Gather some documentation and go for it.

(Well, you're advised to do that. I can't possibly know whether or not you know a programming language.)

Name: Anonymous 2011-02-13 16:25

What the fuck, Perl 5. I'm never using this again. (Perl faggots: am I doing something wrong here?)

sub fact {
  my $n = 1;
  for (my $i = 1; $i <= $_[0]; $i++) {
    $n *= $i;
  }
  return $n;
}
 
sub choose {
  my ($n, $k) = @_;
  return fact($n) / (fact($k) * fact($n - $k));
}
 
sub format_exp {
  my ($base, $exp) = @_;
 
  if ($exp == 0) {
    return "";
  } elsif ($exp == 1) {
    return $base;
  } else {
    return "$base^$exp"
  }
}
 
sub binom {
  my @bin = ();
  for (my $i = 0; $i <= $_[0]; $i++) {
    $j = $_[0] - $i;
    $a = format_exp('a', $j);
    $b = format_exp('b', $i);
    $c = choose($_[0], $i);
    if ($c == 1) {
      $c = ''
    }
    push @bin, "$c$a$b";
  }
  return join(' + ', @bin);
}
 
print binom(<>)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List