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

Pages: 1-4041-

↻ /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: sage 2011-02-13 14:20

sage your disgusting attempt to make people program in haskell

Name: Anonymous 2011-02-13 14:31

I'll do one (or more) later. One in a common language, possibly others in uncommon languages. Once I learn them.

Name: Anonymous 2011-02-13 14:48

i]EXPAND MY ANUS[/i]

Name: Anonymous 2011-02-13 15:16

>>4
Did you mean: EXPAND MY ANUS

Name: Anonymous 2011-02-13 15:22

e  x  p  a  n  d    m  y   a  n  u  s

Name: Anonymous 2011-02-13 15:30

>>4-6
Back to deleted, please.

Name: Anonymous 2011-02-13 15:33

>>7
NIBBLE MY FORESKIN, ANUSBEARD

Name: Anonymous 2011-02-13 15:53

321 GET

Name: Anonymous 2011-02-13 16:17

I've cheated since I wrote it in a langauge that I know, but here I go:

;;; Generic Utils (taken from other code I've written)

(defun ensure-length (sequence n &key (filler nil))
  (if (< (length sequence) n)
      (replace (make-sequence (class-of sequence) n :initial-element filler)
               sequence)
      sequence))

(defun take (sequence n &key (filler nil))  
  (subseq (ensure-length sequence n :filler filler) 0 n))

;; maybe this would be better done as a defun-memoized?
(defmacro memoize-named-function (name)
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (setf (fdefinition ',name) (memoize #',name))))

(defun memoize (function)
  (let ((values (make-hash-table :test #'equal)))
    #'(lambda (&rest args)
        (multiple-value-bind (value present-p)
            (gethash args values)
          (if present-p value
              (setf (gethash args values) (apply function args)))))))

(defun mappend (fn list
                &rest otherlists
                &aux (list (copy-list list)) (otherlists (copy-list otherlists)))         
  (apply #'mapcan fn list otherlists))

(defun insert-inbetween (list element &key (no-last t))
  (let ((new-list
         (mappend #'(lambda (e) (list e element)) list)))
    (if no-last (butlast new-list) new-list)))

(defun merge-strings (&rest strings)
  (apply #'concatenate 'string strings))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defun symbolicate (syms &optional (package *package*))
    (intern (apply #'concatenate 'string (mapcar #'string syms)) package))
  (defun reverse-if (list reverse)
    (if reverse (reverse list) list)))

(defmacro with-gensyms (names &body body)
  `(let ,(loop for name in names collect `(,name (gensym ,(string name))))
     ,@body))


;;; Actual implementation of the challenge

(defun binomial-coefficients (n)  
  (unless (zerop n)
    `(1 ,@(maplist #'(lambda (list)                      
                       (apply #'+ (take list 2 :filler 0)))
                   (binomial-coefficients (1- n))))))

(memoize-named-function binomial-coefficients)

(macrolet ((frob-fun (name format reverse)
             (with-gensyms (string n)
               `(defun ,name (,string ,n)
                  (case ,n
                    (0 "")
                    (1 ,string)
                    (t (format nil ,format
                               ,@(reverse-if `(,string ,n) reverse))))))))
  (frob-fun string-to-the-power "~A^~D" nil)
  (frob-fun string-multiply "~A~D" t))

(defun binomial-element (n k)
  (merge-strings
   (string-to-the-power "a" (- n k))
   (string-to-the-power "b" k)))

(defun newton-binomial-expansion (n)
  (apply #'merge-strings
         (insert-inbetween
          (loop for k to n
                for element = (binomial-element n k)
                for coeff in (binomial-coefficients (1+ n))
                collect (string-multiply element coeff))
          " + ")))

;;; Test
CL-USER> (newton-binomial-expansion 1)
"a + b"
CL-USER> (newton-binomial-expansion 2)
"a^2 + 2ab + b^2"
CL-USER> (newton-binomial-expansion 3)
"a^3 + 3a^2b + 3ab^2 + b^3"
CL-USER> (newton-binomial-expansion 4)
"a^4 + 4a^3b + 6a^2b^2 + 4ab^3 + b^4"
CL-USER> (newton-binomial-expansion 5)
"a^5 + 5a^4b + 10a^3b^2 + 10a^2b^3 + 5ab^4 + b^5"

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(<>)

Name: >>11 2011-02-13 16:27

(altough, admittedly, interpolation is kind of neat and I haven't used a language that has that before)

Name: Anonymous 2011-02-13 16:34

>>10
bold parentheses[o]
[m] tags to not shit up Lisp code indentation
Lisp code
Common Lisp code[/o]
You... you are...
THE COMMON LISPER IS BACK TO /prog/!
I LOVE YOU! I LOVE YOUR POSTS! I READ THEM FIVE TIMES! PLEASE KEEP POSTING!!

Name: Anonymous 2011-02-13 16:36

>>13
I fucked up the whole post.
s/Lisp code indentation/Lisp code highlighting/
I guess I'll go to bed.

Please, >>10, post more.

Name: Anonymous 2011-02-13 16:53

>>1
Whatever:
sub fact {
  my $n = $_[0]--;
  $n *= $_[0] while $_[0]--;
  return $n;
}

Some other stuff too, but i'm tired. How about:
sub binom {
  my $n = shift;
  my $m = $n;
  print "a^$n + ";
  print ($n*($m-$n))."a^$n*b^".($m-$n)." + " while ($n--- 1);
  print "b^$m";
}

I don't know or care if it works.

Name: Anonymous 2011-02-13 16:54

s/1/&&/ >>15

Name: Anonymous 2011-02-13 17:04

i tried doing it in forth but gave up

Name: Anonymous 2011-02-13 17:51

well this is some challenge

Name: >>11 2011-02-13 21:52

>>15
shift
That explains everything.

Name: Anonymous 2011-02-15 6:20

>>11
You're mistake: using Perl

Name: Anonymous 2011-02-15 8:39

I am waiting for a Plankalkül implementation.

Name: Anonymous 2011-02-15 8:47

import System
import Data.List

pascalsTriangle = iterate (\l -> zipWith (+) (0:l) (l++[0])) [1]

aPlusBToTheNthPower n =
    intercalate " + " $ foldl1 (zipWith (++))
        ["": (map show $ init $ tail $ pascalsTriangle !! n) ++ [""], powers "a",
                                                                      reverse $ powers "b"]
    where powers variable =
              "": variable: map ((variable ++) . ('^':) . show) [2..n] 

main =
    do [n] <- getArgs
       print $ aPlusBToTheNthPower $ read n

Name: Anonymous 2011-02-15 13:15


module Binomial where
main=do
    theorem<-readLn::IO Int
    putStrLn $ binomial theorem
    main
cocks=iterate(\cock->zipWith(+)(0:cock)(cock++[0]))[1]
deal n|n==1=""|otherwise=show n
dealer c n|n==0=""|n==1=c|otherwise=c++"^"++show n
dicksort _[]=[]
dicksort _[cock]=[cock]
dicksort dick(cock:cocks)=cock:dick:dicksort dick cocks
toss dick dicks=concat$dicksort dick dicks
binomial n=toss" + "$zipWith3(\cock penis dick->(deal$cock)++(dealer"a"penis)++(dealer"b"dick))(cocks!!n)[n,n-1..0][0..n]

Name: Anonymous 2011-02-15 14:13

>>22

[1 of 1] Compiling Main             ( /prog/I-MENA-HASKALL/binomial.hs, interpreted )
Ok, modules loaded: Main.

*Main> main
*** Exception: user error (Pattern match failure in do expression at /prog/I-MENA-HASKALL/binomial.hs:14:7-9)
*Main>_

Name: VIPPER 2011-02-15 14:21

>>20
What about i am mistake?

Name: Anonymous 2011-02-15 14:24

>>25
You are.

Name: Anonymous 2011-02-15 15:58

>>23
Haskell is so elegant.

Name: Anonymous 2011-02-15 16:03

>>27
Haskell's exquisite syntax was selected with flawless taste and sits on him perfectly.

Name: Anonymous 2011-02-15 16:04

>>24
runghc /prog/I-MENA-HASKALL/binomial.hs 5

Name: Anonymous 2011-02-15 17:33

>>21 here, some more incitation.
This is factorial(5) in Plankalkül, linear notation

[code]P5 R(V0[:32.0]) => R0[:32.0]

1 => Z0[:32.0]

W1 (5) [

i * Z0[:32.0] => Z0[:32.0]

]

Z0[:32.0] => R0[:32.0]

END[code]

from Rojas et al.: Plankalkül: The First High-Level Programming Language and its Implementation, Techn. rep.; 2000

Name: Anonymous 2011-02-15 17:49


P5 R(V0[:32.0]) => R0[:32.0]

1 => Z0[:32.0]

W1 (5) [

i * Z0[:32.0] => Z0[:32.0]

]

Z0[:32.0] => R0[:32.0]

END



my apologies

Name: Anonymous 2011-02-15 17:52

>>31
How is supposed to be human readable?

Name: Anonymous 2011-02-15 18:01

>>32
I hope you did that deliberately. But I know better.

Name: Anonymous 2011-02-16 8:25

>>22

import System
import Data.List

pascalsTriangle = iterate (\l -> zipWith (+) (0:l) (l++[0])) [1]

aPlusBToTheNthPower n =
   intercalate " + " $ foldl1 (zipWith (++)) [coefficients, reverse $ powers "a", powers "b"]
   where
      coefficients = "": (map show $ init $ tail $ pascalsTriangle !! n) ++ [""]
      powers variable =
         "": variable: map ((variable ++) . ('^':) . show) [2..n] 

main =
   do [n] <- getArgs
      putStrLn $ aPlusBToTheNthPower $ read n

Name: clay 2011-02-16 13:16


calcRow(lastRow) {
    var newRow = lastRow;
    push(newRow, 1);
    for(i, x in enumerated(lastRow)){
        if(i > 0)
            newRow[i] = lastRow[i] + lastRow[i-1];
    }
    return newRow;
}

ab(sym, power){
    if(power == 0)
        return;
    print(sym);
    if(power > 1)
        print("^", power);
}

main() {
    var row = Vector([1]);
    var n = 4;
    var i = n;

    while(i > 0) {
        i -= 1;
        row = calcRow(row);
    }

    while( i <= n ){
        if(i > 0)
            print(" + ");

        if(row[i] > 1)
            print(row[i]);

        ab("a", n - i);
        ab("b", i);

        i += 1;
    }

    println();
}


compile with
clay -no-exceptions of course.

Notice that whole program contains only one type declaration(Vector).

Name: Anonymous 2011-02-16 13:19

>>35
This shit looks like JavaScript.

Name: Anonymous 2011-02-16 13:26

>>36 only on surface. Clay as static typed as c++. It's actually like c++ but with implicit template<> and auto everywhere. Oh, and it has multi-dispatching.

Name: Anonymous 2011-02-16 13:31

Name: Anonymous 2011-02-16 13:45

>>38
Seems dead to me.

Name: Anonymous 2011-03-07 15:56

>>17
: fact 1+ 1 tuck +do i * loop ;

: combs ( n i -- nCi )
  over fact over fact / -rot - fact / ;

: .power ( var exponent -- )
  dup 0 > if
    over emit
    dup 1 > if ." ^" dup 0 .r then
  then 2drop ;

: binomexp ( exponent -- )
  dup for
    dup i combs dup 1 > if dup 0 .r then drop
    'a i .power
    'b over i - .power
    ."  "
  next drop ;


Works on GForth.

Name: Anonymous 2011-03-08 8:05

>>40
: combs ( n i -- nCi )
  1 1 d+ 1 tuck +do over i - * i / loop nip ;

: .power ( var exponent -- )
  dup 0 > if
    over emit
    dup 1 > if ." ^" dup 0 .r then
  then 2drop ;

: binomexp ( exponent -- )
  dup for
    dup i combs dup 1 > if dup 0 .r then drop
    'a i .power  'b over i - .power  ."  "
  next drop ;

Name: Anonymous 2011-03-08 8:20

>>39
U MENA HASKAL!

Name: Anonymous 2011-03-08 8:28

>>38
No garbage collection.
>CANCEL DOWNLOAD

Name: Anonymous 2011-03-08 8:35

<---- check em

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