DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Stirling Numbers In Ruby

Snippets Manager user avatar by
Snippets Manager
·
Feb. 22, 07 · · Code Snippet
Like (0)
Save
Tweet
501 Views

Join the DZone community and get the full member experience.

Join For Free
From: http://www.ruby-forum.com/topic/95068
Author: Thomas Hafner

http://en.wikipedia.org/wiki/Stirling_number 
http://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind




$cache = {}

def parts(s,u)
  u0 = [s,u].min
  if u0 < 1
    []
  else
    i = (s-1)*s/2+u0-1
    $cache[i] ||
    begin
      a = []
      u0.downto(1) do |n|
        r = s - n
        if (r > 0)
          parts(r,n).each do |elem|
            a.push([n, elem])
          end
        else
          a.push([n])
        end
      end
      $cache[i] = a
      a
    end
  end
end

def part(n)
  parts(n,n).map{|x| x.flatten}
end

p part(5)     #=> [[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Using Unsupervised Learning to Combat Cyber Threats
  • JUnit 5 Tutorial: Nice and Easy [Video]
  • The Evolution of Configuration Management: IaC vs. GitOps
  • Kafka Fail-Over Using Quarkus Reactive Messaging

Comments

Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo