This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # O(nk) | |
| class Array | |
| def unzip ary | |
| return [] if ary.empty? | |
| count = ary.first.count | |
| (0...count).map { |i| | |
| ary.map { |tuple| | |
| raise 'inconsistent tuple size' if tuple.count != count | |
| tuple[i] | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # The MIT License (MIT) | |
| # | |
| # Copyright (c) 2015 Michael Bates | |
| # | |
| # Permission is hereby granted, free of charge, to any person obtaining a copy | |
| # of this software and associated documentation files (the "Software"), to deal | |
| # in the Software without restriction, including without limitation the rights | |
| # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| # copies of the Software, and to permit persons to whom the Software is | |
| # furnished to do so, subject to the following conditions: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Here, I’ve added a function to Array called `partition`. | |
| // In short, the function will partition the Array into a Dictionary based on a function | |
| // which takes an Element of the Array and returns its corresponding Key into the Dictionary. | |
| extension Array { | |
| func partition<Key>(key: (Element)->Key) -> [Key: [Element]] { | |
| var groups = [Key: [Element]]() | |
| for element in self { | |
| let key = key(element) | |
| var group = groups[key] ?? [Element]() |
NewerOlder