zip Function for Arrays

Actionscript:
  1. var one:Array = [1,2,3];
  2. var two:Array = [10, 20, 30];
  3.  
  4. var zipOneTwo:Array = zip(one, two);
  5.  
  6. // trace each tupple
  7. for each (var tuple:Array in zipOneTwo){
  8.     trace(tuple);
  9. }
  10.  
  11. /* outputs:
  12. 1,10
  13. 2,20
  14. 3,30
  15. */
  16.  
  17. function zip(a:Array, b:Array):Array{
  18.     var longest:Array = (a.length>= b.length) ? a : b;
  19.     var zipped:Array = [];
  20.     for (var i:int = 0; i<longest.length; i++){
  21.         zipped.push([a[i], b[i]]);
  22.     }
  23.     return zipped;
  24. }

This snippet shows a function called zip that takes two arrays and returns a two dimensional array of tuples. Just imagine that each array is one side of a zipper and you'll sort of get the idea...

I do wish flash would trace this:

[[1, 10], [2, 20], [3, 30]]

We shouldn't have to write a utility function to see the real array structure...

I've been messing with haskell for a few days now... just for fun I thought I'd write a few functions inspired by it... this is the first one...

This entry was posted in arrays and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted December 31, 2009 at 1:00 pm | Permalink

    Since longest.length doesn’t change, consider caching it as a local variable for a nice speed boost.

  2. Posted December 31, 2009 at 1:07 pm | Permalink

    @jackson, yeah I’m aware of that… also, push() us usually slower than incrementing an index value… sometimes I write nasty looking optimized code and sometimes I try to write simple looking code… this is just an example of the latter

  3. Posted January 21, 2010 at 9:34 pm | Permalink

    Is hard to undestand how arrays work, but once you play you understand

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*