Created
November 22, 2023 17:17
-
-
Save lukestringer90/fd77cfcb39bbf190fa9ebc5f7e6ce324 to your computer and use it in GitHub Desktop.
Revisions
-
lukestringer90 created this gist
Nov 22, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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))