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: 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).

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