Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save lukestringer90/fd77cfcb39bbf190fa9ebc5f7e6ce324 to your computer and use it in GitHub Desktop.

Select an option

Save lukestringer90/fd77cfcb39bbf190fa9ebc5f7e6ce324 to your computer and use it in GitHub Desktop.

Revisions

  1. lukestringer90 created this gist Nov 22, 2023.
    61 changes: 61 additions & 0 deletions codewars-5547cc7dcad755e480000004.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,61 @@
    // Problem statement: https://www.codewars.com/kata/5547cc7dcad755e480000004/train/swift

    import Foundation

    func removNb(_ length: Int) -> [(Int,Int)] {
    var matches = [(Int,Int)]()
    var seenNumbers = [Int]()

    let sumOfNumbers = ((length * length) + length) / 2
    var numbersToTry = Array(Array(1...length)[1...length-1].reversed()).makeIterator()


    while (true) {
    guard let attempt = numbersToTry.next() else { break }

    // Don't try numbers already seen
    guard !seenNumbers.contains(attempt) else {
    print("Already seen \(attempt), skipping ↩️")
    continue
    }

    // Solve the equation
    let computedFloat = Float(sumOfNumbers - attempt) / Float(attempt + 1)

    // If larger the count then all others will be too large, so totally stop
    guard computedFloat < Float(length) else {
    print("\(computedFloat) too large, Stopping at \(attempt)")
    break
    }

    let computedInt = Int(computedFloat)

    // If computed is a whole number and less than the length it is a match
    if computedInt < length {
    if floor(computedFloat) == computedFloat {
    matches.append((attempt, computedInt))
    matches.append((computedInt, attempt))

    // Skip this computed number if we see it next time as an attemp
    seenNumbers.append(computedInt)
    print("\(attempt) => \(computedFloat)")
    }
    else {
    print("\(attempt) => \(computedFloat)")
    }
    }
    else {
    print("\(attempt) => \(computedFloat)")
    }

    // Skip over these next time
    seenNumbers.append(attempt)
    }

    // Put tuple values in the right order
    return matches.map { pair in
    return (pair.1, pair.0)
    }
    }

    print(removNb(906))