Sunday, September 21, 2008

Generating Combinations in Ruby and Javascript

Hey, time to dust off your discrete math text! (The one I used is Discrete Mathematics and Its Applications by Kenneth H. Rosen). The number of combinations of r items that can be selected from n items is given by the formula = n!/r!(n - r)! (note to self, render this with MathML). The following three code blocks show how to return those combinations in Ruby, Javascript, and Javascript with Prototype. Note that these functions yield (in Ruby) or do a callback with (Javascript) each combination. These could easily be modified to return an array of the combinations. After the three code snippets is a live example of the Javascript code. First the Ruby: Now the Javascript: And finally Javascript with Prototype (wow, now like Ruby): Wow, if that doesn't make you want to learn Prototype using Prototype and script.aculo.us: You Never Knew JavaScript Could Do This! then nothing will.

[ combinations ]

4 comments:

  1. And if you need to calculate all possible combinations, here's a nifty way to do it: http://www.semergence.com/2007/08/04/calculating-combinations-in-ruby-from-erlang/

    ReplyDelete
  2. can you tell me how should be the callback function for the javascript example?
    (to be displayed like with the "generate" button. Thanx a lot

    ReplyDelete
  3. Hey Anonymous here is the actual code ran when the "generate" button is clicked for the javascript example: http://gist.github.com/28281

    ReplyDelete
  4. tnx a LOT! It helped :)

    ReplyDelete