Advertisement
zinch

zip & unzip

Sep 28th, 2014
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 1.21 KB | None | 0 0
  1.  
  2. /*
  3.   Zips two lists into the map.
  4.   Size of the map is that of the shortest list.
  5.   Items from the first list become keys and items from
  6.   the second one become values
  7. */
  8. def zip(xs, ys) {
  9.   if (xs && ys) {
  10.     [(xs[0]):(ys[0])] + zip(xs.size() > 1 ?  xs[1..-1] :[],
  11.                 ys.size() > 1 ? ys[1..-1] : [])
  12.   } else {
  13.     [:]
  14.   }
  15. }
  16.  
  17. assert zip([], [])              == [:]
  18. assert zip([], [1])             == [:]
  19. assert zip([1], [])             == [:]
  20. assert zip(['a'], [1])          == [a:1]
  21. assert zip(('a'..'b'), [1])     == [a:1]
  22. assert zip(['a'], [1,2])        == [a:1]
  23. assert zip(('a'..'c'), (1..3))  == [a:1, b:2, c:3]
  24.  
  25. /*
  26.   Unzips the map into list of lists
  27.   where the first list will contain all the keys
  28.   and the second list will contain all teh values
  29. */
  30. def unzip(zs) {
  31.  
  32.   def keys = zs.keySet().toList()
  33.  
  34.   if (keys) {
  35.     def key = keys[0]
  36.     def res = unzip(keys.size() > 1 ? zs.subMap(keys[1..-1]) : [:])
  37.    
  38.     [[key] + /*list of keys*/ res[0], [zs[key]] + /*list of values*/ res[1]]
  39.   } else {
  40.     [[],[]]
  41.   }
  42. }
  43.  
  44. assert unzip([:])             == [[],[]]
  45. assert unzip([a:1])           == [['a'],[1]]
  46. assert unzip([a:1, b:2, c:3]) == [['a', 'b', 'c'], [1, 2, 3]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement