Posts Tagged ‘math’

Project Euler Problem 6 Solution: Clojure

Posted in Programming on April 19th, 2010 by Jamie – 3 Comments

Problem description, from Project Euler

Find the difference between the sum of the squares of the first N natural numbers and the square of the sum.

Solution

This one actually seemed to be easier than the others. No filters required!

    (defn problem06
        [upper]
        (defn sq [n] (* n n))
        (def l (range 1 (+ upper 1)))
        (-
            (sq (reduce + l))
            (reduce + (map sq l))
            )
        )

The biggest hangup I had was that when I originally read the problem, I thought I’d need a power function, and then spent at least 15 minutes determining there was no Clojure core power function. I found some alternatives here:


     ; for integers (cuz it's faster)
     (. (. java.math.BigInteger (valueOf 2)) (pow 5))
     ; for doubles
     (. java.lang.Math (pow 2 -3))

Project Euler Problem 2 Solution: Clojure

Posted in Programming on April 14th, 2010 by Jamie – 2 Comments

Problem 2 Description, from Project Euler

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.

Solutions

My first attempt

The trickiest thing for me was figuring out how to write the fibonacci function in an elegant way. I know that with functional languages, recursion is supposed to be super elegant, and my solution was anything but.

    (defn problem02
        []
        (defn fib
            [termCount]
            (defn fib-help
                [termCount, terms]
                (def rterms (reverse terms))
                (def lst (first rterms))
                (def nlst (first (rest rterms)))
                (if (< (count terms) termCount)
                    (fib-help
                        termCount
                        (reverse (cons (+ lst nlst) rterms))
                        )
                    terms
                    )
                )
            (fib-help termCount, `(1, 2))
            )
        (reduce + (filter
            #(and
                (< % 4000000)
                (even? %)
                )
            (fib 200)
            ))

    )
    (problem02)

A solution by another person

The [site I linked to in the previous article](http://grok-code.com/367/learning-clojure-with-project-euler/) as a much more elegant solution. I really had trouble figuring out how to do an elegant Fibonacci algorithm, although I knew that mine was inelegant!

   (defn e2 [limit]
     (let [fibs2 (lazy-cat [0 1]
                           (map + fibs2 (rest fibs2)))]
       (reduce + (filter #(zero? (mod % 2))
                         (take-while #(< % limit) fibs2)))))

I love the user of *lazy-cat*. I was trying to search for how to do this, but wasn’t sure what this was called. I only knew that the *iterate* function used something like this (I guess I could’ve checked it’s source). I find the use of map interesting, but confusing because it seems as if *fibs2* would return a list and that there should somehow be duplicate values in that list. I’m sure I will come to understand more later.

Project Euler Problem 1 Solution: Clojure

Posted in Programming on April 12th, 2010 by Jamie – 4 Comments

After PhillyETE, I wanted to try out some Clojure, so I decided to solve the first problem of Project Euler. I coded up my own solution using some of the references on the Clojure site.

Project Euler Problem Description, from Project Euler

Find the sum of all the multiples of 3 or 5 below N.
(N is 1000 is this Project Euler problem.)

Solutions

My first attempt

    (def nmbrs (range 0 1000))
    (def multiples
        (filter
            #(and
                (not= % 0)
                (or
                    (=
                        (rem % 3)
                        0
                        )
                    (=
                        (rem % 5)
                        0
                        )
                    )
                )
            nmbrs
            )
        )
    (reduce + multiples)

Another attempt by a different author

Afterwards, I came across a terser, more elegant solution on a site that seems to have had the same idea as I did, Learning Clojure with Project Euler. The site had a really elegant looking solution:

    ; http://grok-code.com/367/learning-clojure-with-project-euler/
    (defn problem01 [limit]
     (reduce + (filter #(or (zero? (mod % 3))
                            (zero? (mod % 5)))
                       (take (- limit 1) (iterate inc 1)))))
    (problem 1000)

My revised attempt

The use of take and iterate are really interesting. I haven’t encountered these “lazy” functions, and was surprised when I tried to run (iterate inc 1) in the REPL. I decided to modify my version with some of the things I learned from the version above, and make it more terse.

    (defn problem01
        [upper]
        (reduce +
            (filter
                #(or
                    (zero?(rem % 3))
                    (zero?(rem % 5))
                    )
                (range 1 upper)
                ))
        )

I’ll be working on some more of the problems in the coming days.

(PS. If you are wondering why I use rem instead of mod, it’s because I am using an older version of clojure with TextMate–I’ve yet to upgrade)

Javascript Gaussian/Banker’s Rounding

Posted in Libraries, Programming on April 16th, 2009 by Jamie – Be the first to comment

Here’s a function for Gaussian/Banker’s Rounding in Javascript adapted from code written by Michael Boon at http://boonedocks.net/.

This can be useful if you’re working with Microsoft languages such as VBScript, which use Banker’s Rounding by default in their Round function. Javascript has no built-in gaussian rounding and, instead, uses Arithmetic rounding. For more information on this, see Wikipedia’s article on rounding, specifically, the Round to Even section.

/*
    Adapted from <a href="http://boonedocks.net/code/bround.inc.phps">http://boonedocks.net/code/bround.inc.phps</a>
Provided under the GNU General Public License
    Contact me for use outside the bounds of that license

    ---------------------------------------------------------------
    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    The GNU General Public License can be found at:

http://www.gnu.org/copyleft/gpl.html

*/
<a href="http://boonedocks.net/code/bround.inc.phps"></a>
Number.prototype.gaussianRound = Number.prototype.bankersRound = function bround(iDec) {
    return Math.gaussianRound ( this, iDec );
};

Math.gaussianRound = Math.bankersRound = function (dVal, iDec) {

    // banker's style rounding or round-half-even
    // (round down when even number is left of 5, otherwise round up)
    // dVal is value to round
    // iDec specifies number of decimal places to retain

    var
		dFuzz=0.00001, // to deal with floating-point precision loss
		iRoundup=0, // amount to round up by
		iSign= dVal != 0.0 ? Math.floor ( dVal/ Math.abs( dVal ) ) : 1;

	dVal=Math.abs(dVal);

    // get decimal digit in question and amount to right of it as a fraction
    dWorking = dVal * Math.pow ( 10.0, iDec + 1 ) -
		Math.floor ( dVal * Math.pow ( 10.0, iDec ) ) * 10.0;

	iEvenOddDigit =
		Math.floor ( dVal * Math.pow ( 10.0, iDec) ) -
		Math.floor ( dVal * Math.pow ( 10.0, iDec-1 ) ) * 10.0;

    if ( Math.abs ( dWorking - 5.0 ) &lt; dFuzz)
		iRoundup= iEvenOddDigit &amp; 1 ? 1 : 0; // even testing using bitwise and
    else
		iRoundup= dWorking &gt; 5.0 ? 1 : 0;

    return iSign * ( ( Math.floor ( dVal * Math.pow (10.0,iDec ) ) + iRoundup )/ Math.pow(10.0,iDec) );
};

Switch to our mobile site