SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Guru downtroden's Avatar
    Join Date
    Dec 2004
    Location
    illinois
    Posts
    971
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Arranging collection into groups of 12 (values of 2 or 4)

    So I have a collection of objects, each has a value of either 2 or 4. I'm wanting to group them into collections that equal 12.

    For instance, if the collection begins:
    [4,4,2] and the next object is 4, I would like to skip and insert a '2' object, leaving the 4 for the next group.

    I've done some googling and saw someone use shuffle and shift http://stackoverflow.com/questions/2...emainders-ruby, but this is just grouping to sets of 4 with remainders being evenly distributed.

    Any ideas on where to start with this would be most appreciated.

    Thanks
    your brain reacts in the same way whether you are
    looking at something or thinking about it...

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    It sounds like you're wanting a recursive function which would loop through and append groups of 12 to an array, calling itself until all of the numbers are accounted for.

    Code ruby:
    puts get_twelves([2,4,4,2,2,2,4,2. etc...])
    def get_twelves(nums, groups=[])

    Look through recursive function examples like reduce to understand how they work - they're known to be brain benders.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •