Skip to content

Commit

Permalink
Solve 'Gap in Primes' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Apr 19, 2024
1 parent fbf03a2 commit 85dfcf2
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
34 changes: 34 additions & 0 deletions Sources/SwiftKatas/GapInPrimes/gap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
https://www.codewars.com/kata/561e9c843a2ef5a40c0000a4/train/swift
*/
func gap(_ g: Int, _ m: Int, _ n: Int) -> (Int, Int)? {
return (m ... n)
.filter { $0.isPrime() }
.zipWithNext()
.map { ($0, $1) }
.first { $0.1 - $0.0 == g }
}

public extension Int {
func isPrime() -> Bool {
if self <= 1 { return false }
if self <= 3 { return true }
if self % 2 == 0 || self % 3 == 0 { return false }

var i = 5
while i * i <= self {
if self % i == 0 || self % (i + 2) == 0 {
return false
}
i += 6
}

return true
}
}

extension Sequence {
func zipWithNext() -> Zip2Sequence<Self, DropFirstSequence<Self>> {
return zip(self, dropFirst())
}
}
20 changes: 20 additions & 0 deletions Tests/SwiftKatasTests/GapInPrimes/gapTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
@testable import SwiftKatas
import XCTest

class GapInPrimesTest: XCTestCase {
func testing(_ g: Int, _ m: Int, _ n: Int, _ expected: (Int, Int)?) {
XCTAssert(gap(g, m, n)! == expected!, "should return \(expected!), but returned \(gap(g, m, n)!)")
}

func testingNil(_ g: Int, _ m: Int, _ n: Int) {
XCTAssertTrue(gap(g, m, n) == nil, "Should return nil")
}

func testExample() {
testing(2, 100, 110, (101, 103))
testing(4, 100, 110, (103, 107))
testingNil(6, 100, 110)
testingNil(11, 30000, 100_000)
testing(2, 10_000_000, 11_000_000, (10_000_139, 10_000_141))
}
}

0 comments on commit 85dfcf2

Please sign in to comment.