Skip to content

Commit

Permalink
Adjustments on distance logic and remove count because it is already …
Browse files Browse the repository at this point in the history
…on terms of distance and distance is O(1).
  • Loading branch information
LucianoPAlmeida committed Jan 7, 2021
1 parent 76e6d2f commit 91f1e73
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
9 changes: 5 additions & 4 deletions Guides/Chunked.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Break a collection into subsequences where consecutive elements pass a binary
predicate, or where all elements in each chunk project to the same value.

Also, includes a `chunks(ofCount:)` that breaks a collection into subsequences
of a given size.
of a given `count`.

There are two variations of the `chunked` method: `chunked(by:)` and
`chunked(on:)`. `chunked(by:)` uses a binary predicate to test consecutive
Expand All @@ -29,10 +29,11 @@ let chunks = names.chunked(on: \.first!)
// [["David"], ["Kyle", "Karoy"], ["Nate"]]
```

The `chunks(ofCount:)` takes a `size` parameter (required to be > 0) and separates
the collection into `n` chunks of this given size. If the size parameter is
The `chunks(ofCount:)` takes a `count` parameter (required to be > 0) and separates
the collection into `n` chunks of this given count. If the `count` parameter is
evenly divided by the count of the base `Collection` all the chunks will have
the count equals to size. Otherwise, the last chunk will contain the remaining elements.
the count equals to the parameter. Otherwise, the last chunk will contain the
remaining elements.

```swift
let names = ["David", "Kyle", "Karoy", "Nate"]
Expand Down
15 changes: 6 additions & 9 deletions Sources/Algorithms/Chunked.swift
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,11 @@ where Base: RandomAccessCollection {
let distance = base.distance(from: start.base, to: end.base)
let (quotient, remainder) =
distance.quotientAndRemainder(dividingBy: _chunkCount)
return quotient + remainder
// Increment should account for negative distances.
if remainder < 0 {
return quotient - 1
}
return quotient + (remainder == 0 ? 0 : 1)
}

@inlinable
Expand All @@ -343,13 +347,6 @@ where Base: RandomAccessCollection {
base.index(i.base, offsetBy: n * _chunkCount, limitedBy: bound) ?? bound
)
}

@inlinable
public var count: Int {
return base.count
.isMultiple(of: _chunkCount) ? base.count/_chunkCount
: base.count/_chunkCount + 1
}
}

extension Collection {
Expand All @@ -371,7 +368,7 @@ extension Collection {
/// - Complexity: O(1)
@inlinable
public func chunks(ofCount count: Int) -> ChunkedCollection<Self> {
assert(count > 0, " Cannot chunk with size <= 0!")
precondition(count > 0, " Cannot chunk with count <= 0!")
return ChunkedCollection(_base: self, _chunkCount: count)
}
}
Expand Down

0 comments on commit 91f1e73

Please sign in to comment.