Algorithm to split an array into N groups based on item index (should be something simple)

I feel that it should be something very simple and obvious but just stuck on this for the last half an hour and can't move on.

All I need is to split an array of elements into N groups based on element index.

For example we have an array of 30 elements [e1,e2,...e30], that has to be divided into N=3 groups like this:

group1: [e1, ..., e10]
group2: [e11, ..., e20]
group3: [e21, ..., e30]

I came up with nasty mess like this for N=3 (pseudo language, I left multiplication on 0 and 1 just for clarification):

for(i=0;i<array_size;i++) {
   if(i>=0*(array_size/3) && i<1*(array_size/3) {
      print "group1";
   } else if(i>=1*(array_size/3) && i<2*(array_size/3) {
      print "group2";
   } else if(i>=2*(array_size/3) && i<3*(array_size/3)
      print "group3";
   }
}

But what would be the proper general solution?

Thanks.

Answers


What about something like this?

for(i=0;i<array_size;i++) {
  print "group" + (Math.floor(i/(array_size/N)) + 1)
}

Need Your Help

Send AS3 score variable to PHP file

php actionscript-3 variables

I have a variable called score in my flash game and I want to post the score from my flash game to a php file called test.php; the last part of the AS3 code when game is finished is:

Undefined method 'instantiate_observers' error after restarting spork server

ruby-on-rails rspec spork

I was running tests using spork with no problem, however, occasionally I have to restart the spork server to get it to recognize newly added routes. On this occasion, I restarted the spork server, ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.