commit 6cffd04a4f09cb9111d98ee70dc4314fcb5fc56e Author: Nate Cook Date: Fri Oct 2 08:48:29 2020 -0500 Initial import diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.md b/.github/ISSUE_TEMPLATE/BUG_REPORT.md new file mode 100755 index 0000000..6c47f5b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/BUG_REPORT.md @@ -0,0 +1,33 @@ +--- +name: 🐛 Bug Report +about: Something isn't working as expected +--- + + + +Replace this paragraph with a short description of the incorrect incorrect behavior. If this is a regression, please note the last version that the behavior was correct in addition to your current version. + +**Swift Algorithms version:** `0.0.1` or the `main` branch, for example. +**Swift version:** Paste the output of `swift --version` here. + +### Checklist +- [ ] If possible, I've reproduced the issue using the `main` branch of this package +- [ ] I've searched for [existing GitHub issues](https://github.com/apple/swift-algorithms/issues) + +### Steps to Reproduce +Replace this paragraph with an explanation of how to reproduce the incorrect behavior. Include a simple code example, if possible. + +### Expected behavior +Describe what you expect to happen. + +### Actual behavior +Describe or copy/paste the behavior you observe. diff --git a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md new file mode 100755 index 0000000..8fbe390 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md @@ -0,0 +1,13 @@ +--- +name: 💡 Feature Request +about: A suggestion for a new feature +--- + + + +Replace this paragraph with a description of your proposed feature. Code samples that show what's missing, or what new capabilities will be possible, are very helpful! Provide links to existing issues or external references/discussions, if appropriate. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..0292a17 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: ❓ Discussion Forum + url: https://forums.swift.org/c/related-projects/algorithms/ + about: Questions about using Swift Algorithms? Ask here! diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..baf9192 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,21 @@ + + +Replace this paragraph with a description of your changes and rationale. Provide links to an existing issue or external references/discussions, if appropriate. + +### Checklist +- [ ] I've added at least one test that validates that my change is working, if appropriate +- [ ] I've followed the code style of the rest of the project +- [ ] I've read the [Contribution Guidelines](CONTRIBUTING.md) +- [ ] I've updated the documentation if necessary diff --git a/.github/PULL_REQUEST_TEMPLATE/NEW.md b/.github/PULL_REQUEST_TEMPLATE/NEW.md new file mode 100644 index 0000000..f27009f --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE/NEW.md @@ -0,0 +1,38 @@ + + +### Description +Replace this paragraph with a description of your changes and rationale. Provide links to an existing issue or external references/discussions, if appropriate. + +### Detailed Design +Include any additional information about the design here. At minimum, show any new API: + +```swift +extension Collection { + /// The new feature implemented by this pull request. + func newFeature() +} +``` + +### Documentation Plan +How has the new feature been documented? Have the relevant portions of the guides been updated in addition to symbol-level documentation? + +### Test Plan +How is the new feature tested? + +### Source Impact +What is the impact of this change on existing users? Does it deprecate or remove any existing API? + +### Checklist +- [ ] I've added at least one test that validates that my change is working, if appropriate +- [ ] I've followed the code style of the rest of the project +- [ ] I've read the [Contribution Guidelines](CONTRIBUTING.md) +- [ ] I've updated the documentation if necessary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a1a59bd --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ +/.swiftpm diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..14e2f57 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,35 @@ +# CHANGELOG + + + +This project follows semantic versioning. While still in major version `0`, +source-stability is only guaranteed within minor versions (e.g. between +`0.0.3` and `0.0.4`). If you want to guard against potentially source-breaking +package updates, you can specify your package dependency using +`.upToNextMinor(from: "0.0.1")` as the requirement. + +## [Unreleased] + +*No changes yet.* + +--- + +## [0.0.1] - 2020-10-07 + +- **Swift Algorithms** initial release. + +--- + +This changelog's format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + + + +[Unreleased]: https://github.com/apple/swift-algorithms/compare/0.0.1...HEAD +[0.0.1]: https://github.com/apple/swift-algorithms/releases/tag/0.0.1 + + + + + diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..2b0a603 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,55 @@ +# Code of Conduct +To be a truly great community, Swift.org needs to welcome developers from all walks of life, +with different backgrounds, and with a wide range of experience. A diverse and friendly +community will have more great ideas, more unique perspectives, and produce more great +code. We will work diligently to make the Swift community welcoming to everyone. + +To give clarity of what is expected of our members, Swift.org has adopted the code of conduct +defined by [contributor-covenant.org](https://www.contributor-covenant.org). This document is used across many open source +communities, and we think it articulates our values well. The full text is copied below: + +### Contributor Code of Conduct v1.3 +As contributors and maintainers of this project, and in the interest of fostering an open and +welcoming community, we pledge to respect all people who contribute through reporting +issues, posting feature requests, updating documentation, submitting pull requests or patches, +and other activities. + +We are committed to making participation in this project a harassment-free experience for +everyone, regardless of level of experience, gender, gender identity and expression, sexual +orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or +nationality. + +Examples of unacceptable behavior by participants include: +- The use of sexualized language or imagery +- Personal attacks +- Trolling or insulting/derogatory comments +- Public or private harassment +- Publishing other’s private information, such as physical or electronic addresses, without explicit permission +- Other unethical or unprofessional conduct + +Project maintainers have the right and responsibility to remove, edit, or reject comments, +commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of +Conduct, or to ban temporarily or permanently any contributor for other behaviors that they +deem inappropriate, threatening, offensive, or harmful. + +By adopting this Code of Conduct, project maintainers commit themselves to fairly and +consistently applying these principles to every aspect of managing this project. Project +maintainers who do not follow or enforce the Code of Conduct may be permanently removed +from the project team. + +This code of conduct applies both within project spaces and in public spaces when an +individual is representing the project or its community. + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by +contacting a project maintainer at [conduct@swift.org](mailto:conduct@swift.org). All complaints will be reviewed and +investigated and will result in a response that is deemed necessary and appropriate to the +circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter +of an incident. + +*This policy is adapted from the Contributor Code of Conduct [version 1.3.0](http://contributor-covenant.org/version/1/3/0/).* + +### Reporting +A working group of community members is committed to promptly addressing any [reported +issues](mailto:conduct@swift.org). Working group members are volunteers appointed by the project lead, with a +preference for individuals with varied backgrounds and perspectives. Membership is expected +to change regularly, and may grow or shrink. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..e36bf96 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,10 @@ +By submitting a pull request, you represent that you have the right to license +your contribution to Apple and the community, and agree by submitting the patch +that your contributions are licensed under the [Swift +license](https://swift.org/LICENSE.txt). + +--- + +Before submitting the pull request, please make sure you have tested your +changes and that they follow the Swift project [guidelines for contributing +code](https://swift.org/contributing/#contributing-code). diff --git a/Guides/Chain.md b/Guides/Chain.md new file mode 100644 index 0000000..1c46ad3 --- /dev/null +++ b/Guides/Chain.md @@ -0,0 +1,49 @@ +# Chain + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chain.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/ChainTests.swift)] + +Concatenates two collections with the same element type, one after another. + +This operation is available through the `chained(with:)` method on any sequence. + +```swift +let numbers = [10, 20, 30].chained(with: 1...5) +// Array(numbers) == [10, 20, 30, 1, 2, 3, 4, 5] +// +let letters = "abcde".chained(with: "FGHIJ") +// String(letters) == "abcdeFGHIJ" +``` + +Unlike placing two collections in an array and calling `joined()`, chaining +permits different collection types, performs no allocations, and can preserve +the shared conformances of the two underlying types. + +## Detailed Design + +The `chained(with:)` method is added as an extension method on the `Sequence` +protocol: + +```swift +extension Sequence { + public func chained(with other: S) -> Concatenation + where Element == S.Element +} + +``` + +The resulting `Chain` type is a sequence, with conditional conformance to the +`Collection`, `BidirectionalCollection`, and `RandomAccessCollection` when both +the first and second arguments conform. + +### Naming + +This method’s and type’s name match the term of art used in other languages and +libraries. + +### Comparison with other langauges + +**Rust:** Rust provides a `chain` function that concatenates two iterators. + +**Ruby/Python:** Ruby and Python’s `itertools` both define a `chain` function +for concatenating collections of different kinds. diff --git a/Guides/Chunked.md b/Guides/Chunked.md new file mode 100644 index 0000000..d23a001 --- /dev/null +++ b/Guides/Chunked.md @@ -0,0 +1,91 @@ +# Chunked + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Chunked.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/ChunkedTests.swift)] + +Break a collection into subsequences where consecutive elements pass a binary +predicate, or where all elements in each chunk project to the same value. + +There are two variations of the `chunked` method: `chunked(by:)` and +`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive +elements, separating chunks where the predicate returns `false`. For example, +you can chunk a collection into ascending sequences using this method: + +```swift +let numbers = [10, 20, 30, 10, 40, 40, 10, 20] +let chunks = numbers.chunked(by: { $0 <= $1 }) +// [[10, 20, 30], [10, 40, 40], [10, 20]] +``` + +The `chunk(on:)` method, by contrast, takes a projection of each element and +separates chunks where the projection of two consecutive elements is not equal. + +```swift +let names = ["David", "Kyle", "Karoy", "Nate"] +let chunks = names.chunked(on: \.first!) +// [["David"], ["Kyle", "Karoy"], ["Nate"]] +``` + +These methods are related to the [existing SE proposal][proposal] for chunking a +collection into subsequences of a particular size, potentially named something +like `chunked(length:)`. Unlike the `split` family of methods, the entire +collection is included in the chunked result — joining the resulting chunks +recreates the original collection. + +```swift +c.elementsEqual(c.chunked(...).joined()) +// true +``` + +[proposal]: https://github.com/apple/swift-evolution/pull/935 + +## Detailed Design + +The two methods are added as extension to `Collection`, with two matching +versions that return a lazy wrapper added to `LazyCollectionProtocol`. + +```swift +extension Collection { + public func chunked( + by belongInSameGroup: (Element, Element) -> Bool + ) -> [SubSequence] + + public func chunked( + on projection: (Element) -> Subject + ) -> [SubSequence] + } + + extension LazyCollectionProtocol { + public func chunked( + by belongInSameGroup: @escaping (Element, Element) -> Bool + ) -> LazyChunked + + public func chunked( + on projection: @escaping (Element) -> Subject + ) -> LazyChunked +} +``` + +The `LazyChunked` type is bidirectional when the wrapped collection is +bidirectional. + +### Complexity + +The eager methods are O(_n_), the lazy methods are O(_1_). + +### Naming + +The operation performed by these methods is similar to other ways of breaking a collection up into subsequences. In particular, the predicate-based `split(where:)` method looks similar to `chunked(on:)`. You can draw a distinction between these different operations based on the resulting subsequences: + +- `split`: *In the standard library.* Breaks a collection into subsequences, removing any elements that are considered "separators". The original collection cannot be recovered from the result of splitting. +- `chunked`: *In this package.* Breaks a collection into subsequences, preserving each element in its initial ordering. Joining the resulting subsequences re-forms the original collection. +- `sliced`: *Not included in this package or the stdlib.* Breaks a collection into potentially overlapping subsequences. + + +### Comparison with other langauges + +**Ruby:** Ruby’s `Enumerable` class defines `chunk_while` and `chunk`, which map +to the proposed `chunked(by:)` and `chunked(on:)` methods. + +**Rust:** Rust defines a variety of size-based `chunks` methods, but doesn’t +include any with the functionality described here. diff --git a/Guides/Combinations.md b/Guides/Combinations.md new file mode 100644 index 0000000..4e3073a --- /dev/null +++ b/Guides/Combinations.md @@ -0,0 +1,80 @@ +# Combinations + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Combinations.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/CombinationsTests.swift)] + +A type that computes combinations of a collection’s elements. + +The `combinations(ofCount:)` method returns a sequence of all the different +combinations of a collection’s elements, with each combination in the order of +the original collection. + +```swift +let numbers = [10, 20, 30, 40] +for combo in numbers.combinations(ofCount: 2) { + print(combo) +} +// [10, 20] +// [10, 30] +// [10, 40] +// [20, 30] +// [20, 40] +// [30, 40] +``` + +The combinations of elements are presented in increasing lexicographic order of +the collection’s original ordering. Values that are repeated in the original +collection are always treated as separate values in the resulting combinations: + +```swift +let numbers2 = [20, 10, 10] +for combo in numbers2.combinations(ofCount: 2) { + print(perm) +} +// [20, 10] +// [20, 10] +// [10, 10] +``` + +## Detailed Design + +The `combinations(ofCount:)` method is declared as a `Collection` extension, +and returns a `Combinations` type: + +```swift +extension Collection { + public func combinations(ofCount k: Int) -> Combinations +} +``` + +Since the `Combinations` type needs to store an array of the collection’s +indices and mutate the array to generate each permutation, `Combinations` only +has `Sequence` conformance. Adding `Collection` conformance would require +storing the array in the index type, which would in turn lead to copying the +array at every index advancement. + +### Complexity + +Calling `combinations(ofCount:)` accesses the count of the collection, so it’s an +O(1) operation for random-access collections, or an O(_n_) operation otherwise. +Creating the iterator for a `Combinations` instance and each call to +`Combinations.Iterator.next()` is an O(_n_) operation. + +### Naming + +The parameter label in `combination(ofCount:)` is the best match for the +Swift API guidelines. A few other options were considered: + +- When the standard library uses `of` as a label, the parameter is generally + the object of the operation, as in `type(of:)` and `firstIndex(of:)`, and + not a configuration detail. +- The `count` label typically indicates the count of the resulting collection, + as in the `repeatElement(_:count:)` function or the `String(repeating:count:)` + initializer. +- `k` is used a term of art for combinations and permutations, but isn't + widely used in programming contexts. + +### Comparison with other langauges + +**Rust/Ruby/Python:** Rust, Ruby, and Python all define functions with +essentially the same semantics as the method described here. diff --git a/Guides/Cycle.md b/Guides/Cycle.md new file mode 100644 index 0000000..7d93a63 --- /dev/null +++ b/Guides/Cycle.md @@ -0,0 +1,62 @@ +# Cycle + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Cycle.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/CycleTests.swift)] + +Iterate over a collection forever, or a set number of times. + +```swift +for (odd, n) in zip([true, false].cycled(), 1...) { + // ... +} + +for x in (1...3).cycled(times: 3) { + print(x) +} +// Prints 1 through 3 three times +``` + +`cycled(times:)` combines two other existing standard library functions +(`repeatElement` and `joined`) to provide a more expressive way of repeating a +collection's elements a limited number of times. + +## Detailed Design + +Two new methods are added to collections: + +```swift +extension Collection { + func cycled() -> Cycle + + func cycled(times: Int) -> FlattenSequence> +} +``` + +The new `Cycle` type is a sequence only, given that the `Collection` protocol +design makes infinitely large types impossible/impractical. Note that despite +its name, the returned `FlattenSequence` will always have `Collection` +conformance, and will have `BidirectionalCollection` conformance when called on +a bidirectional collection. + +### Complexity + +Calling these methods is O(_1_). + +### Naming + +There's a slight off-by-one ambiguity around the naming of `cycled(times:)`, +since one can reasonably interpret the number of cycles as including the first +run-through of elements (the actual semantics) or starting after the first +set. This ambiguity is present in all the different potential names for this +function: `repeated(times:)`, `cycled(repetitions:)`, etc. + +### Comparison with other langauges + +**Rust:** The `cycle` method repeats an iterator's elements forever. I don’t see +anything that matches the `cycled(times:)` behavior. + +**Ruby:** Passing a number to `cycle` limits the number of repetitions, like the +`cycled(times:)` here. + +**Python:** Python’s `itertools` includes a `cycle` method, which caches the +elements of the iterator on the first pass. \ No newline at end of file diff --git a/Guides/Indexed.md b/Guides/Indexed.md new file mode 100644 index 0000000..de168f8 --- /dev/null +++ b/Guides/Indexed.md @@ -0,0 +1,34 @@ +# Indexed + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Indexed.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/IndexedTests.swift)] + +The `enumerated` method, but pairing each element with its index instead of an +incrementing integer counter. + +This is essentially equivalent to `zip(x.indices, x)`: + +```swift +let numbers = [10, 20, 30, 40, 50] +var matchingIndices: Set = [] +for (i, n) in numbers.indexed() { + if n.isMultiple(of: 20) { + matchingIndices.insert(i) + } +} +// matchingIndices == [1, 3] +``` + +## Detailed Design + +The `indexed` method returns an `Indexed` type: + +```swift +extension Sequence { + func indexed() -> Indexed +} +``` + +`Indexed` scales from a sequence up to a random-access collection, depending on +its base type. + diff --git a/Guides/Partition.md b/Guides/Partition.md new file mode 100644 index 0000000..ec1e630 --- /dev/null +++ b/Guides/Partition.md @@ -0,0 +1,94 @@ +# Partition + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Partition.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/PartitionTests.swift)] + +Methods for performing a stable partition on mutable collections, and for +finding the partitioning index in an already partitioned collection. + +The standard library’s existing `partition(by:)` method, which re-orders the +elements in a collection into two partitions based on a given predicate, doesn’t +guarantee stability for either partition. That is, the order of the elements in +each partition doesn’t necessarily match their relative order in the original +collection. These new methods expand on the existing `partition(by:)` by +providing stability for one or both partitions. + +```swift +// existing partition(by:) - unstable ordering +var numbers = [10, 20, 30, 40, 50, 60, 70, 80] +let p1 = numbers.partition(by: { $0.isMultiple(of: 20) }) +// p1 == 4 +// numbers == [10, 70, 30, 50, 40, 60, 20, 80] + +// new stablePartition(by:) - keeps the relative order of both partitions +numbers = [10, 20, 30, 40, 50, 60, 70, 80] +let p2 = numbers.stablePartition(by: { $0.isMultiple(of: 20) }) +// p2 == 4 +// numbers == [10, 30, 50, 70, 20, 40, 60, 80] +``` + +Since partitioning is frequently used in divide-and-conquer algorithms, we also +include a variant that accepts a range parameter to avoid copying when mutating +slices, as well as a range-based variant of the existing standard library +partition. + +The `partitioningIndex(where:)` method returns the index of the start of the +second partition when called on an already partitioned collection. + +```swift +let numbers = [10, 30, 50, 70, 20, 40, 60] +let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) }) +// numbers[.. Bool + ) rethrows -> Index + + mutating func stablePartition( + subrange: Range, + by belongsInSecondPartition: (Element) throws -> Bool + ) rethrows -> Index + + mutating func partition( + subrange: Range, + by belongsInSecondPartition: (Element) throws -> Bool + ) rethrows -> Index +} + +extension Collection { + func partitioningIndex( + where belongsInSecondPartition: (Element) throws -> Bool + ) rethrows -> Index +} +``` + +### Complexity + +The existing partition is an O(_n_) operations, where _n_ is the length of the +range to be partitioned, while the stable partition is O(_n log n_). Both +partitions have algorithms with improved performance for bidirectional +collections, so it would be ideal for those to be customization points were they +to eventually land in the standard library. + +`partitioningIndex(where:)` is a slight generalization of a binary search, and +is an O(_log n_) operation for random-access collections; O(_n_) otherwise. + +### Comparison with other langauges + +**C++:** The `` library defines `partition`, `stable_partition`, and +`partition_point` functions with similar semantics to these. Notably, in the C++ +implementation, the result of partitioning has the opposite polarity, with the +passing elements in the first partition and failing elements in the second. + +**Rust:** Rust includes the `partition` method, which returns separate +collections of passing and failing elements, and `partition_in_place`, which +matches the Swift standard library’s existing `partition(by:)` method. diff --git a/Guides/Permutations.md b/Guides/Permutations.md new file mode 100644 index 0000000..19341c7 --- /dev/null +++ b/Guides/Permutations.md @@ -0,0 +1,99 @@ +# Permutations + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Permutations.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/PermutationsTests.swift)] + +A type that computes permutations of a collection’s elements, or of a subset of +those elements. + +The `permutations(ofCount:)` method, when called without the `ofCount` +parameter, returns a sequence of all the different permutations of a +collection’s elements: + +```swift +let numbers = [10, 20, 30] +for perm in numbers.permutations() { + print(perm) +} +// [10, 20, 30] +// [10, 30, 20] +// [20, 10, 30] +// [20, 30, 10] +// [30, 10, 20] +// [30, 20, 10] +``` + +Passing a value for `ofCount` generates partial permutations, each with the +specified number of elements: + +```swift +for perm in numbers.permutations(ofCount: 2) { + print(perm) +} +// [10, 20] +// [10, 30] +// [20, 10] +// [20, 30] +// [30, 10] +// [30, 20] +``` + +The permutations or partial permutations are generated in increasing +lexicographic order of the collection’s original ordering (rather than the order +of the elements themselves). The first permutation will always consist of +elements in their original order, and the last will have the elements in the +reverse of their original order. + +Values that are repeated in the original collection are always treated as +separate values in the resulting permutations: + +```swift +let numbers2 = [20, 10, 10] +for perm in numbers2.permutations() { + print(perm) +} +// [20, 10, 10] +// [20, 10, 10] +// [10, 20, 10] +// [10, 10, 20] +// [10, 20, 10] +// [10, 10, 20] +``` + +## Detailed Design + +The `permutations(ofCount:)` method is declared as a `Collection` extension, +and returns a `Permutations` type: + +```swift +extension Collection { + public func permutations(ofCount k: Int? = nil) -> Permutations +} +``` + +Since the `Permutations` type needs to store an array of the collection’s +indices and mutate the array to generate each permutation, `Permutations` only +has `Sequence` conformance. Adding `Collection` conformance would require +storing the array in the index type, which would in turn lead to copying the +array at every index advancement. + +### Complexity + +Calling `permutations()` is an O(1) operation. Creating the iterator for a +`Permutations` instance and each call to `Permutations.Iterator.next()` is an +O(_n_) operation. + +### Naming + +See the ["Naming" section for `combinations(ofCount:)`](Combinations.md#naming) for detail. + +### Comparison with other langauges + +**C++:** The `` library defines a `next_permutation` function that +advances an array of comparable values through their lexicographic orderings. +This function is tricky to use and understand, so while it’s included in +`swift-algorithms` as an implementation detail of the `Permutations` type, it +isn’t public. + +**Rust/Ruby/Python:** Rust, Ruby, and Python all define functions with +essentially the same semantics as the method described here. diff --git a/Guides/Product.md b/Guides/Product.md new file mode 100644 index 0000000..171b690 --- /dev/null +++ b/Guides/Product.md @@ -0,0 +1,71 @@ +# Product + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Product.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/ProductTests.swift)] + +A function for iterating over every pair of elements in two different +collections. + +```swift +let seasons = ["winter", "spring", "summer", "fall"] +for (year, season) in product(1900...2020, seasons) { + // ... +} + +// Is equivalent to: +for years in 1900...2020 { + for season in seasons { + // ... + } +} +``` + +When either collection is empty, the resulting wrapper collection is also empty. + +## Detailed Design + +The `product` function takes (at minimum) a sequence and a collection and +returns a `Product2` type: + +```swift +public func product( + _ s1: Base1, _ s2: Base2 +) -> Product2 +``` + +We require `Collection` conformance for `Base2`, since it needs to be iterated +over multiple times. `Base1`, by contrast, is only iterated over a single time, +so it can be a sequence. + +The `Product2` type wraps the base sequence and collection, and acts as a +sequence in the base case, upgrading to a collection, a bidirectional +collection, and a random-access collection when both base collections have those +conformances. + +We don't provide higher arities (like `Product3`, `Product4`, etc.) at this +time to match the standard library's `Zip2` type. Users can compose multiple +calls to `product` if they would like higher arities. + +### Complexity + +Since the `product` function returns a wrapper type, that call is O(1); +collection operations on the resulting wrapper are O(_m \* n_). + +### Naming + +This function and the resulting collection provide the cartestian product of two +collections. While `product` is precedented in other languages, the name has an +unfortunate overlap with multiplication, where `product(numbers1, numbers2)` +could be seen as producing an element-wise product. + +### Comparison with other langauges + +**Ruby:** You can call the `product` method on an array, passing one or more +arrays to form n-ary tuples — passing a single array gives the same semantics as +this function. + +**Python:** Passing two or more collections to `product` returns the product of +those collections. Passing one collection and a `repeat=n` parameter is +equivalent to passing that collection `n` times. For example, `product("ABC", +repeat=2)` yields `"AA", "AB", "AC", "BA", "BB", "BC", "CA", "CB", "CC"`. + diff --git a/Guides/RandomSampling.md b/Guides/RandomSampling.md new file mode 100644 index 0000000..dc737f9 --- /dev/null +++ b/Guides/RandomSampling.md @@ -0,0 +1,149 @@ +# Random Sampling + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/RandomSample.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/RandomSampleTests.swift)] + +Operations for randomly selecting `k` elements without replacement from a +sequence or collection. + +Use these methods for sampling multiple elements from a collection, optionally +maintaining the relative order of the elements. Each method has an overload that +takes a `RandomNumberGenerator` as a parameter. + +```swift +var source = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + +source.randomSample(count: 4) +// e.g. [30, 10, 70, 50] +source.randomStableSample(count: 4) +// e.g. [20, 30, 80, 100] +// +var rng = SplitMix64(seed: 0) +source.randomSample(count: 4, using: &rng) +``` + +## Detailed Design + +The four methods are declared as below, as well as an additional overload of the +two `randomSample(count:)` methods for `Collection`. + +```swift +extension Sequence { + func randomSample(count: Int) -> [Element] + + func randomSample( + count: Int, using: inout G + ) -> [Element] +} + +extension Collection { + func randomStableSample(count: Int) -> [Element] + + func randomStableSample( + count: Int, using: inout G + ) -> [Element] +} +``` + +The value passed as `count` must always be non-negative. If `count` is larger +than the length of the collection it’s called on, then the returned array +contains all the elements of the collection. + +### Related types + +These methods do not rely on additional types — they eagerly select the required +number of elements and return an array. + +### Complexity + +The `randomSample` method uses reservoir sampling, which allows the method to be +O(_k_) when called on a random-access collection. When called on a sequence or a +non-random-access collection, the algorithm requires O(_k_) random numbers and +accesses O(_n_) elements of the collection. + +The `randomStableSample` method uses selection sampling, which is an O(_n_) +algorithm. This algorithm requires the count of the collection in advance, which +restricts its use to collections — a sequence-based version would need to save +the elements to a temporary array, which we generally don’t want to do for this +kind of operation. + +### Naming + +The standard library already declares `randomElement()` on `Sequence`, which +returns a single random element. The `randomSample(count:)` name is chosen to +align with `randomElement`, but be more distinguishable than something like +`randomElements`. Other names considered include `sample` and `choose`. + +### Comparison with other langauges + +**C++:** As of C++17, the `` library includes a `sample` function +that provides linear performance. This algorithm is stable for all source +iterators that conform to `LegacyForwardIterator` (roughly `Collection` in +Swift), but is unstable otherwise. + +**Ruby/Python:** Ruby and Python both define `sample` functions that return +either a single random element or, when you pass a count, a list of random +elements. The order of the returned elements is unstable. + +## Other Considerations + +### Post-sample shuffling + +Simple implementations of reservoir sampling tend to return some of the initial +elements in the same order they appear in the array. To avoid this bias, the +unstable implementation of `randomSample` explicitly shuffles the elements +before returning them. + +To see the bias without shuffling, consider the following example that uses a +hypothetical `randomElementsUnshuffled` method. When selecting three out of +four elements from an array, whenever any of the first three elements are +included in the result, they are always in their original positions. Elements +selected after the initial `count` are in randomly selected positions. + +```swift +// This shows the behavior WITHOUT post-sample shuffling. +// Selecting 3/4 elements, there are only four possible outcomes: +let source = [10, 20, 30, 40] +source.randomElementsUnshuffled(count: 3) // [10, 20, 30] +source.randomElementsUnshuffled(count: 3) // [40, 20, 30] +source.randomElementsUnshuffled(count: 3) // [10, 40, 30] +source.randomElementsUnshuffled(count: 3) // [10, 20, 40] +``` + +The proposed `randomElements` method has no positional bias: + +```swift +// The current behavior shuffles the elements, erasing the bias: +let source = [10, 20, 30, 40] +source.randomElements(count: 3) // [20, 30, 10] +source.randomElements(count: 3) // [40, 20, 30] +// ...several more possible outcomes +``` + +Since only the resulting array is shuffled, this additional reordering has an +O(_k_) performance cost. + +### Reproducibility + +This doesn’t address the ongoing issue of versioning RNG algorithms. It poses +the same problem as the existing high-level methods, such as +`randomElement(using:)` and `Int.random(in:using:)`, in that changes to the +sampling algorithm in future versions of the library will change the expected +output for repeatable RNGs. While we don't currently make any guarantees about +future versions of the stdlib producing identical results, users routinely +make that assumption. + +### Index-based overloads + +Because none of these methods are mutating or have special behavior based on the +underlying collection type, we don’t need a separate set of methods for working +specifically with indices. A collection’s `indices` typically has the same +performance characteristics as the collection itself, so a user can call +`collection.indices.randomSample(count:)` to get a number of random indices. + +### Lazy sampling + +The stable version of sampling could theoretically return a lazy wrapper +instead of eagerly creating the sample. However, this isn’t well-motivated and +poses some challenges, such as needing to store a copy of the random generator +and potentially needing to cache the randomly-generated values. \ No newline at end of file diff --git a/Guides/Rotate.md b/Guides/Rotate.md new file mode 100644 index 0000000..18f1455 --- /dev/null +++ b/Guides/Rotate.md @@ -0,0 +1,69 @@ +# Rotate + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Rotate.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/RotateTests.swift)] + +A mutating method that rotates the elements of a collection to new positions. + +```swift +var numbers = [10, 20, 30, 40, 50, 60] +let p = numbers.rotate(at: 2) +// numbers == [30, 40, 50, 60, 10, 20] +// p == 4 -- numbers[p] == 10 +``` + +To work around the CoW / slice mutation problem for divide-and-conquer +algorithms, which are the idiomatic use case for rotation, this also includes +variants that take a range: + +```swift +var numbers = [10, 20, 30, 40, 50, 60] +numbers.rotate(subrange: 0..<3, at: 1) +// numbers = [20, 30, 10, 40, 50, 60] +numbers.rotate(subrange: 3..<6, at: 4) +// numbers = [20, 30, 10, 50, 60, 40] +``` + +## Detailed Design + +This adds the two `MutableCollection` methods shown above: + +```swift +extension MutableCollection { + mutating func rotate(at p: Index) -> Index + + mutating func rotate( + subrange: Range, + at p: Index + ) -> Index +} +``` + +### Complexity + +Rotation is a O(_n_) operation, where _n_ is the length of the range being +rotated. The `BidirectionalCollection` version of rotation significantly lowers +the number of swaps required per element, so `rotate` would need to be a +`MutableCollection` customization point were it adopted by the standard library. + +### Naming + +The index parameter has been proposed as `shiftingToStart` in the past; this +proposal uses the simpler `at` label. `shiftingToStart` introduces the idea of +a "shift", which can sound like shifting just that single element to the +beginning of the collection. + +For the range-based overloads, the label could be omitted. That is, instead of +using `subrange:`, the method could be called as +`numbers.rotate(0..<3, at: 2)`. + +### Comparison with other langauges + +**C++:** The `` library defines a `rotate` function with similar +semantics to this one. + +**Ruby:** You can rotate the elements of an array by a number of positions, +either forward or backward (by passing a negative number). For zero-indexed +collections, forward rotation by e.g. 3 elements is equivalent to +`rotate(at: 3)`. + diff --git a/Guides/Unique.md b/Guides/Unique.md new file mode 100644 index 0000000..e9016ee --- /dev/null +++ b/Guides/Unique.md @@ -0,0 +1,53 @@ +# Unique + +[[Source](https://github.com/apple/swift-algorithms/blob/main/Sources/Algorithms/Unique.swift) | + [Tests](https://github.com/apple/swift-algorithms/blob/main/Tests/AlgorithmsTests/UniqueTests.swift)] + +Methods to strip repeated elements from a sequence or collection. + +The `uniqued()` method returns an array, dropping duplicate elements +from a sequence. The `uniqued(on:)` method does the same, using +the result of the given closure to determine the "uniqueness" of each +element. + +```swift +let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1] + +let unique = numbers.uniqued() +// unique == [1, 2, 3] +``` + +## Detailed Design + +Both methods are available for sequences, with the simplest limited to +when the element type conforms to `Hashable`. Both methods preserve +the relative order of the elements. + +```swift +extension Sequence where Element: Hashable { + func uniqued() -> [Element] +} + +extension Sequence { + func uniqued(on: (Element) throws -> T) rethrows -> [Element] + where T: Hashable +} +``` + +### Complexity + +The `uniqued` methods are O(_n_) in both time and space complexity. + +### Comparison with other langauges + +**C+\+:** The `` library defines a `unique` function that removes +consecutive equal elements. + +**Ruby:** Ruby defines a `uniq()` method that acts like `uniqued()`, as well as +a variant that takes a mapping block to a property that should be unique, +matching `uniqued(on:)`. + +**Rust:** Rust includes `unique()` and `unique_by()` methods that lazily +compute the unique elements of a collection, storing the set of already seen +elements in the iterator. + diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..61b0c78 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,211 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +## Runtime Library Exception to the Apache 2.0 License: ## + + + As an exception, if you use this Software to compile your source code and + portions of this Software are embedded into the binary product as a result, + you may redistribute such product without providing attribution as would + otherwise be required by Sections 4(a), 4(b) and 4(d) of the License. diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..109d787 --- /dev/null +++ b/Package.swift @@ -0,0 +1,32 @@ +// swift-tools-version:5.1 +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import PackageDescription + +let package = Package( + name: "swift-algorithms", + products: [ + .library( + name: "Algorithms", + targets: ["Algorithms"]), + ], + dependencies: [ + ], + targets: [ + .target( + name: "Algorithms", + dependencies: []), + .testTarget( + name: "SwiftAlgorithmsTests", + dependencies: ["Algorithms"]), + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..6bc15bc --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ +# Swift Algorithms + +**Swift Algorithms** is an open-source package of sequence and collection algorithms, along with their related types. + +Read more about the package, and the intent behind it, in the [announcement on swift.org](https://swift.org/blog/swift-algorithms/). + +## Contents + +#### Combinations / permutations + +- [`combinations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Combinations.md): Combinations of a particular size of the elements in a collection. +- [`permutations(ofCount:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md): Permutations of a particular size of the elements in a collection, or of the full collection. + +#### Mutating algorithms + +- [`rotate(toStartAt:)`, `rotate(subrange:toStartAt:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Rotate.md): In-place rotation of elements. +- [`stablePartition(by:)`, `stablePartition(subrange:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Partition.md): A partition that preserves the relative order of the resulting prefix and suffix. + +#### Combining collections + +- [`chained(with:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chain.md): Concatenates two collections with the same element type. +- [`product(_:_:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Product.md): Iterates over all the pairs of two collections; equivalent to nested `for`-`in` loops. +- [`cycled()`, `cycled(times:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Cycle.md): Repeats the elements of a collection forever or a set number of times. + +#### Subsetting operations + +- [`randomSample(count:)`, `randomSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection. +- [`randomStableSample(count:)`, `randomStableSample(count:using:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/RandomSampling.md): Randomly selects a specific number of elements from a collection, preserving their original relative order. +- [`uniqued()`, `uniqued(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Unique.md): The unique elements of a collection, preserving their order. + +#### Other useful operations + +- [`chunked(by:)`, `chunked(on:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/Chunked.md): Eager and lazy operations that break a collection into chunks based on either a binary predicate or when the result of a projection changes. +- [`indexed()`](https://github.com/apple/swift-algorithms/blob/main/Guides/Indexed.md): Iterate over tuples of a collection's indices and elements. + + +## Adding Swift Algorithms as a Dependency + +To use the `Algorithms` library in a SwiftPM project, +add the following line to the dependencies in your `Package.swift` file: + +```swift +.package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"), +``` + +Because `Algorithms` is under active development, +source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`). +If you don't want potentially source-breaking package updates, +use this dependency specification instead: + +```swift +.package(url: "https://github.com/apple/swift-algorithms", .upToNextMinor(from: "0.0.1")), +``` + +Finally, include `"Algorithms"` as a dependency for your executable target: + +```swift +let package = Package( + // name, platforms, products, etc. + dependencies: [ + .package(url: "https://github.com/apple/swift-algorithms", from: "0.0.1"), + // other dependencies + ], + targets: [ + .target(name: "", dependencies: [ + .product(name: "Algorithms", package: "swift-algorithms"), + ]), + // other targets + ] +) +``` diff --git a/Sources/Algorithms/Chain.swift b/Sources/Algorithms/Chain.swift new file mode 100644 index 0000000..e8500aa --- /dev/null +++ b/Sources/Algorithms/Chain.swift @@ -0,0 +1,271 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A concatenation of two sequences with the same element type. +public struct Chain + where Base1.Element == Base2.Element +{ + /// The first sequence in this chain. + public let base1: Base1 + + /// The second sequence in this chain. + public let base2: Base2 + + internal init(base1: Base1, base2: Base2) { + self.base1 = base1 + self.base2 = base2 + } +} + +extension Chain: Sequence { + /// The iterator for a `Chain` sequence. + public struct Iterator: IteratorProtocol { + internal var iterator1: Base1.Iterator + internal var iterator2: Base2.Iterator + + internal init(_ concatenation: Chain) { + iterator1 = concatenation.base1.makeIterator() + iterator2 = concatenation.base2.makeIterator() + } + + public mutating func next() -> Base1.Element? { + return iterator1.next() ?? iterator2.next() + } + } + + public func makeIterator() -> Iterator { + Iterator(self) + } +} + +extension Chain: Collection where Base1: Collection, Base2: Collection { + /// A position in a `Chain` collection. + public struct Index: Comparable { + // The internal index representation, which can either be an index of the + // first collection or the second. The `endIndex` of the first collection + // is not to be used as a value - iterating over indices should go straight + // from the penultimate index of the first collection to the start of the + // second. + internal enum Representation : Equatable { + case first(Base1.Index) + case second(Base2.Index) + } + + internal let position: Representation + + /// Creates a new index into the first underlying collection. + internal init(first i: Base1.Index) { + position = .first(i) + } + + /// Creates a new index into the second underlying collection. + internal init(second i: Base2.Index) { + position = .second(i) + } + + public static func < (lhs: Index, rhs: Index) -> Bool { + switch (lhs.position, rhs.position) { + case (.first, .second): + return true + case (.second, .first): + return false + case let (.first(l), .first(r)): + return l < r + case let (.second(l), .second(r)): + return l < r + } + } + } + + public var startIndex: Index { + // If `base1` is empty, then `base2.startIndex` is either a valid position + // of the first element in `base2` or equal to `base2.endIndex`. + return base1.isEmpty + ? Index(second: base2.startIndex) + : Index(first: base1.startIndex) + } + + public var endIndex: Index { + return Index(second: base2.endIndex) + } + + public subscript(i: Index) -> Base1.Element { + switch i.position { + case let .first(i): + return base1[i] + case let .second(i): + return base2[i] + } + } + + public func index(after i: Index) -> Index { + switch i.position { + case let .first(i): + assert(i != base1.endIndex) + let next = base1.index(after: i) + return next == base1.endIndex + ? Index(second: base2.startIndex) + : Index(first: next) + case let .second(i): + return Index(second: base2.index(after: i)) + } + } + + public func index(_ i: Index, offsetBy n: Int) -> Index { + if n == 0 { return i } + return n > 0 + ? offsetForward(i, by: n, limitedBy: endIndex)! + : offsetBackward(i, by: -n, limitedBy: startIndex)! + } + + public func index( + _ i: Index, + offsetBy n: Int, + limitedBy limit: Index + ) -> Index? { + if n == 0 { return i } + return n > 0 + ? offsetForward(i, by: n, limitedBy: limit) + : offsetBackward(i, by: -n, limitedBy: limit) + } + + private func offsetForward( + _ i: Index, by n: Int, limitedBy limit: Index + ) -> Index? { + switch (i.position, limit.position) { + case let (.first(i), .first(limit)): + let d = base1.distance(from: i, to: base1.endIndex) + if n < d { + return base1.index(i, offsetBy: n, limitedBy: limit) + .map(Index.init(first:)) + } else { + // The limit only has an effect here if it's "above" `i` + if limit >= i { + return Index(first: limit) + } else { + return Index( + second: base2.index(base2.startIndex, offsetBy: n - d)) + } + } + + case let (.first(i), .second(limit)): + let d = base1.distance(from: i, to: base1.endIndex) + if n < d { + return Index(first: base1.index(i, offsetBy: n)) + } else { + return base2.index( + base2.startIndex, offsetBy: n - d, limitedBy: limit) + .map(Index.init(second:)) + } + + case let (.second(i), .first): + // `limit` has no effect here + return Index(second: base2.index(i, offsetBy: n)) + + case let (.second(i), .second(limit)): + return base2.index(i, offsetBy: n, limitedBy: limit) + .map(Index.init(second:)) + } + } + + private func offsetBackward( + _ i: Index, by n: Int, limitedBy limit: Index + ) -> Index? { + switch (i.position, limit.position) { + case let (.first(i), .first(limit)): + return base1.index(i, offsetBy: -n, limitedBy: limit) + .map(Index.init(first:)) + + case let (.first(i), .second): + // `limit` has no effect here + return Index(first: base1.index(i, offsetBy: -n)) + + case let (.second(i), .first(limit)): + let d = base2.distance(from: base2.startIndex, to: i) + if n <= d { + return Index(second: base2.index(i, offsetBy: -n)) + } else { + return base1.index(base1.endIndex, offsetBy: -n - d, limitedBy: limit) + .map(Index.init(first:)) + } + + case let (.second(i), .second(limit)): + let d = base2.distance(from: base2.startIndex, to: i) + if n <= d { + return base2.index(i, offsetBy: -n, limitedBy: limit) + .map(Index.init(second:)) + } else { + return Index( + first: base1.index(base1.endIndex, offsetBy: -n - d)) + } + } + } + + // TODO: Add distance(from:to:) +} + +extension Chain: BidirectionalCollection + where Base1: BidirectionalCollection, Base2: BidirectionalCollection +{ + public func index(before i: Index) -> Index { + assert(i != startIndex, "Can't advance before startIndex") + switch i.position { + case let .first(i): + return Index(first: base1.index(before: i)) + case let .second(i): + return i == base2.startIndex + ? Index(first: base1.index(before: base1.endIndex)) + : Index(second: base2.index(before: i)) + } + } +} + +extension Chain: RandomAccessCollection + where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} + +extension Chain: Equatable where Base1: Equatable, Base2: Equatable {} +extension Chain: Hashable where Base1: Hashable, Base2: Hashable {} + +//===----------------------------------------------------------------------===// +// chained(with:) +//===----------------------------------------------------------------------===// + +extension Sequence { + /// Returns a new sequence that iterates over this sequence, followed by the + /// given sequence. + /// + /// You can pass a sequence or collection of any type that has the same + /// element type as this sequence. This example chains a closed range of `Int` + /// with an array of `Int`: + /// + /// let small = 1...3 + /// let big = [100, 200, 300] + /// for num in small.chained(with: big) { + /// print(num) + /// } + /// // 1 + /// // 2 + /// // 3 + /// // 100 + /// // 200 + /// // 300 + /// + /// - Parameter other: The sequence to iterate over after this sequence. + /// - Returns: A sequences that follows iteration of this sequence with + /// `other`. + /// + /// - Complexity: O(1) + public func chained(with other: S) -> Chain + where Element == S.Element + { + Chain(base1: self, base2: other) + } +} diff --git a/Sources/Algorithms/Chunked.swift b/Sources/Algorithms/Chunked.swift new file mode 100644 index 0000000..4b131ba --- /dev/null +++ b/Sources/Algorithms/Chunked.swift @@ -0,0 +1,188 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +public struct LazyChunked { + /// The collection that this instance provides a view onto. + public let base: Base + + /// The projection function. + internal var belongInSameGroup: (Base.Element, Base.Element) -> Bool +} + +extension LazyChunked: LazyCollectionProtocol { + /// A position in a chunked collection. + public struct Index: Comparable { + /// The lower bound of the chunk at this position. + internal var lowerBound: Base.Index + + /// The upper bound of the chunk at this position. + /// + /// `upperBound` is optional so that computing `startIndex` can be an O(1) + /// operation. When `upperBound` is `nil`, the actual upper bound is found + /// when subscripting or calling `index(after:)`. + internal var upperBound: Base.Index? + + public static func == (lhs: Index, rhs: Index) -> Bool { + // Only use the lower bound to test for equality, since sometimes the + // `startIndex` will have an upper bound of `nil` and sometimes it won't, + // such as when retrieved by: + // `c.index(before: c.index(after: c.startIndex))`. + // + // Since each index represents the range of a disparate chunk, no two + // unique indices will have the same lower bound. + lhs.lowerBound == rhs.lowerBound + } + + public static func < (lhs: Index, rhs: Index) -> Bool { + // Only use the lower bound to test for ordering, as above. + lhs.lowerBound < rhs.lowerBound + } + } + + /// Returns the index in the base collection for the first element that + /// doesn't match the current chunk. + internal func endOfChunk(from i: Base.Index) -> Base.Index { + guard i != base.endIndex else { return base.endIndex } + return base[base.index(after: i)...] + .firstIndex(where: { !belongInSameGroup($0, base[i]) }) ?? base.endIndex + } + + public var startIndex: Index { + Index(lowerBound: base.startIndex) + } + + public var endIndex: Index { + Index(lowerBound: base.endIndex, upperBound: base.endIndex) + } + + public func index(after i: Index) -> Index { + let upperBound = i.upperBound ?? endOfChunk(from: i.lowerBound) + let end = endOfChunk(from: upperBound) + return Index(lowerBound: upperBound, upperBound: end) + } + + public subscript(position: Index) -> Base.SubSequence { + let upperBound = position.upperBound + ?? endOfChunk(from: position.lowerBound) + return base[position.lowerBound.. Base.Index { + // Get the projected value of the last element in the range ending at `end`. + let lastOfPreviousChunk = base[base.index(before: end)] + + // Search backward from `end` for the first element whose projection isn't + // equal to `lastOfPreviousChunk`. + if let firstMismatch = base[.. Index { + let start = startOfChunk(endingAt: i.lowerBound) + return Index(lowerBound: start, upperBound: i.lowerBound) + } +} + +//===----------------------------------------------------------------------===// +// lazy.chunked(by:) +//===----------------------------------------------------------------------===// + +extension LazyCollectionProtocol { + /// Returns a lazy collection of subsequences of this collection, chunked by + /// the given predicate. + /// + /// - Complexity: O(1). When iterating over the resulting collection, + /// accessing each successive chunk has a complexity of O(*m*), where *m* + /// is the length of the chunk. + public func chunked( + by belongInSameGroup: @escaping (Element, Element) -> Bool + ) -> LazyChunked { + LazyChunked(base: elements, belongInSameGroup: belongInSameGroup) + } + + /// Returns a lazy collection of subsequences of this collection, chunked by + /// grouping elements that project to the same value. + /// + /// - Complexity: O(1). When iterating over the resulting collection, + /// accessing each successive chunk has a complexity of O(*m*), where *m* + /// is the length of the chunk. + public func chunked( + on projection: @escaping (Element) -> Subject + ) -> LazyChunked { + LazyChunked( + base: elements, + belongInSameGroup: { projection($0) == projection($1) }) + } +} + +//===----------------------------------------------------------------------===// +// chunked(by:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns a collection of subsequences of this collection, chunked by + /// the given predicate. + /// + /// - Complexity: O(*n*), where *n* is the length of this collection. + public func chunked( + by belongInSameGroup: (Element, Element) -> Bool + ) -> [SubSequence] { + guard !isEmpty else { return [] } + var result: [SubSequence] = [] + + var start = startIndex + var current = startIndex + while true { + let next = index(after: current) + if next == endIndex { break } + + if !belongInSameGroup(self[current], self[next]) { + result.append(self[start..( + on projection: (Element) -> Subject + ) -> [SubSequence] { + chunked(by: { projection($0) == projection($1) }) + } +} + diff --git a/Sources/Algorithms/Combinations.swift b/Sources/Algorithms/Combinations.swift new file mode 100644 index 0000000..571da60 --- /dev/null +++ b/Sources/Algorithms/Combinations.swift @@ -0,0 +1,153 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +public struct Combinations { + /// The collection to iterate over for combinations. + public let base: Base + internal var k: Int + + internal init(_ base: Base, k: Int) { + self.base = base + self.k = base.count < k ? -1 : k + } + + public var count: Int { + func binomial(n: Int, k: Int) -> Int { + switch k { + case n, 0: return 1 + case n...: return 0 + case (n / 2 + 1)...: return binomial(n: n, k: n - k) + default: return n * binomial(n: n - 1, k: k - 1) / k + } + } + + return k >= 0 + ? binomial(n: base.count, k: k) + : 0 + } +} + +extension Combinations: Sequence { + public struct Iterator: IteratorProtocol { + internal let base: Base + internal var indexes: [Base.Index] + internal var finished: Bool + + internal init(_ combinations: Combinations) { + self.base = combinations.base + self.finished = combinations.k < 0 + self.indexes = combinations.k < 0 + ? [] + : Array(combinations.base.indices.prefix(combinations.k)) + } + + /// Advances the current indices to the next set of combinations. If + /// `indexes.count == 3` and `base.count == 5`, the indices advance like + /// this: + /// + /// [0, 1, 2] + /// [0, 1, 3] + /// [0, 1, 4] * + /// // * `base.endIndex` reached in `indexes.last` + /// // Advance penultimate index and propagate that change + /// [0, 2, 3] + /// [0, 2, 4] * + /// [0, 3, 4] * + /// [1, 2, 3] + /// [1, 2, 4] * + /// [1, 3, 4] * + /// [2, 3, 4] * + /// // Can't advance without needing to go past `base.endIndex`, + /// // so the iteration is finished. + internal mutating func advance() { + guard !indexes.isEmpty else { + // Initial state for combinations of 0 elements is an empty array with + // `finished == false`. Even though no indexes are involved, advancing + // from that state means we are finished with iterating. + finished = true + return + } + + let i = indexes.count - 1 + base.formIndex(after: &indexes[i]) + if indexes[i] != base.endIndex { return } + + var j = i + while indexes[i] == base.endIndex { + j -= 1 + guard j >= 0 else { + // Finished iterating over combinations + finished = true + return + } + + base.formIndex(after: &indexes[j]) + for k in indexes.indices[(j + 1)...] { + indexes[k] = base.index(after: indexes[k - 1]) + if indexes[k] == base.endIndex { + break + } + } + } + } + + public mutating func next() -> [Base.Element]? { + if finished { return nil } + defer { advance() } + return indexes.map { i in base[i] } + } + } + + public func makeIterator() -> Iterator { + Iterator(self) + } +} + +extension Combinations: Equatable where Base: Equatable {} +extension Combinations: Hashable where Base: Hashable {} + +//===----------------------------------------------------------------------===// +// combinations(count:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns a collection of combinations of this collection's elements, with + /// each combination having the specificed number of elements. + /// + /// This example prints the different combinations of three from an array of + /// four colors: + /// + /// let colors = ["fuchsia", "cyan", "mauve", "magenta"] + /// for combo in colors.combinations(ofCount k: 3) { + /// print(combo.joined(separator: ", ")) + /// } + /// // fuchsia, cyan, mauve + /// // fuchsia, cyan, magenta + /// // fuchsia, mauve, magenta + /// // cyan, mauve, magenta + /// + /// The returned collection presents combinations in a consistent order, where + /// the indices in each combination are in ascending lexicographical order. + /// That is, in the example above, the combinations in order are the elements + /// at `[0, 1, 2]`, `[0, 1, 3]`, `[0, 2, 3]`, and finally `[1, 2, 3]`. + /// + /// If `k` is zero, the resulting sequence has exactly one element, an empty + /// array. If `k` is greater than the number of elements in this sequence, + /// the resulting sequence has no elements. + /// + /// - Parameter k: The number of elements to include in each combination. + /// + /// - Complexity: O(1) + public func combinations(ofCount k: Int) -> Combinations { + assert(k >= 0, "Can't have combinations with a negative number of elements.") + return Combinations(self, k: k) + } +} diff --git a/Sources/Algorithms/Cycle.swift b/Sources/Algorithms/Cycle.swift new file mode 100644 index 0000000..c28501b --- /dev/null +++ b/Sources/Algorithms/Cycle.swift @@ -0,0 +1,101 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A collection wrapper that repeats the elements of a base collection. +public struct Cycle { + /// The collection to repeat. + public let base: Base +} + +extension Cycle: Sequence { + /// The iterator for a `Cycle` sequence. + public struct Iterator: IteratorProtocol { + let base: Base + var current: Base.Index + + public mutating func next() -> Base.Element? { + guard !base.isEmpty else { return nil } + + if current == base.endIndex { + current = base.startIndex + } + + defer { base.formIndex(after: ¤t) } + return base[current] + } + } + + public func makeIterator() -> Iterator { + Iterator(base: base, current: base.startIndex) + } +} + +//===----------------------------------------------------------------------===// +// cycled() +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns a sequence that repeats the elements of this collection forever. + /// + /// Use the `cycled()` method to repeat the elements of a sequence or + /// collection forever. You can combine `cycled()` with another, finite + /// sequence to iterate over the two together. + /// + /// for (evenOrOdd, number) in zip(["even", "odd"].cycled(), 0..<10) { + /// print("\(number) is \(evenOrOdd)") + /// } + /// // 0 is even + /// // 1 is odd + /// // 2 is even + /// // 3 is odd + /// // ... + /// // 9 is odd + /// + /// - Important: When called on a non-empty collection, the resulting sequence + /// is infinite. Do not directly call methods that require a finite + /// sequence, like `map` or `filter`, without first constraining the length + /// of the cycling sequence. + /// + /// - Returns: A sequence that repeats the elements of this collection + /// forever. + /// + /// - Complexity: O(1) + public func cycled() -> Cycle { + Cycle(base: self) + } +} + +//===----------------------------------------------------------------------===// +// repeated(count:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns a sequence that repeats the elements of this collection the + /// specified number of times. + /// + /// Passing `1` as `times` results in this collection's elements being + /// provided a single time; passing `0` results in an empty sequence. The + /// `print(_:)` function in this example is never called: + /// + /// for x in [1, 2, 3].cycled(times: 0) { + /// print(x) + /// } + /// + /// - Parameter times: The number of times to repeat this sequence. `times` + /// must be zero or greater. + /// - Returns: A sequence that repeats the elements of this sequence `times` + /// times. + /// + /// - Complexity: O(1) + public func cycled(times: Int) -> FlattenSequence> { + repeatElement(self, count: times).joined() + } +} diff --git a/Sources/Algorithms/Indexed.swift b/Sources/Algorithms/Indexed.swift new file mode 100644 index 0000000..af022fc --- /dev/null +++ b/Sources/Algorithms/Indexed.swift @@ -0,0 +1,81 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A collection wrapper that iterates over the indices and elements of a +/// collection together. +public struct Indexed { + /// The element type for an `Indexed` collection. + public typealias Element = (index: Base.Index, element: Base.Element) + + /// The base collection. + public let base: Base +} + +extension Indexed: Collection { + public var startIndex: Base.Index { + base.startIndex + } + + public var endIndex: Base.Index { + base.endIndex + } + + public subscript(position: Base.Index) -> Element { + (index: position, element: base[position]) + } + + public func index(after i: Base.Index) -> Base.Index { + base.index(after: i) + } + + public func index(_ i: Base.Index, offsetBy distance: Int) -> Base.Index { + base.index(i, offsetBy: distance) + } + + public func index(_ i: Base.Index, offsetBy distance: Int, limitedBy limit: Base.Index) -> Base.Index? { + base.index(i, offsetBy: distance, limitedBy: limit) + } + + public func distance(from start: Base.Index, to end: Base.Index) -> Int { + base.distance(from: start, to: end) + } +} + +extension Indexed: BidirectionalCollection where Base: BidirectionalCollection { + public func index(before i: Base.Index) -> Base.Index { + base.index(before: i) + } +} + +extension Indexed: RandomAccessCollection where Base: RandomAccessCollection {} +extension Indexed: Equatable where Base: Equatable {} +extension Indexed: Hashable where Base: Hashable {} + +extension Collection { + /// Returns a collection of pairs *(i, x)*, where *i* represents an index of + /// the collection, and *x* represents an element. + /// + /// This example iterates over the indices and elements of a set, building an + /// array consisting of indices of names with five or fewer letters. + /// + /// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "NicolĂĄs"] + /// var shorterIndices: [Set.Index] = [] + /// for (i, name) in zip(names.indices, names) { + /// if name.count <= 5 { + /// shorterIndices.append(i) + /// } + /// } + /// + /// Returns: A collection of paired indices and elements of this collection. + public func indexed() -> Indexed { + Indexed(base: self) + } +} diff --git a/Sources/Algorithms/Partition.swift b/Sources/Algorithms/Partition.swift new file mode 100644 index 0000000..603a3e5 --- /dev/null +++ b/Sources/Algorithms/Partition.swift @@ -0,0 +1,200 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// stablePartition(by:) +//===----------------------------------------------------------------------===// + +extension MutableCollection { + /// Moves all elements satisfying `belongsInSecondPartition` into a suffix + /// of the collection, preserving their relative order, and returns the + /// start of the resulting suffix. + /// + /// - Complexity: O(*n* log *n*), where *n* is the number of elements. + /// - Precondition: + /// `n == distance(from: range.lowerBound, to: range.upperBound)` + internal mutating func stablePartition( + count n: Int, + subrange: Range, + by belongsInSecondPartition: (Element) throws-> Bool + ) rethrows -> Index { + if n == 0 { return subrange.lowerBound } + if n == 1 { + return try belongsInSecondPartition(self[subrange.lowerBound]) + ? subrange.lowerBound + : subrange.upperBound + } + + let h = n / 2, i = index(subrange.lowerBound, offsetBy: h) + let j = try stablePartition( + count: h, + subrange: subrange.lowerBound.., + by belongsInSecondPartition: (Element) throws-> Bool + ) rethrows -> Index { + try stablePartition( + count: count, + subrange: subrange, + by: belongsInSecondPartition) + } + + /// Moves all elements satisfying the given predicate into a suffix of this + /// collection, preserving the relative order of the elements in both + /// partitions, and returns the start of the resulting suffix. + /// + /// - Parameter belongsInSecondPartition: A predicate used to partition the + /// collection. All elements satisfying this predicate are ordered after + /// all elements not satisfying it. + /// + /// - Complexity: O(*n* log *n*), where *n* is the length of this collection. + public mutating func stablePartition( + by belongsInSecondPartition: (Element) throws-> Bool + ) rethrows -> Index { + try stablePartition( + subrange: startIndex.., + by belongsInSecondPartition: (Element) throws -> Bool + ) rethrows -> Index { + // This version of `partition(subrange:)` is half stable; the elements in + // the first partition retain their original relative order. + guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition) + else { return subrange.upperBound } + + var j = index(after: i) + while j != subrange.upperBound { + if try !belongsInSecondPartition(self[j]) { + swapAt(i, j) + formIndex(after: &i) + } + formIndex(after: &j) + } + + return i + } +} + +extension MutableCollection where Self: BidirectionalCollection { + /// Moves all elements satisfying `isSuffixElement` into a suffix of the + /// collection, returning the start position of the resulting suffix. + /// + /// - Complexity: O(*n*) where n is the length of the collection. + public mutating func partition( + subrange: Range, + by belongsInSecondPartition: (Element) throws -> Bool + ) rethrows -> Index { + var lo = subrange.lowerBound + var hi = subrange.upperBound + + // 'Loop' invariants (at start of Loop, all are true): + // * lo < hi + // * predicate(self[i]) == false, for i in startIndex ..< lo + // * predicate(self[i]) == true, for i in hi ..< endIndex + + Loop: while true { + FindLo: repeat { + while lo < hi { + if try belongsInSecondPartition(self[lo]) { break FindLo } + formIndex(after: &lo) + } + break Loop + } while false + + FindHi: repeat { + formIndex(before: &hi) + while lo < hi { + if try !belongsInSecondPartition(self[hi]) { break FindHi } + formIndex(before: &hi) + } + break Loop + } while false + + swapAt(lo, hi) + formIndex(after: &lo) + } + + return lo + } +} + +//===----------------------------------------------------------------------===// +// partitioningIndex(where:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Returns the index of the first element in the collection that matches + /// the predicate. + /// + /// The collection must already be partitioned according to the predicate. + /// That is, there should be an index `i` where for every element in + /// `collection[.. Bool + ) rethrows -> Index { + var n = count + var l = startIndex + + while n > 0 { + let half = n / 2 + let mid = index(l, offsetBy: half) + if try belongsInSecondPartition(self[mid]) { + n = half + } else { + l = index(after: mid) + n -= half + 1 + } + } + return l + } +} + diff --git a/Sources/Algorithms/Permutations.swift b/Sources/Algorithms/Permutations.swift new file mode 100644 index 0000000..48e292a --- /dev/null +++ b/Sources/Algorithms/Permutations.swift @@ -0,0 +1,236 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A sequence of all the permutations of a collection's elements. +public struct Permutations { + /// The base collection. + public let base: Base + + internal let baseCount: Int + internal let countToChoose: Int + + internal init(_ base: Base, k: Int? = nil) { + self.base = base + let baseCount = base.count + self.baseCount = baseCount + self.countToChoose = k ?? baseCount + } + + public var count: Int { + return baseCount >= countToChoose + ? stride(from: baseCount, to: baseCount - countToChoose, by: -1).reduce(1, *) + : 0 + } +} + +extension Permutations: Sequence { + public struct Iterator: IteratorProtocol { + internal var base: Base + internal var indexes: [Base.Index] + internal var hasMorePermutations: Bool + internal var countToChoose: Int = 0 + + /// `true` if we're generating permutations of the full collection. + internal var permutesFullCollection: Bool { + countToChoose == indexes.count + } + + internal init(_ base: Base) { + self.base = base + self.indexes = Array(base.indices) + self.countToChoose = self.indexes.count + self.hasMorePermutations = true + } + + internal init(_ base: Base, count: Int) { + self.base = base + self.countToChoose = count + + // Produce exactly one empty permutation when `count == 0`. + self.indexes = count == 0 ? [] : Array(base.indices) + + // Can't produce any permutations when `count > base.count`. + self.hasMorePermutations = count <= indexes.count + } + + /// Advances the `indexes` array such that the first `countToChoose` + /// elements contain the next lexicographic ordering of elements. + /// + /// Uses the SEP(n,k) algorithm, as described in: + /// https://alistairisrael.wordpress.com/2009/09/22/simple-efficient-pnk-algorithm/ + /// + /// - Returns: A Boolean value indicating whether `indexes` still has + /// remaining permutations. When this method returns `false`, `indexes` + /// is in ascending order. + /// + /// - Complexity: O(*n*), where *n* is the length of the collection. + internal mutating func nextState() -> Bool { + let edge = countToChoose - 1 + + // Find first index greater than the one at `edge`. + if let i = indexes[countToChoose...].firstIndex(where: { indexes[edge] < $0 }) { + indexes.swapAt(edge, i) + } else { + indexes.reverse(subrange: countToChoose..= 0 && indexes[lastAscent] >= indexes[lastAscent + 1]) { + lastAscent -= 1 + } + if (lastAscent < 0) { + return false + } + + // Find rightmost index less than that at `lastAscent`. + if let i = indexes[lastAscent...].lastIndex(where: { indexes[lastAscent] < $0 }) { + indexes.swapAt(lastAscent, i) + } + indexes.reverse(subrange: (lastAscent + 1).. [Base.Element]? { + if !hasMorePermutations { return nil } + + if permutesFullCollection { + // If we're permuting the full collection, each iteration is just a + // call to `nextPermutation` on `indexes`. + defer { hasMorePermutations = indexes.nextPermutation() } + return indexes.map { base[$0] } + } else { + // Otherwise, return the items at the first `countToChoose` indices and + // advance the state. + defer { hasMorePermutations = nextState() } + return indexes.prefix(countToChoose).map { base[$0] } + } + } + } + + internal var permutesFullCollection: Bool { + baseCount == countToChoose + } + + public func makeIterator() -> Iterator { + permutesFullCollection + ? Iterator(base) + : Iterator(base, count: countToChoose) + } +} + +//===----------------------------------------------------------------------===// +// nextPermutation(by:) +//===----------------------------------------------------------------------===// + +extension MutableCollection + where Self: BidirectionalCollection, Element: Comparable +{ + /// Permutes this collection's elements through all the lexical orderings. + /// + /// Call `nextPermutation()` repeatedly starting with the collection in + /// sorted order. When the full cycle of all permutations has been completed, + /// the collection will be back in sorted order and this method will return + /// `false`. + /// + /// - Returns: A Boolean value indicating whether the collection still has + /// remaining permutations. When this method returns `false`, the collection + /// is in ascending order according to `areInIncreasingOrder`. + /// + /// - Complexity: O(*n*), where *n* is the length of the collection. + internal mutating func nextPermutation() -> Bool { + // ensure we have > 1 element in the collection + if isEmpty { return false } + var i = index(before: endIndex) + if i == startIndex { return false } + + while true { + let ip1 = i + formIndex(before: &i) + + if self[i] < self[ip1] { + var j = index(before: endIndex) + while self[i] >= self[j] { + formIndex(before: &j) + } + swapAt(i, j) + self.reverse(subrange: ip1.. Permutations { + assert( + k ?? 0 >= 0, + "Can't have permutations with a negative number of elements.") + return Permutations(self, k: k) + } +} diff --git a/Sources/Algorithms/Product.swift b/Sources/Algorithms/Product.swift new file mode 100644 index 0000000..c5e106e --- /dev/null +++ b/Sources/Algorithms/Product.swift @@ -0,0 +1,200 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +/// A sequence that represents the product of two sequence's elements. +public struct Product2 { + /// The outer sequence in the product. + public let base1: Base1 + /// The inner sequence in the product. + public let base2: Base2 + + internal init(_ base1: Base1, _ base2: Base2) { + self.base1 = base1 + self.base2 = base2 + } +} + +extension Product2: Sequence { + /// The iterator for a `Product2` sequence. + public struct Iterator: IteratorProtocol { + var i1: Base1.Iterator + var i2: Base2.Iterator + var element1: Base1.Element? + let base2: Base2 + + init(_ c: Product2) { + self.base2 = c.base2 + self.i1 = c.base1.makeIterator() + self.i2 = c.base2.makeIterator() + self.element1 = nil + } + + public mutating func next() -> (Base1.Element, Base2.Element)? { + // This is the initial state, where i1.next() has never + // been called, or the final state, where i1.next() has + // already returned nil. + if element1 == nil { + element1 = i1.next() + // once Base1 is exhausted, return `nil` forever + if element1 == nil { return nil } + } + + // Get the next element from the second sequence, if not + // at end. + if let element2 = i2.next() { + return (element1!, element2) + } + + // We've reached the end of the second sequence, so: + // 1) Get the next element of the first sequence, if exists + // 2) Restart iteration of the second sequence + // 3) Get the first element of the second sequence, if exists + element1 = i1.next() + guard let element1 = element1 + else { return nil } + + i2 = base2.makeIterator() + if let element2 = i2.next() { + return (element1, element2) + } else { + return nil + } + } + } + + public func makeIterator() -> Iterator { + return Iterator(self) + } +} + +extension Product2: Collection where Base1: Collection { + /// The index type for a `Product2` collection. + public struct Index: Comparable { + var i1: Base1.Index + var i2: Base2.Index + + public static func < (lhs: Index, rhs: Index) -> Bool { + (lhs.i1, lhs.i2) < (rhs.i1, rhs.i2) + } + } + + public var count: Int { + base1.count * base2.count + } + + public var startIndex: Index { + base1.isEmpty || base2.isEmpty + ? endIndex + : Index(i1: base1.startIndex, i2: base2.startIndex) + } + + public var endIndex: Index { + Index(i1: base1.endIndex, i2: base2.endIndex) + } + + public func index(after i: Index) -> Index { + precondition(i.i1 != base1.endIndex && i.i2 != base2.endIndex, + "Can't advance past endIndex") + let newIndex2 = base2.index(after: i.i2) + if newIndex2 < base2.endIndex { + return Index(i1: i.i1, i2: newIndex2) + } + + let newIndex1 = base1.index(after: i.i1) + return newIndex1 == base1.endIndex + ? endIndex + : Index(i1: newIndex1, i2: base2.startIndex) + } + + // TODO: Implement index(_:offsetBy:) and index(_:offsetBy:limitedBy:) + + public func distance(from start: Index, to end: Index) -> Int { + if start > end { + return -distance(from: end, to: start) + } + if start.i1 == end.i1 { + return base2[start.i2.. (Base1.Element, Base2.Element) { + return (base1[position.i1], base2[position.i2]) + } +} + +extension Product2: BidirectionalCollection + where Base1: BidirectionalCollection, Base2: BidirectionalCollection +{ + public func index(before i: Index) -> Index { + precondition(i != startIndex, + "Can't move before startIndex") + if i.i2 == base2.startIndex { + return Index(i1: i.i1, i2: base2.index(before: i.i2)) + } + + return Index( + i1: base1.index(before: i.i1), + i2: base2.index(before: base2.endIndex)) + } +} + +extension Product2: RandomAccessCollection + where Base1: RandomAccessCollection, Base2: RandomAccessCollection {} + +extension Product2.Index: Hashable where Base1.Index: Hashable, Base2.Index: Hashable {} +extension Product2: Equatable where Base1: Equatable, Base2: Equatable {} +extension Product2: Hashable where Base1: Hashable, Base2: Hashable {} + +//===----------------------------------------------------------------------===// +// product(_:_:) +//===----------------------------------------------------------------------===// + +/// Creates a sequence of each pair of elements of two underlying sequences. +/// +/// Use this function to iterate over every pair of elements in two different +/// collections. The returned sequence yields 2-element tuples, where the first +/// element of the tuple is from the first collection and the second element is +/// from the second collection. +/// +/// +/// let numbers = 1...3 +/// let colors = ["cerise", "puce", "heliotrope"] +/// for (number, color) in product(numbers, colors) { +/// print("\(number): \(color)") +/// } +/// // 1: cerise +/// // 1: puce +/// // 1: heliotrope +/// // 2: cerise +/// // 2: puce +/// // 2: heliotrope +/// // 3: cerise +/// // 3: puce +/// // 3: heliotrope +/// +/// The order of tuples in the returned sequence is consistent. The first +/// element of the first collection is paired with each element of the second +/// collection, then the second element of the first collection is paired with +/// each element of the second collection, and so on. +/// +/// - Parameters: +/// - s1: The first sequence to iterate over. +/// - s2: The second sequence to iterate over. +/// +/// - Complexity: O(1) +public func product( + _ s1: Base1, _ s2: Base2 +) -> Product2 { + return Product2(s1, s2) +} diff --git a/Sources/Algorithms/RandomSample.swift b/Sources/Algorithms/RandomSample.swift new file mode 100644 index 0000000..a42eccd --- /dev/null +++ b/Sources/Algorithms/RandomSample.swift @@ -0,0 +1,238 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// For log(_:) and exp(_:) +#if canImport(Glibc) +@_implementationOnly +import Glibc +#elseif canImport(Darwin) +@_implementationOnly +import Darwin +#endif + +//===----------------------------------------------------------------------===// +// randomStableSample(count:) +//===----------------------------------------------------------------------===// + +extension Collection { + /// Randomly selects the specified number of elements from this collection, + /// maintaining their relative order. + /// + /// - Parameters: + /// - k: The number of elements to randomly select. + /// - rng: The random number generator to use for the sampling. + /// - Returns: An array of `k` random elements. If `k` is greater than this + /// collection's count, then this method returns the full collection. + /// + /// - Complexity: O(*n*), where *n* is the length of the collection. + public func randomStableSample( + count k: Int, using rng: inout G + ) -> [Element] { + guard k > 0 else { return [] } + + var remainingCount = count + guard k < remainingCount else { return Array(self) } + + var result: [Element] = [] + result.reserveCapacity(k) + + var i = startIndex + var countToSelect = k + while countToSelect > 0 { + let r = Int.random(in: 0.. [Element] { + var g = SystemRandomNumberGenerator() + return randomStableSample(count: k, using: &g) + } +} + +//===----------------------------------------------------------------------===// +// randomSample(count:) +//===----------------------------------------------------------------------===// + +// These methods use Algorithm L, described in "Reservoir-Sampling +// Algorithms of Time Complexity O(n(1 + log(N/n)))": +// https://dl.acm.org/doi/pdf/10.1145/198429.198435 + +fileprivate func nextW( + k: Double, using rng: inout G +) -> Double { + exp(log(Double.random(in: 0..<1, using: &rng)) / k) +} + +fileprivate func nextOffset( + w: Double, using rng: inout G +) -> Int { + Int(log(Double.random(in: 0..<1, using: &rng)) / log(1 - w)) +} + +extension Collection { + /// Randomly selects the specified number of elements from this collection. + /// + /// - Parameters: + /// - k: The number of elements to randomly select. + /// - rng: The random number generator to use for the sampling. + /// - Returns: An array of `k` random elements. The returned elements may be + /// in any order. If `k` is greater than this collection's count, then this + /// method returns the full collection. + /// + /// - Complexity: O(*k*), where *k* is the number of elements to select, if + /// the collection conforms to `RandomAccessCollection`. Otherwise, O(*n*), + /// where *n* is the length of the collection. + public func randomSample( + count k: Int, using rng: inout G + ) -> [Element] { + guard k > 0 else { return [] } + + var w = 1.0 + var result: [Element] = [] + result.reserveCapacity(k) + + // Fill the reservoir with the first `k` elements. + var i = startIndex + while i < endIndex, result.count < k { + result.append(self[i]) + formIndex(after: &i) + } + + let dk = Double(k) + while i < endIndex { + // Calculate the next value of w. + w *= nextW(k: dk, using: &rng) + + // Find index of the next element to swap into the reservoir. + let offset = nextOffset(w: w, using: &rng) + i = index(i, offsetBy: offset, limitedBy: endIndex) ?? endIndex + + if i < endIndex { + // Swap selected element with a randomly chosen one in the reservoir. + let j = Int.random(in: 0.. [Element] { + var g = SystemRandomNumberGenerator() + return randomSample(count: k, using: &g) + } +} + +extension Sequence { + /// Randomly selects the specified number of elements from this sequence. + /// + /// - Parameters: + /// - k: The number of elements to randomly select. + /// - rng: The random number generator to use for the sampling. + /// - Returns: An array of `k` random elements. The returned elements may be + /// in any order. If `k` is greater than this sequence's count, then this + /// method returns the full sequence. + /// + /// - Complexity: O(*n*), where *n* is the length of the sequence. + public func randomSample( + count k: Int, using rng: inout G + ) -> [Element] { + guard k > 0 else { return [] } + + var w = 1.0 + var result: [Element] = [] + result.reserveCapacity(k) + + // Fill the reservoir with the first `k` elements. + var iterator = makeIterator() + while result.count < k, let el = iterator.next() { + result.append(el) + } + + let dk = Double(k) + while true { + // Calculate the next value of w. + w *= nextW(k: dk, using: &rng) + + // Find the offset of the next element to swap into the reservoir. + var offset = nextOffset(w: w, using: &rng) + 1 + + // Skip over `offset - 1` elements to find the selected element. + while offset > 1, let _ = iterator.next() { + offset -= 1 + } + guard let nextElement = iterator.next() else { break } + + // Swap selected element with a randomly chosen one in the reservoir. + let j = Int.random(in: 0.. [Element] { + var g = SystemRandomNumberGenerator() + return randomSample(count: k, using: &g) + } +} diff --git a/Sources/Algorithms/Rotate.swift b/Sources/Algorithms/Rotate.swift new file mode 100644 index 0000000..2e67e65 --- /dev/null +++ b/Sources/Algorithms/Rotate.swift @@ -0,0 +1,203 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// reverse(subrange:) +//===----------------------------------------------------------------------===// + +extension MutableCollection where Self: BidirectionalCollection { + /// Reverses the elements of the collection, moving from each end until + /// `limit` is reached from either direction. The returned indices are the + /// start and end of the range of unreversed elements. + /// + /// Input: + /// [a b c d e f g h i j k l m n o p] + /// ^ + /// limit + /// Output: + /// [p o n m e f g h i j k l d c b a] + /// ^ ^ + /// f l + /// + /// - Postcondition: For returned indices `(f, l)`: + /// `f == limit || l == limit` + @discardableResult + internal mutating func _reverse( + subrange: Range, until limit: Index + ) -> (Index, Index) { + var f = subrange.lowerBound + var l = subrange.upperBound + while f != limit && l != limit { + formIndex(before: &l) + swapAt(f, l) + formIndex(after: &f) + } + return (f, l) + } + + public mutating func reverse(subrange: Range) { + if subrange.isEmpty { return } + var lo = subrange.lowerBound + var hi = subrange.upperBound + + while lo < hi { + formIndex(before: &hi) + swapAt(lo, hi) + formIndex(after: &lo) + } + } +} + +//===----------------------------------------------------------------------===// +// rotate(at:) / rotate(subrange:at:) +//===----------------------------------------------------------------------===// + +extension MutableCollection { + /// Swaps the elements of the two given subranges, up to the upper bound of + /// the smaller subrange. The returned indices are the ends of the two + /// ranges that were actually swapped. + /// + /// Input: + /// [a b c d e f g h i j k l m n o p] + /// ^^^^^^^ ^^^^^^^^^^^^^ + /// lhs rhs + /// + /// Output: + /// [i j k l e f g h a b c d m n o p] + /// ^ ^ + /// p q + /// + /// - Precondition: !lhs.isEmpty && !rhs.isEmpty + /// - Postcondition: For returned indices `(p, q)`: + /// + /// - distance(from: lhs.lowerBound, to: p) == distance(from: + /// rhs.lowerBound, to: q) + /// - p == lhs.upperBound || q == rhs.upperBound + internal mutating func _swapNonemptySubrangePrefixes( + _ lhs: Range, _ rhs: Range + ) -> (Index, Index) { + assert(!lhs.isEmpty) + assert(!rhs.isEmpty) + + var p = lhs.lowerBound + var q = rhs.lowerBound + repeat { + swapAt(p, q) + formIndex(after: &p) + formIndex(after: &q) + } + while p != lhs.upperBound && q != rhs.upperBound + return (p, q) + } + + @discardableResult + public mutating func rotate( + subrange: Range, + at newStart: Index + ) -> Index { + var m = newStart, s = subrange.lowerBound + let e = subrange.upperBound + + // Handle the trivial cases + if s == m { return e } + if m == e { return s } + + // We have two regions of possibly-unequal length that need to be + // exchanged. The return value of this method is going to be the + // position following that of the element that is currently last + // (element j). + // + // [a b c d e f g|h i j] or [a b c|d e f g h i j] + // ^ ^ ^ ^ ^ ^ + // s m e s m e + // + var ret = e // start with a known incorrect result. + while true { + // Exchange the leading elements of each region (up to the + // length of the shorter region). + // + // [a b c d e f g|h i j] or [a b c|d e f g h i j] + // ^^^^^ ^^^^^ ^^^^^ ^^^^^ + // [h i j d e f g|a b c] or [d e f|a b c g h i j] + // ^ ^ ^ ^ ^ ^ ^ ^ + // s s1 m m1/e s s1/m m1 e + // + let (s1, m1) = _swapNonemptySubrangePrefixes(s.. Index { + rotate(subrange: startIndex.., + at newStart: Index + ) -> Index { + reverse(subrange: subrange.lowerBound.. Index { + rotate(subrange: startIndex.. [Element] { + var seen: Set = [] + var result: [Element] = [] + for element in self { + if seen.insert(element).inserted { + result.append(element) + } + } + return result + } +} + +extension Sequence { + /// Returns an array with the unique elements of this sequence (as determined + /// by the given projection), in the order of the first occurence of each + /// unique element. + public func uniqued( + on projection: (Element) throws -> Subject + ) rethrows -> [Element] { + var seen: Set = [] + var result: [Element] = [] + for element in self { + if seen.insert(try projection(element)).inserted { + result.append(element) + } + } + return result + } +} diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift new file mode 100644 index 0000000..917e331 --- /dev/null +++ b/Tests/LinuxMain.swift @@ -0,0 +1,19 @@ +//===----------------------------------------------------------*- swift -*-===// +// +// This source file is part of the Swift Argument Parser open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#error(""" + + ----------------------------------------------------- + + Please test with `swift test --enable-test-discovery` + + ----------------------------------------------------- + """) diff --git a/Tests/SwiftAlgorithmsTests/ChainTests.swift b/Tests/SwiftAlgorithmsTests/ChainTests.swift new file mode 100644 index 0000000..3a1c1c9 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/ChainTests.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class ChainTests: XCTestCase { + func testChainSequences() { + let run = (1...).prefix(10).chained(with: 20...) + XCTAssertEqualSequences(run.prefix(20), Array(1...10) + (20..<30)) + } + + func testChainForwardCollection() { + let s1 = Set(0...10) + let s2 = Set(20...30) + let c = s1.chained(with: s2) + XCTAssertEqualSequences(c, Array(s1) + Array(s2)) + } + + func testChainBidirectionalCollection() { + let s1 = "ABCDEFGHIJ" + let s2 = "klmnopqrstuv" + let c = s1.chained(with: s2) + + XCTAssertEqualSequences(c, "ABCDEFGHIJklmnopqrstuv") + XCTAssertEqualSequences(c.reversed(), "ABCDEFGHIJklmnopqrstuv".reversed()) + XCTAssertEqualSequences(s1.reversed().chained(with: s2), "JIHGFEDCBAklmnopqrstuv") + } + + // TODO: Add tests that check distance and index(offsetBy:) +} diff --git a/Tests/SwiftAlgorithmsTests/ChunkedTests.swift b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift new file mode 100644 index 0000000..66682b0 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/ChunkedTests.swift @@ -0,0 +1,74 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class ChunkedTests: XCTestCase { + let fruits = [ + "Apple", "Apricot", "Avocado", "Banana", + "Bilberry", "Blackberry", "Blackcurrant", "Blueberry", + "Currant", "Cherry", "Cherimoya", "Clementine", + "Date", "Damson", "Dragonfruit", "Durian", + "Eggplant", "Elderberry", "Feijoa", + "Grape", "Grapefruit", "Guava", + ] + + func validateFruitChunks(_ fruitChunks: C) + where C.Element == ArraySlice + { + let expectedChunks: Array> = [ + fruits[0..<3], + fruits[3..<8], + fruits[8..<12], + fruits[12..<16], + fruits[16..<18], + fruits[18..<19], + fruits[19..<22], + ] + XCTAssertEqualSequences(expectedChunks, fruitChunks, by: ==) + + XCTAssertEqual(fruits[19..<22], fruitChunks.last) + + XCTAssertEqual("Currant", fruitChunks.first(where: { $0.count == 4 })?.first) + XCTAssertEqual("Date", fruitChunks.last(where: { $0.count == 4 })?.first) + XCTAssertNil(fruitChunks.first(where: { $0.count == 0 })) + XCTAssertNil(fruitChunks.last(where: { $0.count == 0 })) + } + + func testSimple() { + // Example + let names = ["David", "Kyle", "Karoy", "Nate"] + let chunks = names.chunked(on: { $0.first }) + XCTAssertEqualSequences([["David"], ["Kyle", "Karoy"], ["Nate"]], chunks) + + // Empty sequence + XCTAssertEqual(0, names.prefix(0).chunked(on: { $0.first }).count) + + // Single chunk + let namesStartingWithD = ["David", "Don", "Darren"] + XCTAssertEqual(1, namesStartingWithD.chunked(on: { $0.first }).count) + } + + func testChunkedOn() { + validateFruitChunks(fruits.chunked(on: { $0.first })) + + let lazyChunks = fruits.lazy.chunked(on: { $0.first }) + validateFruitChunks(lazyChunks) + } + + func testChunkedBy() { + validateFruitChunks(fruits.chunked(by: { $0.first == $1.first })) + + let lazyChunks = fruits.lazy.chunked(by: { $0.first == $1.first }) + validateFruitChunks(lazyChunks) + } +} diff --git a/Tests/SwiftAlgorithmsTests/CombinationsTests.swift b/Tests/SwiftAlgorithmsTests/CombinationsTests.swift new file mode 100644 index 0000000..77cab02 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/CombinationsTests.swift @@ -0,0 +1,41 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class CombinationsTests: XCTestCase { + func testCombinations() { + let c = "ABCD" + + let c1 = c.combinations(ofCount: 1) + XCTAssertEqual(["A", "B", "C", "D"], c1.map { String($0) }) + + let c2 = c.combinations(ofCount: 2) + XCTAssertEqual(["AB", "AC", "AD", "BC", "BD", "CD"], c2.map { String($0) }) + + let c3 = c.combinations(ofCount: 3) + XCTAssertEqual(["ABC", "ABD", "ACD", "BCD"], c3.map { String($0) }) + + let c4 = c.combinations(ofCount: 4) + XCTAssertEqual(["ABCD"], c4.map { String($0) }) + } + + func testEmpty() { + // `k == 0` results in one zero-length combination + XCTAssertEqualSequences([[]], "".combinations(ofCount: 0)) + XCTAssertEqualSequences([[]], "ABCD".combinations(ofCount: 0)) + + // `k` greater than element count results in zero combinations + XCTAssertEqualSequences([], "".combinations(ofCount: 5)) + XCTAssertEqualSequences([], "ABCD".combinations(ofCount: 5)) + } +} diff --git a/Tests/SwiftAlgorithmsTests/CycleTests.swift b/Tests/SwiftAlgorithmsTests/CycleTests.swift new file mode 100644 index 0000000..181ec69 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/CycleTests.swift @@ -0,0 +1,42 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class CycleTests: XCTestCase { + func testCycle() { + let cycle = (1...4).cycled() + XCTAssertEqualSequences( + [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], + cycle.prefix(20) + ) + + let a = Array((0..<17).cycled().prefix(10_000)) + XCTAssertEqual(10_000, a.count) + + let empty = Array("".cycled()) + XCTAssert(empty.isEmpty) + } + + func testRepeated() { + let repeats = (1...4).cycled(times: 3) + XCTAssertEqualSequences( + [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], + repeats) + + let empty1 = Array("".cycled(times: 100)) + XCTAssert(empty1.isEmpty) + + let empty2 = Array("Hello".cycled(times: 0)) + XCTAssert(empty2.isEmpty) + } +} diff --git a/Tests/SwiftAlgorithmsTests/IndexedTests.swift b/Tests/SwiftAlgorithmsTests/IndexedTests.swift new file mode 100644 index 0000000..7e2b7ba --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/IndexedTests.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class IndexedTests: XCTestCase { + func testIndexed() { + let s = "ABCDEFGHIJKLMNOP" + let si = s.indexed() + + XCTAssertEqual(s.startIndex, si.first!.index) + XCTAssertEqual("A", si.first!.element) + XCTAssertEqual(s.index(before: s.endIndex), si.last!.index) + XCTAssertEqual("P", si.last!.element) + + let indexOfG = si.first(where: { $0.element == "G" })!.index + XCTAssertEqual("G", s[indexOfG]) + let indexOfI = si.last(where: { $0.element == "I" })!.index + XCTAssertEqual("I", s[indexOfI]) + } +} diff --git a/Tests/SwiftAlgorithmsTests/PartitionTests.swift b/Tests/SwiftAlgorithmsTests/PartitionTests.swift new file mode 100644 index 0000000..a65bcc3 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/PartitionTests.swift @@ -0,0 +1,76 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class PartitionTests: XCTestCase { + func testStablePartition() { + for l in 0..<13 { + let a = Array(0..= k } + XCTAssertGreaterThanOrEqual(p, i) + XCTAssertLessThanOrEqual(p, j) + XCTAssertEqual(p, k) + } + } + } + } +} diff --git a/Tests/SwiftAlgorithmsTests/PermutationsTests.swift b/Tests/SwiftAlgorithmsTests/PermutationsTests.swift new file mode 100644 index 0000000..1085d7e --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/PermutationsTests.swift @@ -0,0 +1,72 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +@testable import Algorithms + +final class PermutationsTests: XCTestCase { + func testPermutations() { + let c = "ABCDE" + + func t(count: Int?) { + let p = c.permutations(ofCount: count) + + let count = count ?? c.count + let permCount = c.count.factorial() / (c.count - count).factorial() + XCTAssertEqual(permCount, p.count) + XCTAssertEqual(p.count, Array(p).count) + XCTAssertTrue(p.allSatisfy { $0.count == count }) + XCTAssertTrue(p.isSorted(by: { $0.lexicographicallyPrecedes($1) })) + } + + t(count: 1) + t(count: 2) + t(count: 3) + t(count: 4) + t(count: 5) + t(count: nil) + } + + func testEmpty() { + // `k == 0` results in one zero-length permutation + XCTAssertEqual(1, "".permutations().count) + XCTAssertEqual(1, "ABCD".permutations(ofCount: 0).count) + XCTAssertEqual(Array("".permutations()), [[]]) + XCTAssertEqual(Array("".permutations(ofCount: 0)), [[]]) + XCTAssertEqual(Array("ABCD".permutations(ofCount: 0)), [[]]) + + // `k` greater than element count results in zero permutations + XCTAssertEqual(0, "".permutations(ofCount: 5).count) + XCTAssertEqual(Array("".permutations(ofCount: 5)), []) + XCTAssertEqual(Array("ABCD".permutations(ofCount: 5)), []) + } + + func testNextPermutation() { + var numbers = Array(1...7) + + _ = numbers.nextPermutation() + XCTAssertEqual([1, 2, 3, 4, 5, 7, 6], numbers) + _ = numbers.nextPermutation() + XCTAssertEqual([1, 2, 3, 4, 6, 5, 7], numbers) + _ = numbers.nextPermutation() + XCTAssertEqual([1, 2, 3, 4, 6, 7, 5], numbers) + _ = numbers.nextPermutation() + XCTAssertEqual([1, 2, 3, 4, 7, 5, 6], numbers) + _ = numbers.nextPermutation() + XCTAssertEqual([1, 2, 3, 4, 7, 6, 5], numbers) + _ = numbers.nextPermutation() + XCTAssertEqual([1, 2, 3, 5, 4, 6, 7], numbers) + + // Fast-forward to end of permutations. + while numbers.nextPermutation() {} + XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], numbers) + } +} diff --git a/Tests/SwiftAlgorithmsTests/ProductTests.swift b/Tests/SwiftAlgorithmsTests/ProductTests.swift new file mode 100644 index 0000000..e4d9462 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/ProductTests.swift @@ -0,0 +1,25 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class ProductTests: XCTestCase { + func testProduct() { + XCTAssertEqualSequences( + [(1, "A" as Character), (1, "B"), (2, "A"), (2, "B")], + product(1...2, "AB"), + by: ==) + + XCTAssertEqualSequences(product(1...10, ""), [], by: ==) + XCTAssertEqualSequences(product("", 1...10), [], by: ==) + } +} diff --git a/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift b/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift new file mode 100644 index 0000000..023c8d5 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/RandomSampleTests.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +func validateRandomSamples( + _ samples: [Int: Int], + elements: S, + expectedValue: Int, + file: StaticString = #file, line: UInt = #line +) where S.Element == Int { + let expectedRange = ((expectedValue / 3) * 2) ... ((expectedValue / 3) * 4) + XCTAssertEqualSequences(samples.keys.sorted(), elements, + file: file, line: line) + for v in samples.values { + XCTAssert(expectedRange.contains(v), file: file, line: line) + } +} + +let n = 100 +let k = 12 +let iterations = 10_000 +let c = 0.. Bool) -> Bool { + zip(self, self.dropFirst()).allSatisfy { !f($1, $0) } + } +} + +extension Sequence where Element: Comparable { + func isSorted() -> Bool { + isSorted(by: <) + } +} + +extension Numeric { + func factorial() -> Self { + guard self != 0 else { return 1 } + return self * (self - 1).factorial() + } +} + +struct SplitMix64: RandomNumberGenerator { + private var state: UInt64 + + init(seed: UInt64) { + self.state = seed + } + + mutating func next() -> UInt64 { + self.state &+= 0x9e3779b97f4a7c15 + var z: UInt64 = self.state + z = (z ^ (z &>> 30)) &* 0xbf58476d1ce4e5b9 + z = (z ^ (z &>> 27)) &* 0x94d049bb133111eb + return z ^ (z &>> 31) + } +} + +func XCTAssertEqualSequences( + _ expression1: @autoclosure () throws -> S1, + _ expression2: @autoclosure () throws -> S2, + _ message: @autoclosure () -> String = "", + file: StaticString = #file, line: UInt = #line +) rethrows where S1.Element: Equatable, S1.Element == S2.Element { + try XCTAssert(expression1().elementsEqual(expression2()), message(), file: file, line: line) +} + +func XCTAssertEqualSequences( + _ expression1: @autoclosure () throws -> S1, + _ expression2: @autoclosure () throws -> S2, + by areEquivalent: (S1.Element, S1.Element) -> Bool, + _ message: @autoclosure () -> String = "", + file: StaticString = #file, line: UInt = #line +) rethrows where S1.Element == S2.Element { + try XCTAssert(expression1().elementsEqual(expression2(), by: areEquivalent), message(), file: file, line: line) +} + diff --git a/Tests/SwiftAlgorithmsTests/UniqueTests.swift b/Tests/SwiftAlgorithmsTests/UniqueTests.swift new file mode 100644 index 0000000..3be41a8 --- /dev/null +++ b/Tests/SwiftAlgorithmsTests/UniqueTests.swift @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Algorithms open source project +// +// Copyright (c) 2020 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +import XCTest +import Algorithms + +final class UniqueTests: XCTestCase { + func testUnique() { + let a = repeatElement(1...10, count: 15).joined().shuffled() + let b = a.uniqued() + XCTAssertEqual(b.sorted(), Set(a).sorted()) + XCTAssertEqual(10, b.count) + + let c: [Int] = [] + XCTAssertEqual(c.uniqued(), []) + } + + func testUniqueOn() { + let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"] + let b = a.uniqued(on: { $0.first }) + XCTAssertEqual(["Albemarle", "Brandywine"], b) + + let c: [Int] = [] + XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), []) + } +}