Skip to content

Commit ff356ae

Browse files
committed
Avoid counting base more than once
This is similar to how `Permutations` works
1 parent c49f1eb commit ff356ae

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

Sources/Algorithms/Combinations.swift

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ public struct Combinations<Base: Collection> {
1414
/// The collection to iterate over for combinations.
1515
public let base: Base
1616

17+
@usableFromInline
18+
internal let baseCount: Int
19+
1720
/// The range of accepted sizes of combinations.
1821
/// - Note: This may be `nil` if the attempted range entirely exceeds the
1922
/// upper bounds of the size of the `base` collection.
@@ -40,17 +43,19 @@ public struct Combinations<Base: Collection> {
4043
) where R.Bound == Int {
4144
let range = kRange.relative(to: 0 ..< .max)
4245
self.base = base
43-
let upperBound = base.count + 1
46+
let baseCount = base.count
47+
self.baseCount = baseCount
48+
let upperBound = baseCount + 1
4449
self.kRange = range.lowerBound < upperBound
45-
? range.clamped(to: 0..<upperBound)
50+
? range.clamped(to: 0 ..< upperBound)
4651
: nil
4752
}
4853

4954
/// The total number of combinations.
5055
@inlinable
5156
public var count: Int {
5257
guard let k = self.kRange else { return 0 }
53-
let n = base.count
58+
let n = baseCount
5459
if k == 0..<(n + 1) {
5560
return 1 << n
5661
}

0 commit comments

Comments
 (0)