diff --git a/exercises/accumulate/AccumulateExample.swift b/exercises/accumulate/AccumulateExample.swift index e94197af9..94f58af92 100644 --- a/exercises/accumulate/AccumulateExample.swift +++ b/exercises/accumulate/AccumulateExample.swift @@ -1,7 +1,5 @@ - // Foundation not needed - extension Array { func accumulate(yield: (Element) -> S) -> [S] { var result: [S] = [S]() diff --git a/exercises/accumulate/AccumulateTest.swift b/exercises/accumulate/AccumulateTest.swift index 830bc5f1b..cb31d9fe5 100644 --- a/exercises/accumulate/AccumulateTest.swift +++ b/exercises/accumulate/AccumulateTest.swift @@ -1,12 +1,8 @@ - import XCTest - - private extension String { - - var length: Int {return self.characters.count} - + var length: Int { return self.characters.count } + func reverse() -> String { var result:String = "" for char in self.characters { @@ -14,66 +10,57 @@ private extension String { } return result } - } class AccumulateTest: XCTestCase { - - func testEmptyAccumulation() { - - let input = [Int]() - func square(input:Int) -> Int { + func testEmptyAccumulation() { + let input = [Int]() + func square(input:Int) -> Int { return input * input - } - let result = input.accumulate(square) - + } + let result = input.accumulate(square) + XCTAssertTrue(result.isEmpty) } func testAccumulateSquares() { - + let input = [1,2,3,4] let expected = [1,4,9,16] func square(input:Int) -> Int { return input * input } - + let result = input.accumulate(square) - + XCTAssertEqual(expected, result) } - func testAccumulateUpcases() { - let input = ["hello","world"] let expected = ["HELLO","WORLD"] func toUpper(input:String) -> String { return input.uppercaseString } - + let result = input.accumulate(toUpper) - + XCTAssertEqual(expected, result) + } - } - - func testAccumulateReversedStrings() { - let input = ["the","quick","brown","fox","etc"] let expected = ["eht","kciuq","nworb","xof","cte"] func reverse(input:String) -> String { return input.reverse() } - + let result = input.accumulate(reverse) - + XCTAssertEqual(expected, result) } - + func testAccumulateRecursively() { - let input = ["a","b","c"] let expected = [ @@ -81,7 +68,7 @@ class AccumulateTest: XCTestCase { ["b1","b2","b3"], ["c1","c2","c3"] ] - + func recurse(input:String) -> [String] { func appendTo(innerInput:String) -> String { return input+innerInput @@ -90,9 +77,8 @@ class AccumulateTest: XCTestCase { return result } - let result = input.accumulate(recurse) - + XCTAssertEqual(expected, result) } } diff --git a/exercises/acronym/AcronymExample.swift b/exercises/acronym/AcronymExample.swift index 358d93c6f..586dc0b99 100644 --- a/exercises/acronym/AcronymExample.swift +++ b/exercises/acronym/AcronymExample.swift @@ -1,39 +1,34 @@ // Foundation not needed - - -private extension String{ - - func substringWithRangeInt(intRange:Range)->String{ +private extension String { + func substringWithRangeInt(intRange:Range) -> String { let start = self.startIndex.advancedBy(intRange.startIndex) let end = self.startIndex.advancedBy(intRange.endIndex) return self.substringWithRange(start.. String{ + + func substringWithRangeInt(start start:Int, end:Int) -> String { let range = start.. String { - var previousLetter:String = "" - + func splitCamelcaseAt(currentLetter: String, inout withString previousLetter: String ) -> Bool { - + defer { previousLetter = currentLetter } - + if currentLetter == " " { return false } else if currentLetter.isEmpty { return false } else if (previousLetter.isLowercase && currentLetter.isUppercase){ @@ -43,11 +38,11 @@ struct Acronym{ //previousLetter = currentLetter // see defer block return false } - + func insertSpaceAtCamelcase(inString:String)->String{ var accumulate = "" var lastIndexAdded = 0 - + for (index , each) in inString.characters.map({String($0)}).enumerate() { if splitCamelcaseAt(each, withString: &previousLetter){ accumulate += inString.substringWithRangeInt(start: lastIndexAdded, end: index)+" " // inserts a space @@ -57,7 +52,7 @@ struct Acronym{ let lastStringSection = inString.substringWithRangeInt(start: lastIndexAdded, end: inString.characters.count) return accumulate + lastStringSection } - + func splitAt(characterToCompare:Character, charToSplitAt:String = " ,-:")-> Bool{ for each in charToSplitAt.characters{ if each == characterToCompare{ @@ -66,15 +61,12 @@ struct Acronym{ } return false } - + func splitStringToArray(inString:String) -> [String]{ - + return inString.characters.split(isSeparator: { splitAt($0) }).map{String($0)} } - + return splitStringToArray(insertSpaceAtCamelcase(inString)).map({$0.uppercaseString.substringWithRangeInt(start: 0, end: 1)}).joinWithSeparator("") } - } - - diff --git a/exercises/acronym/AcronymTest.swift b/exercises/acronym/AcronymTest.swift index 608e80423..47627355a 100644 --- a/exercises/acronym/AcronymTest.swift +++ b/exercises/acronym/AcronymTest.swift @@ -1,32 +1,27 @@ - import XCTest - - class AcronymTest: XCTestCase { - func testAcronymAbbreviateTest1(){ XCTAssertEqual("PNG", Acronym.abbreviate("Portable Network Graphics")) } - + func testAcronymAbbreviateTest2(){ XCTAssertEqual("ROR", Acronym.abbreviate("Ruby on Rails")) } - + func testAcronymAbbreviateTest3(){ XCTAssertEqual("HTML", Acronym.abbreviate("HyperText Markup Language")) } - + func testAcronymAbbreviateTest4(){ XCTAssertEqual("FIFO", Acronym.abbreviate("First In, First Out")) } - + func testAcronymAbbreviateTest5(){ XCTAssertEqual("PHP", Acronym.abbreviate("PHP: Hypertext Preprocessor")) } - + func testAcronymAbbreviateTest6(){ XCTAssertEqual("CMOS", Acronym.abbreviate("Complementary metal-oxide semiconductor")) } - -} \ No newline at end of file +} diff --git a/exercises/allergies/AllergiesExample.swift b/exercises/allergies/AllergiesExample.swift index 51541579d..651c590f7 100644 --- a/exercises/allergies/AllergiesExample.swift +++ b/exercises/allergies/AllergiesExample.swift @@ -1,7 +1,5 @@ // Foundation not needed - - enum Allergen: UInt { case Eggs = 1 case Peanuts = 2 @@ -15,12 +13,12 @@ enum Allergen: UInt { struct Allergies { let score: UInt - + init(_ score: UInt) { self.score = UInt(score) } - + func hasAllergy(allergen: Allergen) -> Bool { return allergen.rawValue & score == allergen.rawValue ? true : false } -} \ No newline at end of file +} diff --git a/exercises/allergies/AllergiesTest.swift b/exercises/allergies/AllergiesTest.swift index cb25d9e80..6da1754cf 100644 --- a/exercises/allergies/AllergiesTest.swift +++ b/exercises/allergies/AllergiesTest.swift @@ -1,40 +1,31 @@ - import XCTest - - class AllergiesTest: XCTestCase { - func testBob() { - let allergies = Allergies(34) - + XCTAssertTrue(allergies.hasAllergy(.Peanuts), "Bob is allergic to peanuts") XCTAssertTrue(allergies.hasAllergy(.Chocolate), "Bob is allergic to chocolate") XCTAssertFalse(allergies.hasAllergy(.Cats), "Bob is not allergic to cats") } - + func testEggsNcats() { - let allergies = Allergies(129) - + XCTAssertTrue(allergies.hasAllergy(.Eggs)) XCTAssertTrue(allergies.hasAllergy(.Cats)) XCTAssertFalse(allergies.hasAllergy(.Chocolate)) - } - + func testNone() { let allergies = Allergies(0) - XCTAssertFalse(allergies.hasAllergy(.Pollen)) } - + func testAll() { - let allInt = UInt(Array(0...7).reduce(0){ return ($0 | (1 << $1)) }) let allergies = Allergies(allInt) - + XCTAssertTrue(allergies.hasAllergy(.Eggs)) XCTAssertTrue(allergies.hasAllergy(.Peanuts)) XCTAssertTrue(allergies.hasAllergy(.Shellfish)) @@ -43,6 +34,5 @@ class AllergiesTest: XCTestCase { XCTAssertTrue(allergies.hasAllergy(.Chocolate)) XCTAssertTrue(allergies.hasAllergy(.Pollen)) XCTAssertTrue(allergies.hasAllergy(.Cats)) - } } diff --git a/exercises/anagram/AnagramExample.swift b/exercises/anagram/AnagramExample.swift index 2bda4c09a..873a5c4e8 100644 --- a/exercises/anagram/AnagramExample.swift +++ b/exercises/anagram/AnagramExample.swift @@ -1,13 +1,11 @@ // Foundation not needed - - struct Anagram { var baseWord = "" init (word: String) { baseWord = word } - + func sortLetters(wordToSort: String) -> String { var characters: [String] = [] for char in wordToSort.characters { @@ -16,20 +14,17 @@ struct Anagram { characters = characters.sort(< ) return characters.reduce("", combine: +) } - + func match(words: [String]) -> [String] { var matches: [String] = [] - + for candidateWord in words { if sortLetters(baseWord.lowercaseString) == sortLetters(candidateWord.lowercaseString) && baseWord.lowercaseString != candidateWord.lowercaseString { matches.append(candidateWord) } } - + return matches } - } - - diff --git a/exercises/anagram/AnagramTest.swift b/exercises/anagram/AnagramTest.swift index 41b54113b..35110fe52 100644 --- a/exercises/anagram/AnagramTest.swift +++ b/exercises/anagram/AnagramTest.swift @@ -1,79 +1,73 @@ - import XCTest - - class AnagramTest: XCTestCase { - func testNoMatches() { let anagram = Anagram(word: "diaper") let results = anagram.match(["hello","world","zombies","pants"]) let expected = [] XCTAssertEqual(results, expected) } - - + func testDetectSimpleAnagram() { let anagram = Anagram(word: "ant") let results = anagram.match(["tan","stand","at"]) let expected = ["tan"] XCTAssertEqual(results, expected) } - + func testDetectMultipleAnagrams() { let anagram = Anagram(word: "master") let results = anagram.match(["stream","pigeon","maters"]) let expected = ["stream","maters"] XCTAssertEqual(results, expected) } - + func testDoesNotConfuseDifferentDuplicates() { let anagram = Anagram(word: "galea") let results = anagram.match(["eagle"]) let expected = [] XCTAssertEqual(results, expected) } - + func testIdenticalWordIsNotAnagram() { let anagram = Anagram(word: "corn") let results = anagram.match(["corn", "dark", "Corn", "rank", "CORN", "cron", "park"]) let expected = ["cron"] XCTAssertEqual(results, expected) } - + func testEliminateAnagramsWithSameChecksum() { let anagram = Anagram(word: "mass") let results = anagram.match(["last"]) let expected = [] XCTAssertEqual(results, expected) } - + func testEliminateAnagramSubsets() { let anagram = Anagram(word: "good") let results = anagram.match(["dog","goody"]) let expected = [] XCTAssertEqual(results, expected) } - + func testDetectAnagram() { let anagram = Anagram(word: "listen") let results = anagram.match(["enlists","google","inlets","banana"]) let expected = ["inlets"] XCTAssertEqual(results, expected) } - + func testMultipleAnagrams() { let anagram = Anagram(word: "allergy") let results = anagram.match(["gallery","ballerina","regally","clergy","largely","leading"]) let expected = ["gallery","regally","largely"] XCTAssertEqual(results, expected) } - + func testAnagramsAreCaseInsensitive() { let anagram = Anagram(word: "Orchestra") let results = anagram.match(["cashregister","Carthorse","radishes"]) let expected = ["Carthorse"] XCTAssertEqual(results, expected) } - } diff --git a/exercises/atbash-cipher/AtbashExample.swift b/exercises/atbash-cipher/AtbashExample.swift index c30580131..57a223de4 100644 --- a/exercises/atbash-cipher/AtbashExample.swift +++ b/exercises/atbash-cipher/AtbashExample.swift @@ -1,45 +1,42 @@ // Foundation not needed - - struct Atbash { - - private static func stripWhiteSpaceAndPunctuations(input:String) ->String{ + private static func stripWhiteSpaceAndPunctuations(input: String) ->String { var returnString = "" - input.characters.forEach{ - if !" ,.".containsString(String($0)){ + input.characters.forEach { + if !" ,.".containsString(String($0)) { returnString.append($0) } } - + return returnString } - - - - static let cipherDictApply:[Character : Character] = ["a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"] - - static func encode( valueIn:String)->String{ - let value = stripWhiteSpaceAndPunctuations(valueIn.lowercaseString ) - + + static let cipherDictApply: [Character : Character] = ["a": "z", "b": "y", "c": "x", "d": "w", "e": "v", "f": "u", "g": "t", "h": "s", "i": "r", "j": "q", "k": "p", "l": "o", "m": "n", "n": "m", "o": "l", "p": "k", "q": "j", "r": "i", "s": "h", "t": "g", "u": "f", "v": "e", "w": "d", "x": "c", "y": "b", "z": "a"] + + static func encode(valueIn: String) -> String { + let value = stripWhiteSpaceAndPunctuations(valueIn.lowercaseString ) + var text2return = "" - - for each in value.characters{ + + for each in value.characters { text2return.append(cipherDictApply[each] ?? each ) } + return insertSpace5th(text2return) } - - static func insertSpace5th(value:String)->String{ + + static func insertSpace5th(value: String) -> String { var tempCounter = 0 - var tempString:String = "" - for each in value.characters{ + var tempString: String = "" + for each in value.characters { if tempCounter % 5 == 0 && tempCounter != 0{ tempString += " \(each)" - } else { tempString += "\(each)" } + } else { + tempString += "\(each)" + } tempCounter += 1 } return tempString } - -} \ No newline at end of file +} diff --git a/exercises/atbash-cipher/AtbashTest.swift b/exercises/atbash-cipher/AtbashTest.swift index eedb999b0..7c880da06 100644 --- a/exercises/atbash-cipher/AtbashTest.swift +++ b/exercises/atbash-cipher/AtbashTest.swift @@ -1,43 +1,38 @@ - import XCTest - - class AtbashTest: XCTestCase { - func testEncodeNo() { XCTAssertEqual("ml", Atbash.encode("no") ) } - + func testEncodeYes() { XCTAssertEqual("bvh", Atbash.encode("yes") ) } - + func testEncodeOMG() { XCTAssertEqual("lnt", Atbash.encode("OMG") ) } - + func testEncodeOMGWithSpaces() { XCTAssertEqual("lnt", Atbash.encode("O M G") ) } - + func testEncodeLongWord() { XCTAssertEqual("nrmwy oldrm tob", Atbash.encode("mindblowingly") ) } - + func testEncodeNumbers() { XCTAssertEqual("gvhgr mt123 gvhgr mt", - Atbash.encode("Testing, 1 2 3, testing.") ) + Atbash.encode("Testing, 1 2 3, testing.") ) } - + func testEncodeSentence() { XCTAssertEqual("gifgs rhurx grlm", Atbash.encode("Truth is fiction.") ) } - + func testEncodeAllTheThings() { let plaintext = "The quick brown fox jumps over the lazy dog." let cipher = "gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt" XCTAssertEqual(cipher, Atbash.encode(plaintext) ) } - } diff --git a/exercises/binary-search-tree/BinarySearchTreeExample.swift b/exercises/binary-search-tree/BinarySearchTreeExample.swift index 6978d4f3d..e1d9e6455 100644 --- a/exercises/binary-search-tree/BinarySearchTreeExample.swift +++ b/exercises/binary-search-tree/BinarySearchTreeExample.swift @@ -1,15 +1,15 @@ // Foundation not needed class BinarySearchTree { - + var data: T var left: BinarySearchTree? var right: BinarySearchTree? - + init(_ data: T) { self.data = data } - + func insert(newData: T) { if newData <= data { if let left = left { @@ -25,23 +25,22 @@ class BinarySearchTree { } } } - + func allData() -> [T] { return getAllData().sort(<) } - + private func getAllData() -> [T] { var result = [data] - + if let left = left { result += left.getAllData() } - + if let right = right { result += right.getAllData() } - + return result } - -} \ No newline at end of file +} diff --git a/exercises/binary-search-tree/BinarySearchTreeTest.swift b/exercises/binary-search-tree/BinarySearchTreeTest.swift index c0fd94085..983f81fa2 100644 --- a/exercises/binary-search-tree/BinarySearchTreeTest.swift +++ b/exercises/binary-search-tree/BinarySearchTreeTest.swift @@ -1,34 +1,31 @@ import XCTest - - class BinarySearchTreeTest: XCTestCase { - func testDataIsRetained() { XCTAssertEqual(4, BinarySearchTree(4).data) } - + func testInsertingLess() { var four = BinarySearchTree(4) four.insert(2) XCTAssertEqual(4, four.data) XCTAssertEqual(2, four.left?.data) } - + func testInsertingSame() { var four = BinarySearchTree(4) four.insert(4) XCTAssertEqual(4, four.data) XCTAssertEqual(4, four.left?.data) } - + func testInsertingRight() { var four = BinarySearchTree(4) four.insert(5) XCTAssertEqual(4, four.data) XCTAssertEqual(5, four.right?.data) } - + func testComplexTree() { var four = BinarySearchTree(4) four.insert(2) @@ -45,17 +42,17 @@ class BinarySearchTreeTest: XCTestCase { XCTAssertEqual(5, four.right?.left?.data) XCTAssertEqual(7, four.right?.right?.data) } - + func testAllDataForOneElement() { XCTAssertEqual([4], BinarySearchTree(4).allData()) } - + func testAllDataForSmallerElement() { var four = BinarySearchTree(4) four.insert(2) XCTAssertEqual([2, 4], four.allData()) } - + func testAllDataForLargerElement() { var four = BinarySearchTree(4) four.insert(5) @@ -72,5 +69,4 @@ class BinarySearchTreeTest: XCTestCase { four.insert(5) XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], four.allData()) } - } diff --git a/exercises/binary-search/BinarySearchExample.swift b/exercises/binary-search/BinarySearchExample.swift index adb9828d2..185cac9df 100644 --- a/exercises/binary-search/BinarySearchExample.swift +++ b/exercises/binary-search/BinarySearchExample.swift @@ -1,7 +1,5 @@ // Foundation not needed - - // Note: Placing this enum inside the BinarySearch struct results in a compiler crash #if swift(>=3.0) @@ -10,35 +8,34 @@ } #else enum BinarySearchError: ErrorType { - case Unsorted + case Unsorted } #endif struct BinarySearch { - let list: [T] var middle: Int { return list.count / 2 } - + init(_ list: [T]) throws { #if swift(>=3.0) - guard list == list.sorted(isOrderedBefore: <) else { - throw BinarySearchError.Unsorted - } + guard list == list.sorted(isOrderedBefore: <) else { + throw BinarySearchError.Unsorted + } #else guard list == list.sort(<) else { throw BinarySearchError.Unsorted } - + #endif - + self.list = list } - + func searchFor(datum: T) -> Int? { let middleItem = list[middle] - + if middleItem == datum { return middle } else if middleItem > datum { @@ -46,7 +43,7 @@ struct BinarySearch { guard sublist != list else { return nil } - + // try! is safe here, since it's not possible to get here if the data isn't initially sorted return try! BinarySearch(sublist).searchFor(datum) } else { @@ -54,7 +51,7 @@ struct BinarySearch { guard sublist != list else { return nil } - + // try! is safe here, since it's not possible to get here if the data isn't initially sorted if let index = try! BinarySearch(sublist).searchFor(datum) { return index + middle @@ -63,5 +60,4 @@ struct BinarySearch { } } } - -} \ No newline at end of file +} diff --git a/exercises/binary-search/BinarySearchTest.swift b/exercises/binary-search/BinarySearchTest.swift index 1f5962852..0dfdb34ea 100644 --- a/exercises/binary-search/BinarySearchTest.swift +++ b/exercises/binary-search/BinarySearchTest.swift @@ -1,9 +1,6 @@ import XCTest - - class BinarySearchTest: XCTestCase { - func testHasListData() { let binary = try! BinarySearch([1, 3, 4, 6, 8, 9, 11]) XCTAssertEqual([1, 3, 4, 6, 8, 9, 11], binary.list) @@ -11,11 +8,11 @@ class BinarySearchTest: XCTestCase { func testThrowsErrorForUnsortedList() { var throwsUnsortedError = false - + defer { XCTAssertTrue(throwsUnsortedError) } - + do { let _ = try BinarySearch([2, 1, 4, 3, 6]) } catch BinarySearchError.Unsorted { @@ -28,23 +25,23 @@ class BinarySearchTest: XCTestCase { func testNilForDataNotInList() { XCTAssertNil(try! BinarySearch([1, 3, 6]).searchFor(2)) } - + func testFindsPositionOfMiddleItem() { let binary = try! BinarySearch([1, 3, 4, 6, 8, 9, 11]) - XCTAssertEqual(3, binary.middle) + XCTAssertEqual(3, binary.middle) } - + func testFindsPositionOfSearchData() { let binary = try! BinarySearch([1, 3, 4, 6, 8, 9, 11]) XCTAssertEqual(5, binary.searchFor(9)) } - + func testFindsPositionInALargerList() { let binary = try! BinarySearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144]) XCTAssertEqual(1, binary.searchFor(3)) XCTAssertEqual(7, binary.searchFor(55)) } - + func testFindsCorrectPositionInAListWithAnEvenNumberOfElements() { let binary = try! BinarySearch([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]) XCTAssertEqual(5, binary.searchFor(21)) diff --git a/exercises/binary/BinaryExample.swift b/exercises/binary/BinaryExample.swift index 2df95da01..0a93454a8 100644 --- a/exercises/binary/BinaryExample.swift +++ b/exercises/binary/BinaryExample.swift @@ -1,24 +1,28 @@ // Foundation not needed - - -extension Int{ - init(_ value:Binary?){ +extension Int { + init(_ value: Binary?) { if let value = value { - self = value.toDecimal + self = value.toDecimal } else { - self = 0 } + self = 0 + } } } - struct Binary { private var UIntValue:UInt = 0 - private var toDecimal:Int {get {return Int(UIntValue)}} - private func bi2Uint(input:String) -> UInt?{ + + private var toDecimal: Int { + get { + return Int(UIntValue) + } + } + + private func bi2Uint(input: String) -> UInt? { let orderedInput = Array(input.characters.reverse()) - var tempUInt:UInt = 0 - for (inx,each) in orderedInput.enumerate(){ + var tempUInt: UInt = 0 + for (inx,each) in orderedInput.enumerate() { if each == "1" { tempUInt += UInt(0x1 << inx) } @@ -28,13 +32,12 @@ struct Binary { } return tempUInt } - - init?(_ input:String){ + + init?(_ input: String){ if bi2Uint(input) != nil { - self.UIntValue = bi2Uint(input)! + self.UIntValue = bi2Uint(input)! } else { - return nil + return nil } - } -} \ No newline at end of file +} diff --git a/exercises/binary/BinaryTest.swift b/exercises/binary/BinaryTest.swift index 0c8158e55..c354d642f 100644 --- a/exercises/binary/BinaryTest.swift +++ b/exercises/binary/BinaryTest.swift @@ -1,54 +1,49 @@ import XCTest - - class BinaryTests: XCTestCase { - func testBinary0IsDecimal0() { XCTAssertEqual( 0, Int(Binary("0"))) } - + func testBinary1isDecimal1() { XCTAssertEqual( 1, Int(Binary("1"))) } - + func testBinary10isDecimal2() { XCTAssertEqual( 2, Int(Binary("10"))) } - + func testBinary11isDecimal3() { XCTAssertEqual( 3, Int(Binary("11"))) } - + func testBinary100isDecimal4() { XCTAssertEqual( 4, Int(Binary("100"))) } - + func testBinary1001isDecimal9() { XCTAssertEqual( 9, Int(Binary("1001"))) } - + func testBinary11010isDecimal26() { XCTAssertEqual( 26, Int(Binary("11010"))) } - + func testBinary10001101000isDecimal1128() { XCTAssertEqual( 1128, Int(Binary("10001101000"))) } - + func testBinaryIgnoresLeadingZeros() { XCTAssertEqual( 31, Int(Binary("000011111"))) } - + func testInvalidBinaryIsDecimal0() { XCTAssertNil ( Binary("carrot123")) } - + func testInvalidBinaryNumbers() { XCTAssertNil ( Binary("012")) XCTAssertNil ( Binary("10nope")) XCTAssertNil ( Binary("nope10")) - } - } diff --git a/exercises/bob/BobExample.swift b/exercises/bob/BobExample.swift index 109a7ae98..f77c04b13 100644 --- a/exercises/bob/BobExample.swift +++ b/exercises/bob/BobExample.swift @@ -1,71 +1,67 @@ // Foundation not needed - - private extension String { - - func trimWhiteSpace()-> String{ + func trimWhiteSpace() -> String { let removeSpaces = trimCharacters(" ", sourceText: self) if removeSpaces.hasSuffix("\n"){ return String(removeSpaces.characters.dropLast()) } return removeSpaces } - - func trimCharacters(charToTrim:Character, sourceText:String) -> String{ + + func trimCharacters(charToTrim: Character, sourceText: String) -> String { var editCharacterView = sourceText.characters var editString = String(editCharacterView) - + let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim - + if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } - + if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } return editString } - - - var isQuestion:Bool { + + var isQuestion: Bool { return hasSuffix("?") } - - var hasLetters:Bool { + + var hasLetters: Bool { return containsLetters(self) } - - var isShouting:Bool { + + var isShouting: Bool { #if swift(>=3.0) return (self == uppercased() && hasLetters) #else return (self == uppercaseString && hasLetters) #endif } - - private func containsLetters(input:String) ->Bool{ + + private func containsLetters(input: String) -> Bool { let abc = "abcdefghijklmnopqrstuvwxyz" var contains = false let inputStringCollection = input.characters.map({String($0)}) let abcStringCollection = abc.characters.map({String($0)}) - + for each in inputStringCollection { abcStringCollection.forEach({ - #if swift(>=3.0) if each == $0 || each == $0.uppercased() { - contains = true } + contains = true + } #else if each == $0 || each == $0.uppercaseString { - contains = true } + contains = true + } #endif }) } return contains } - } struct Bob { @@ -80,6 +76,4 @@ struct Bob { return "Whatever." } } - } - diff --git a/exercises/bob/BobTest.swift b/exercises/bob/BobTest.swift index 5e1ff886a..d5941d0e8 100644 --- a/exercises/bob/BobTest.swift +++ b/exercises/bob/BobTest.swift @@ -1,126 +1,122 @@ import XCTest - - class BobTests: XCTestCase { - func testStatingSomething() { let input = "Tom-ay-to, tom-aaaah-to." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShouting() { let input = "WATCH OUT!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testAskingAQustion() { let input = "Does this cryogenic chamber make me look fat?" let expected = "Sure." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testTalkingForcefully() { let input = "Let's go make out behind the gym!" let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testUsingAcronyms() { let input = "It's OK if you don't want to go to the DMV." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testForcefulQuestions() { let input = "WHAT THE HELL WERE YOU THINKING?" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingNumbers() { let input = "1, 2, 3 GO!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testOnlyNumbers() { let input = "1, 2, 3." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testQuestionWithOnlyNumbers() { let input = "4?" let expected = "Sure." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingWithSpecialCharacters() { let input = "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingWithUmlautsCharacters() { let input = "ÄMLÄTS!" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testCalmlySpeakingAboutUmlauts() { let input = "ÄMLäTS!" let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testShoutingWithNoExclamationmark() { let input = "I HATE YOU" let expected = "Woah, chill out!" let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testStatementContainingQuestionsMark() { let input = "Ending with a ? means a question." let expected = "Whatever." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testPrattlingOn() { let input = "Wait! Hang on. Are you going to be OK?" let expected = "Sure." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testSilence() { let input = "" let expected = "Fine, be that way." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - + func testProlongedSilence() { let input = " " let expected = "Fine, be that way." let result = Bob.hey(input) XCTAssertEqual(expected, result) } - } diff --git a/exercises/clock/ClockExample.swift b/exercises/clock/ClockExample.swift index 4a9a8ea9c..c9c35a89b 100644 --- a/exercises/clock/ClockExample.swift +++ b/exercises/clock/ClockExample.swift @@ -1,33 +1,32 @@ // Foundation not needed struct Clock: Equatable, CustomStringConvertible { - var hours: Int var minutes: Int - + init(hours: Int, minutes: Int = 0) { self.hours = hours self.minutes = minutes normalize() } - + var description: String { return self.toString } - - func add(minutes minutes:Int) -> Clock { + + func add(minutes minutes: Int) -> Clock { return Clock(hours: self.hours, minutes: self.minutes + minutes) } - - func subtract(minutes minutes:Int) -> Clock { + + func subtract(minutes minutes: Int) -> Clock { return add(minutes: -minutes) } - + private var toString: String { let h = String(format: "%02d", self.hours) let m = String(format: "%02d", self.minutes) - + return h + ":" + m } - + private mutating func normalize() { if minutes >= 60 { self.hours += self.minutes / 60 @@ -44,7 +43,6 @@ struct Clock: Equatable, CustomStringConvertible { self.hours += 24 } } - } private extension String { @@ -53,6 +51,6 @@ private extension String { } } -func == (lhs: Clock, rhs: Clock) -> Bool { +func ==(lhs: Clock, rhs: Clock) -> Bool { return lhs.description == rhs.description -} \ No newline at end of file +} diff --git a/exercises/clock/ClockTest.swift b/exercises/clock/ClockTest.swift index d3cb257b7..4a0b5db79 100644 --- a/exercises/clock/ClockTest.swift +++ b/exercises/clock/ClockTest.swift @@ -1,215 +1,211 @@ -import XCTest - - - // Test for Protocols: CustomStringConvertible, Equatable +import XCTest class ClockTest: XCTestCase { - // MARK: - Create: Test creating a new clock with an initial time. - + func testOnTheHour() { XCTAssertEqual("08:00", Clock(hours: 8).description) } - + func testPastTheHour() { XCTAssertEqual("11:09", Clock(hours: 11, minutes: 9).description) } - + func testMidnightIsZeroHours() { XCTAssertEqual("00:00", Clock(hours: 24).description) } - + func testHourRollsOver() { XCTAssertEqual("01:00", Clock(hours: 25).description) } - + func testHourRollsOverContinuously() { XCTAssertEqual("04:00", Clock(hours: 100).description) } - + func testSixtyMinutesIsNextHour() { XCTAssertEqual("02:00", Clock(hours: 1, minutes: 60).description) } - + func testMinutesRollOver() { XCTAssertEqual("02:40", Clock(hours: 0, minutes: 160).description) } - + func testMinutesRollOverContinuously() { XCTAssertEqual("04:43", Clock(hours: 0, minutes: 1723).description) } - + func testHoursAndMinutesRollOver() { XCTAssertEqual("11:01", Clock(hours: 201, minutes: 3001).description) } - + func testHoursAndMinutesRollOverToExactlyMidnight() { XCTAssertEqual("00:00", Clock(hours: 72, minutes: 8640).description) } - + func testNegativeHour() { XCTAssertEqual("23:15", Clock(hours: -1, minutes: 15).description) } - + func testNegativeHourRollsOver() { XCTAssertEqual("23:00", Clock(hours: -25).description) } - + func testNegativeHourRollsOverContinuously() { XCTAssertEqual("05:00", Clock(hours: -91).description) } - + func testNegativeMinutes() { XCTAssertEqual("00:20", Clock(hours: 1, minutes: -40).description) } - + func testNegativeMinutesRollOver() { XCTAssertEqual("22:20", Clock(hours: 1, minutes: -160).description) } - + func testNegativeMinutesRollOverContinuously() { XCTAssertEqual("16:40", Clock(hours: 1, minutes: -4820).description) } - + func testNegativeHoursAndMinutesBothRollOverContinuously() { XCTAssertEqual("22:10", Clock(hours: -121, minutes: -5810).description) } - + // MARK: - Add: Test adding and subtracting minutes. - + func testAddMinutes() { let clock = Clock(hours: 10).add(minutes: 3) XCTAssertEqual("10:03", clock.description) } - + func testAddNoMinutes() { let clock = Clock(hours: 6, minutes: 41).add(minutes: 0) XCTAssertEqual("06:41", clock.description) } - + func testAddToNextHour() { let clock = Clock(hours: 0, minutes: 45).add(minutes: 40) XCTAssertEqual("01:25", clock.description) } - + func testAddMoreThanOneHour() { let clock = Clock(hours: 10).add(minutes: 61) XCTAssertEqual("11:01", String(clock)) } - + func testAddMoreThanTwoHoursWithCarry() { let clock = Clock(hours: 0, minutes: 45).add(minutes: 160) XCTAssertEqual("03:25", clock.description) } - + func testAddAcrossMidnight() { let clock = Clock(hours: 23, minutes: 59).add(minutes: 2) XCTAssertEqual("00:01", String(clock)) } - + func testAddMoreThanOneDay() { // (1500 min = 25 hrs) let clock = Clock(hours: 5, minutes: 32).add(minutes: 1500) XCTAssertEqual("06:32", String(clock)) } - + func testAddMoreThanTwoDays() { let clock = Clock(hours: 1, minutes: 1).add(minutes: 3500) XCTAssertEqual("11:21", String(clock)) } - + func testSubtractMinutes() { let clock = Clock(hours: 10, minutes: 3).subtract(minutes: 3) XCTAssertEqual("10:00", String(clock)) } - + func testSubtractToPreviousHour() { let clock = Clock(hours: 10, minutes: 3).subtract(minutes: 30) XCTAssertEqual("09:33", String(clock)) } - + func testSubtractMoreThanAnHour() { let clock = Clock(hours: 10, minutes: 3).subtract(minutes: 70) XCTAssertEqual("08:53", String(clock)) } - + func testSubtractAcrossMidnight() { let clock = Clock(hours: 0, minutes: 3).subtract(minutes: 4) XCTAssertEqual("23:59", String(clock)) } - + func testSubtractMoreThanTwoHours() { let clock = Clock(hours: 0, minutes: 0).subtract(minutes: 160) XCTAssertEqual("21:20", String(clock)) } - + func testSubtractMoreTHanTwoHoursWithBorrow() { let clock = Clock(hours: 6, minutes: 15).subtract(minutes: 160) XCTAssertEqual("03:35", String(clock)) } - + func testSubtractMoreThanOneDay() { // (1500 min = 25 hrs) let clock = Clock(hours: 5, minutes: 32).subtract(minutes: 1500) XCTAssertEqual("04:32", String(clock)) } - + func testSubtractMoreThanTwoDays() { let clock = Clock(hours: 2, minutes: 20).subtract(minutes: 3000) XCTAssertEqual("00:20", String(clock)) } - + // MARK: - Equal: Construct two separate clocks, set times, test if they are equal. - + func testClocksWithSameTime() { let clock1 = Clock(hours: 15, minutes: 37) let clock2 = Clock(hours: 15, minutes: 37) XCTAssertEqual(clock1, clock2) } - + func testClocksAMinuteApart() { let clock1 = Clock(hours: 15, minutes: 36) let clock2 = Clock(hours: 15, minutes: 37) XCTAssertNotEqual(clock1, clock2) } - + func testClocksAnHourApart() { let clock1 = Clock(hours: 14, minutes: 37) let clock2 = Clock(hours: 15, minutes: 37) XCTAssertNotEqual(clock1, clock2) } - + func testClocksWithHourOverflow() { let clock1 = Clock(hours: 10, minutes: 37) let clock2 = Clock(hours: 34, minutes: 37) XCTAssertEqual(clock1, clock2) } - + func testClocksWithHourOverflowBySeveralDays() { let clock1 = Clock(hours: 3, minutes: 11) let clock2 = Clock(hours: 99, minutes: 11) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHour() { let clock1 = Clock(hours: 22, minutes: 40) let clock2 = Clock(hours: -2, minutes: 40) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHourThatWraps() { let clock1 = Clock(hours: 17, minutes: 3) let clock2 = Clock(hours: -31, minutes: 3) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHourThatWrapsMultipleTimes() { let clock1 = Clock(hours: 13, minutes: 49) let clock2 = Clock(hours: -83, minutes: 49) XCTAssertEqual(clock1, clock2) } - + func testClocksWithMinuteOverflow() { let clock1 = Clock(hours: 0, minutes: 1) let clock2 = Clock(hours: 0, minutes: 1441) @@ -221,35 +217,34 @@ class ClockTest: XCTestCase { let clock2 = Clock(hours: 2, minutes: 4322) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeMinute() { let clock1 = Clock(hours: 2, minutes: 40) let clock2 = Clock(hours: 3, minutes: -20) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeMinuteThatWraps() { let clock1 = Clock(hours: 4, minutes: 10) let clock2 = Clock(hours: 5, minutes: -1490) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeMinuteThatWrapsMultipleTimes() { let clock1 = Clock(hours: 6, minutes: 15) let clock2 = Clock(hours: 6, minutes: -4305) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHoursAndMinutes() { let clock1 = Clock(hours: 7, minutes: 32) let clock2 = Clock(hours: -12, minutes: -268) XCTAssertEqual(clock1, clock2) } - + func testClocksWithNegativeHoursAndMinutesThatWrap() { let clock1 = Clock(hours: 18, minutes: 7) let clock2 = Clock(hours: -54, minutes: -11513) XCTAssertEqual(clock1, clock2) } - } diff --git a/exercises/crypto-square/CryptoSquareExample.swift b/exercises/crypto-square/CryptoSquareExample.swift index 9b8a47a12..fb9f56561 100644 --- a/exercises/crypto-square/CryptoSquareExample.swift +++ b/exercises/crypto-square/CryptoSquareExample.swift @@ -1,101 +1,90 @@ import Darwin - - private extension String { - - func stripCharacters(charToRemove:String) -> String{ + func stripCharacters(charToRemove: String) -> String { var returnString = "" - self.characters.forEach{ - if !charToRemove.containsString(String($0)){ + self.characters.forEach { + if !charToRemove.containsString(String($0)) { returnString.append($0) }} return returnString } - - var stripWhiteSpace:String { return stripCharacters(" ") } - var stripPunctuations:String { return stripCharacters(",.!?") } - var stripSymbols:String { return stripCharacters("#$%^&") } - - -} - + var stripWhiteSpace: String { return stripCharacters(" ") } + var stripPunctuations: String { return stripCharacters(",.!?") } + var stripSymbols: String { return stripCharacters("#$%^&") } +} struct Crypto { - - func segmentSorter(value:String, spacing:Int)->[String]{ + func segmentSorter(value: String, spacing: Int) -> [String] { var tempCounter = 0 - var tempString:String = "" - for each in value.characters{ - if tempCounter % spacing == 0 && tempCounter != 0{ + var tempString: String = "" + for each in value.characters { + if tempCounter % spacing == 0 && tempCounter != 0 { tempString += " \(each)" - } else { tempString += "\(each)" } + } else { + tempString += "\(each)" + } tempCounter += 1 } - return (tempString.componentsSeparatedByString(" ") ) + return tempString.componentsSeparatedByString(" ") } - - func getSquareSize(text:String, floorNoCeling:Bool = false)->Int - { + + func getSquareSize(text: String, floorNoCeling: Bool = false) -> Int { let tempDouble = Double(text.characters.count) let tempRoot = sqrt(tempDouble) let tempCeil = ceil(tempRoot) let tempFloor = floor(tempRoot) - if floorNoCeling{ return Int(tempFloor)} else { - return Int(tempCeil)} + if floorNoCeling { + return Int(tempFloor) + } else { + return Int(tempCeil) + } } - - func normalizer(textInput:String)->String{ + + func normalizer(textInput: String) -> String { return textInput.stripSymbols.stripPunctuations.stripWhiteSpace.lowercaseString } - - var ciphertext:String { - - var plaintextSegmentsArray = [[Character]]() - - for each in plaintextSegments{ - plaintextSegmentsArray.append(Array(each.characters)) + + var ciphertext: String { + var plaintextSegmentsArray = [[Character]]() + + for each in plaintextSegments { + plaintextSegmentsArray.append(Array(each.characters)) + } + + var ciphertextReturn = "" + + for i in 0 ..< plaintextSegmentsArray[0].count { + for e in 0 ..< plaintextSegmentsArray.count { + if i < plaintextSegmentsArray[e].count { + ciphertextReturn.append(plaintextSegmentsArray[e][i]) + } } - - var ciphertextReturn = "" - - - for i in 0 ..< plaintextSegmentsArray[0].count { - for e in 0 ..< plaintextSegmentsArray.count { - if i < plaintextSegmentsArray[e].count{ - ciphertextReturn.append(plaintextSegmentsArray[e][i]) - } - }} - - return ciphertextReturn - + } + + return ciphertextReturn } - - var normalizeCiphertext:String { - - let sizeNormal:Int = (ciphertext.characters.count == self.size * self.size ) ? getSquareSize(self.ciphertext) : getSquareSize(self.ciphertext, floorNoCeling: true) - + + var normalizeCiphertext: String { + let sizeNormal: Int = (ciphertext.characters.count == self.size * self.size ) ? getSquareSize(self.ciphertext) : getSquareSize(self.ciphertext, floorNoCeling: true) + return segmentSorter(ciphertext, spacing: sizeNormal).joinWithSeparator(" ") } - - - var plaintextSegments:[String]{ get{ return segmentSorter(self.normalizePlaintext, spacing: self.size)}} - - - var textValue:String = "" - var normalizePlaintext:String = "" - var size:Int = 0 - - init (_ value:String){ + + var plaintextSegments: [String] { + get { + return segmentSorter(self.normalizePlaintext, spacing: self.size) + } + } + + var textValue: String = "" + var normalizePlaintext: String = "" + var size: Int = 0 + + init (_ value: String) { self.textValue = value self.normalizePlaintext = normalizer(value) self.size = getSquareSize(self.normalizePlaintext) } } - - - - - - diff --git a/exercises/crypto-square/CryptoSquareTest.swift b/exercises/crypto-square/CryptoSquareTest.swift index a94a9e7fa..4d3d985be 100644 --- a/exercises/crypto-square/CryptoSquareTest.swift +++ b/exercises/crypto-square/CryptoSquareTest.swift @@ -1,24 +1,21 @@ import XCTest - - class CryptoSquareTest: XCTestCase { - func testNormalizeStrangeCharacters() { let crypto = Crypto("s#$%^&plunk") XCTAssertEqual("splunk", crypto.normalizePlaintext) } - + func testNormalizeUppercaseCharacters() { let crypto = Crypto("WHOA HEY!") XCTAssertEqual("whoahey", crypto.normalizePlaintext) } - + func testNormalizeWithNumbers() { let crypto = Crypto("1, 2, 3 GO!") XCTAssertEqual("123go", crypto.normalizePlaintext) } - + func testSizeOfSmallSquare() { let crypto = Crypto("1234") XCTAssertEqual(2, crypto.size) @@ -28,17 +25,17 @@ class CryptoSquareTest: XCTestCase { let crypto = Crypto("123456789") XCTAssertEqual(3, crypto.size) } - + func testSizeOfNonPerfectSquare() { let crypto = Crypto("123456789abc") XCTAssertEqual(4, crypto.size) } - + func testSizeIsDeterminedByNormalizedPlaintext() { let crypto = Crypto("Oh hey, this is nuts!") XCTAssertEqual(4, crypto.size) } - + func testPlaintextSegments() { let crypto = Crypto("Never vex thine heart with idle woes") let expected = ["neverv", "exthin", "eheart", "withid", "lewoes"] @@ -59,30 +56,28 @@ class CryptoSquareTest: XCTestCase { let crypto = Crypto("We all know interspecies romance is weird.") XCTAssertEqual("wneiaweoreneawssciliprerlneoidktcms", crypto.ciphertext) } - + func testNormalizedCiphertext() { let crypto = Crypto("Vampires are people too!") XCTAssertEqual("vrel aepe mset paoo irpo", crypto.normalizeCiphertext) } - + func testNormalizedCiphertextSpillsIntoShortSegment() { let crypto = Crypto("Madness, and then illumination.") XCTAssertEqual("msemo aanin dninn dlaet ltshu i", crypto.normalizeCiphertext) } - + func testAnotherNormalizedCiphertext() { let crypto = Crypto( "If man was meant to stay on the ground god would have given us roots" - ) - let expected = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghns seoau" + ) + let expected = "imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghns seoau" XCTAssertEqual(expected, crypto.normalizeCiphertext) } - + func testNormalizedCiphertextWithPunctuation() { let crypto = Crypto("Have a nice day. Feed the dog & chill out!") let expected = "hifei acedl veeol eddgo aatcu nyhht" XCTAssertEqual(expected, crypto.normalizeCiphertext) } - - -} \ No newline at end of file +} diff --git a/exercises/custom-set/CustomSetExample.swift b/exercises/custom-set/CustomSetExample.swift index 8d02910b7..cb6ec24f3 100644 --- a/exercises/custom-set/CustomSetExample.swift +++ b/exercises/custom-set/CustomSetExample.swift @@ -1,10 +1,6 @@ - // Foundation not needed - - - -func == (lh: CustomSet, rh: CustomSet) -> Bool { +func ==(lh: CustomSet, rh: CustomSet) -> Bool { #if swift(>=3.0) return lh.contents.keys.sorted{$0.hashValue < $1.hashValue} == rh.contents.keys.sorted{$0.hashValue < $1.hashValue} #else @@ -12,97 +8,81 @@ func == (lh: CustomSet, rh: CustomSet) -> Bool { #endif } - -struct CustomSet:Equatable{ - +struct CustomSet: Equatable { typealias Element = T - + private var contents = [Element: Bool]() - - var size:Int {return contents.count} - - + + var size: Int { return contents.count } + #if swift(>=3.0) - var toSortedArray:[Element] {return Array(contents.keys.sorted{$0.hashValue < $1.hashValue})} + var toSortedArray: [Element] { return Array(contents.keys.sorted{$0.hashValue < $1.hashValue}) } init(_ sequence: S) { self.contents = [:] - _ = sequence.map{ self.contents[$0] = true } + _ = sequence.map { self.contents[$0] = true } } - #else - var toSortedArray:[Element] {return Array(contents.keys.sort{$0.hashValue < $1.hashValue})} - + var toSortedArray: [Element] { return Array(contents.keys.sort{$0.hashValue < $1.hashValue}) } + init(_ sequence: S) { self.contents = [:] - _ = sequence.map{ self.contents[$0] = true } + _ = sequence.map { self.contents[$0] = true } } #endif - - mutating func put(item:Element){ + + mutating func put(item: Element) { contents[item] = true - } - - mutating func delete(item:Element){ + + mutating func delete(item: Element) { contents[item] = nil - } - - mutating func removeAll(){ + + mutating func removeAll() { contents = [:] - } - - func intersection(item:CustomSet)-> CustomSet{ + + func intersection(item: CustomSet) -> CustomSet { var temp = [Element: Bool]() for each in Array(item.contents.keys){ if (contents[each] != nil) { temp[each] = true } } return CustomSet(temp.keys) } - - - func difference(item:CustomSet)-> CustomSet{ + + func difference(item: CustomSet) -> CustomSet { var temp = contents for each in Array(item.contents.keys){ temp[each] = nil } return CustomSet(temp.keys) } - - func union(item:CustomSet)-> CustomSet{ + + func union(item: CustomSet) -> CustomSet { var temp = contents - for each in Array(item.contents.keys){ + for each in Array(item.contents.keys) { temp[each] = true } return CustomSet(temp.keys) } - - - func isSupersetOf (item:CustomSet)-> Bool{ - + + func isSupersetOf(item: CustomSet) -> Bool { return item.contents.count == item.contents.filter{self.contents.keys.contains($0.0)}.count - } - func isDisjoint(item:CustomSet)-> Bool{ - - for each in Array(item.contents.keys){ - if contents.keys.contains(each){ + + func isDisjoint(item: CustomSet) -> Bool { + for each in Array(item.contents.keys) { + if contents.keys.contains(each) { return false } } return true } - - func containsMember(item:Element)-> Bool{ + + func containsMember(item: Element) -> Bool { if contents[item] != nil { return true} return false } - - - - } - diff --git a/exercises/custom-set/CustomSetTest.swift b/exercises/custom-set/CustomSetTest.swift index ca09b05bc..83ddea110 100644 --- a/exercises/custom-set/CustomSetTest.swift +++ b/exercises/custom-set/CustomSetTest.swift @@ -1,91 +1,85 @@ - import XCTest - - class CustomSetTest: XCTestCase { - let emptyTypedArray = [Int]() - + func testEqual(){ XCTAssertEqual(CustomSet([1, 3]), CustomSet([3, 1])) XCTAssertNotEqual(CustomSet([1, 3]), CustomSet([3, 1, 5])) XCTAssertNotEqual(CustomSet([1, 3, 5]), CustomSet([3, 1])) XCTAssertNotEqual(CustomSet([1, 3]), CustomSet([2, 1])) } - + func testNoDuplicates(){ XCTAssertEqual(CustomSet([1, 1]), CustomSet([1])) } - + func testDeleteMethod(){ - var expected1 = CustomSet([3, 2, 1]) expected1.delete(2) XCTAssertEqual(CustomSet([1, 3]), expected1) - + var expected2 = CustomSet([3, 2, 1]) expected2.delete(4) XCTAssertEqual(CustomSet([1, 2, 3]), expected2) } - + func testDifference(){ XCTAssertEqual(CustomSet([1, 3]), - CustomSet([1, 2, 3]).difference(CustomSet([2, 4]))) + CustomSet([1, 2, 3]).difference(CustomSet([2, 4]))) XCTAssertEqual(CustomSet([2, 3]), - CustomSet([1, 2, 3, 4]).difference(CustomSet([1, 4]))) - + CustomSet([1, 2, 3, 4]).difference(CustomSet([1, 4]))) + } - + func testDisjoint(){ XCTAssertTrue(CustomSet([1, 2]).isDisjoint(CustomSet([3, 4]))) XCTAssertFalse(CustomSet([1, 2]).isDisjoint(CustomSet([2, 3]))) XCTAssertFalse(CustomSet([1.0, 2.0]).isDisjoint(CustomSet([2.0, 3.0]))) } - + func testEmptyMethod(){ var expected1 = CustomSet([1, 2]) expected1.removeAll() XCTAssertEqual(CustomSet(emptyTypedArray ), expected1 ) - + var expected2 = CustomSet(emptyTypedArray ) expected2.removeAll() XCTAssertEqual(CustomSet(emptyTypedArray ), expected2 ) } - - + func testIntersection(){ XCTAssertEqual(CustomSet(["a", "c"]), - CustomSet(["a", "b", "c"]).intersection(CustomSet(["a", "c", "d"]))) - + CustomSet(["a", "b", "c"]).intersection(CustomSet(["a", "c", "d"]))) + XCTAssertEqual(CustomSet([3.0]), - CustomSet([1.0, 2.0, 3.0]).intersection(CustomSet([3.0]))) + CustomSet([1.0, 2.0, 3.0]).intersection(CustomSet([3.0]))) } - + func testMember(){ XCTAssertTrue(CustomSet([1, 2, 3]).containsMember(2)) XCTAssertTrue(CustomSet([1, 2, 3]).containsMember(3)) XCTAssertFalse(CustomSet([1, 2, 3]).containsMember(4)) } - + func testPutMethod(){ var expected1 = CustomSet([1, 2, 4]) expected1.put(3) XCTAssertEqual(CustomSet([1, 2, 3, 4]), - expected1) - + expected1) + var expected2 = CustomSet([1, 2, 3]) expected2.put(3) XCTAssertEqual(CustomSet([1, 2, 3]), - expected2) + expected2) } - + func testSize(){ XCTAssertEqual(0, CustomSet(emptyTypedArray).size) XCTAssertEqual(3, CustomSet([1, 2, 3]).size) XCTAssertEqual(3, CustomSet([1, 2, 3, 2]).size) } - + func testSubsetMethod(){ XCTAssertTrue(CustomSet([1, 2, 3]).isSupersetOf(CustomSet([1, 2, 3]))) XCTAssertTrue(CustomSet([4, 1, 2, 3]).isSupersetOf(CustomSet([1, 2, 3]))) @@ -94,24 +88,22 @@ class CustomSetTest: XCTestCase { XCTAssertTrue(CustomSet([4, 1, 3]).isSupersetOf(CustomSet(emptyTypedArray))) XCTAssertTrue(CustomSet(emptyTypedArray).isSupersetOf(CustomSet(emptyTypedArray))) } - + func testToA(){ XCTAssertEqual([1, 2, 3], CustomSet([3, 1, 2]).toSortedArray) XCTAssertEqual([1, 2, 3], CustomSet([3, 1, 2, 1]).toSortedArray) } - + func testUnion(){ XCTAssertEqual(CustomSet([3, 2, 1]), - CustomSet([1, 3]).union(CustomSet([2]))) + CustomSet([1, 3]).union(CustomSet([2]))) XCTAssertEqual(CustomSet([3.0, 3, 2, 1]), - CustomSet([1, 3]).union(CustomSet([2, 3.0]))) + CustomSet([1, 3]).union(CustomSet([2, 3.0]))) XCTAssertEqual(CustomSet([3, 1]), - CustomSet([1, 3]).union(CustomSet(emptyTypedArray))) + CustomSet([1, 3]).union(CustomSet(emptyTypedArray))) XCTAssertEqual(CustomSet([2]), - CustomSet([2]).union(CustomSet(emptyTypedArray))) + CustomSet([2]).union(CustomSet(emptyTypedArray))) XCTAssertEqual(CustomSet(emptyTypedArray), - CustomSet(emptyTypedArray).union(CustomSet(emptyTypedArray))) + CustomSet(emptyTypedArray).union(CustomSet(emptyTypedArray))) } - - } diff --git a/exercises/difference-of-squares/DifferenceOfSquaresExample.swift b/exercises/difference-of-squares/DifferenceOfSquaresExample.swift index 27b100859..44be463f7 100644 --- a/exercises/difference-of-squares/DifferenceOfSquaresExample.swift +++ b/exercises/difference-of-squares/DifferenceOfSquaresExample.swift @@ -1,29 +1,26 @@ // Foundation not needed - - struct Squares { - var max = 1 - - init (_ max:Int){ + + init (_ max: Int) { if max > 0{ self.max = max } } - - var squareOfSums:Int{ + + var squareOfSums: Int { let numbers = Array(1...self.max) let sum = numbers.reduce(0, combine: + ) return sum * sum; } - - var sumOfSquares:Int{ + + var sumOfSquares: Int { let numbers = Array(1...self.max) return numbers.map{ return $0*$0 }.reduce(0, combine: + ) } - - var differenceOfSquares:Int{ + + var differenceOfSquares: Int { return squareOfSums - sumOfSquares } -} \ No newline at end of file +} diff --git a/exercises/difference-of-squares/DifferenceOfSquaresTests.swift b/exercises/difference-of-squares/DifferenceOfSquaresTests.swift index 8b20e0e00..cd10c96d4 100644 --- a/exercises/difference-of-squares/DifferenceOfSquaresTests.swift +++ b/exercises/difference-of-squares/DifferenceOfSquaresTests.swift @@ -1,44 +1,39 @@ - import XCTest - - class DifferenceOfSquaresTests: XCTestCase { - func testSquareOfSumsTo5() { XCTAssertEqual(225, Squares(5).squareOfSums) } - + func testSumOfSquaresTo5() { XCTAssertEqual(55, Squares(5).sumOfSquares) } - + func testDifferenceOfSquaresOfSumsTo5() { XCTAssertEqual(170, Squares(5).differenceOfSquares) } - + func testSquareOfSumsTo10() { XCTAssertEqual(3025, Squares(10).squareOfSums) } - + func testSumOfSquaresTo10() { XCTAssertEqual(385, Squares(10).sumOfSquares) } - + func testDifferenceOfSquaresOfSumsTo10() { XCTAssertEqual(2640, Squares(10).differenceOfSquares) } - + func testSquareOfSumsTo100() { XCTAssertEqual(25_502_500, Squares(100).squareOfSums) } - + func testSumOfSquaresTo100() { XCTAssertEqual(338_350, Squares(100).sumOfSquares) } - + func testDifferenceOfSquaresOfSumsTo100() { XCTAssertEqual(25_164_150, Squares(100).differenceOfSquares) } - -} \ No newline at end of file +} diff --git a/exercises/dominoes/DominoesExample.swift b/exercises/dominoes/DominoesExample.swift index 4d3f5925b..43609c2f4 100644 --- a/exercises/dominoes/DominoesExample.swift +++ b/exercises/dominoes/DominoesExample.swift @@ -1,11 +1,8 @@ - - -struct Dominoes{ - +struct Dominoes { let singles:[Bone] let doubles:[Bone] - - var chained:Bool { + + var chained: Bool { if singles.isEmpty && doubles.count == 1 {return true } let (success,result) = chainning(swapDuplicate(singles)) if doubles.isEmpty { @@ -16,31 +13,30 @@ struct Dominoes{ return false } } - - private func swapDuplicate(input:[Bone])->[Bone]{ + + private func swapDuplicate(input: [Bone]) -> [Bone] { var unique = [Bone]() for each in input{ - if unique.contains(each){ - + if unique.contains(each) { #if swift(>=3.0) unique.insert(Bone(each.value.tail,each.value.head), at: 0) #else unique.insert(Bone(each.value.tail,each.value.head), atIndex: 0) #endif - }else{ + } else { unique.append(each) } } return unique } - - private func chainning(input:[Bone])->(Bool,[Bone]){ + + private func chainning(input: [Bone]) -> (Bool, [Bone]) { var matched = input - - guard !matched.isEmpty else {return (false,[])} - + + guard !matched.isEmpty else { return (false,[]) } + let total = matched.count - 1 - + for index in 0...total { for innerIndex in 0...total{ matched[index].connect(matched[innerIndex]) @@ -49,12 +45,12 @@ struct Dominoes{ return (matched.filter({$0.connected >= 2}).count == matched.count) ? (true, matched) : (false,[]) } - + init(_ input: [(Int,Int)]) { var singles = [Bone]() var doubles = [Bone]() - - for each in input{ + + for each in input { if each.0 == each.1 { doubles.append(Bone(each.0,each.1)) } else { @@ -66,96 +62,87 @@ struct Dominoes{ } } - func ==(lhs: Bone, rhs: Bone) -> Bool { return lhs.value.head == rhs.value.head && lhs.value.tail == rhs.value.tail } - -class Bone:CustomStringConvertible,Equatable{ - - let value:(head:Int,tail:Int) - var connected:Int = 0 - var available:Int? - var connectedTo:Bone? - var description:String{ +class Bone: CustomStringConvertible, Equatable { + let value: (head: Int, tail: Int) + var connected: Int = 0 + var available: Int? + var connectedTo: Bone? + var description: String{ return "\(value)|\(connected)|\(available) " } - - func connect(input:Bone)->Bool{ - - if self === input {return false} - if self === input.connectedTo {return false} - + + func connect(input: Bone) -> Bool { + if self === input { return false } + if self === input.connectedTo { return false } + var toReturn = false - + if connected == 1 && input.connected == 0 { - guard let available = available else { return false } - - if available == input.value.head{ + + if available == input.value.head { self.available = nil input.available = input.value.tail toReturn = true } - - if available == input.value.tail{ + + if available == input.value.tail { self.available = nil input.available = input.value.head toReturn = true } } - + if connected == 0 && input.connected == 1 { - guard let available = input.available else { return false } - - if available == value.head{ + + if available == value.head { input.available = nil self.available = value.tail toReturn = true } - - if available == value.tail{ + + if available == value.tail { input.available = nil self.available = value.head toReturn = true } - } - + if connected == 1 && input.connected == 1 { - if available == input.available { self.available = nil input.available = nil toReturn = true } } - + if connected == 0 && input.connected == 0 { - if value.head == input.value.head { available = value.tail input.available = input.value.tail connectedTo = input toReturn = true } - + if value.tail == input.value.tail { available = value.head input.available = input.value.head connectedTo = input toReturn = true } - + if value.head == input.value.tail { available = value.tail input.available = input.value.head connectedTo = input toReturn = true } - + if value.tail == input.value.head { available = value.head input.available = input.value.tail @@ -163,7 +150,7 @@ class Bone:CustomStringConvertible,Equatable{ toReturn = true } } - + if toReturn == true { connected += 1 input.connected += 1 @@ -172,10 +159,9 @@ class Bone:CustomStringConvertible,Equatable{ return false } } - - init(_ head:Int, _ tail:Int){ + + init(_ head: Int, _ tail: Int) { self.value.head = head self.value.tail = tail } - -} \ No newline at end of file +} diff --git a/exercises/dominoes/DominoesTest.swift b/exercises/dominoes/DominoesTest.swift index fcf57e38b..d4aa0b51d 100644 --- a/exercises/dominoes/DominoesTest.swift +++ b/exercises/dominoes/DominoesTest.swift @@ -1,17 +1,16 @@ import XCTest class DominoesTest: XCTestCase { - func testEmptyInputEmptyOutput() { let input = [(Int, Int)]() XCTAssertFalse(Dominoes(input).chained) } - + func testSingletonInputSingletonOutput() { let input = [(1, 1)] XCTAssertTrue(Dominoes(input).chained) } - + func testSingletonThatCantBeChained() { let input = [(1, 2)] XCTAssertFalse(Dominoes(input).chained) @@ -21,45 +20,44 @@ class DominoesTest: XCTestCase { let input = [(1, 2), (3, 1), (2, 3)] XCTAssertTrue(Dominoes(input).chained) } - + func testCanReverseDominoes() { let input = [(1, 2), (1, 3), (2, 3)] XCTAssertTrue(Dominoes(input).chained) } - + func testInvalidInput() { let input = [(1, 2), (4, 1), (2, 3)] XCTAssertFalse(Dominoes(input).chained) } - + func testDisconnectedSimple() { let input = [(1, 1), (2, 2)] XCTAssertFalse(Dominoes(input).chained) } - + func testDisconnectedDoubleLoop() { let input = [(1, 2), (2, 1), (3, 4), (4, 3)] XCTAssertFalse(Dominoes(input).chained) } - + func testDisconnectedSingleIsolated() { let input = [(1, 2), (2, 3), (3, 1), (4, 4)] XCTAssertFalse(Dominoes(input).chained) } - + func testNeedBacktrack() { let input = [(1, 2), (2, 3), (3, 1), (2, 4), (2, 4)] XCTAssertTrue(Dominoes(input).chained) } - + func testSeparateLoops() { let input = [(1, 2), (2, 3), (3, 1), (1, 1), (2, 2), (3, 3)] XCTAssertTrue(Dominoes(input).chained) } - + func testTenElements() { let input = [(1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6)] XCTAssertTrue(Dominoes(input).chained) } - } diff --git a/exercises/etl/EtlExample.swift b/exercises/etl/EtlExample.swift index ec805c106..c8c0c0ea9 100644 --- a/exercises/etl/EtlExample.swift +++ b/exercises/etl/EtlExample.swift @@ -1,10 +1,7 @@ // Foundation not needed - - struct ETL { - static func transform(old: [Int: [String] ] ) -> [String: Int] - { + static func transform(old: [Int: [String]]) -> [String: Int] { var result = [String: Int]() for (score, letters) in old { for letter in letters { @@ -13,4 +10,4 @@ struct ETL { } return result } -} \ No newline at end of file +} diff --git a/exercises/etl/EtlTest.swift b/exercises/etl/EtlTest.swift index be2550ee0..eb7e70517 100644 --- a/exercises/etl/EtlTest.swift +++ b/exercises/etl/EtlTest.swift @@ -1,51 +1,48 @@ import XCTest - - class EtlTest: XCTestCase { - func testTransformOneValue() { let old = [ 1 : [ "A" ] ] let expected = ["a" : 1 ] let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } - + func testTransformMoreValues() { let old = [ 1 : [ "A", "E", "I", "O", "U" ] ] let expected = ["a" : 1, "e": 1, "i": 1, "o": 1, "u": 1 ] let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } - + func testMoreKeys() { let old = [ 1 : [ "A", "E" ], 2: ["D", "G"] ] let expected = ["a" : 1, "e": 1, "d": 2, "g": 2 ] let results = ETL.transform(old) - + XCTAssertEqual(results, expected) } - + func testFullDataSet() { let old = [ 1 : [ "A", "E", "I", "O", "U", "L", "N", "R", "S", "T" ], - 2 : [ "D", "G" ], - 3 : [ "B", "C", "M", "P" ], - 4 : [ "F", "H", "V", "W", "Y" ], - 5 : [ "K"], - 8 : [ "J", "X" ], - 10 : [ "Q", "Z" ] + 2 : [ "D", "G" ], + 3 : [ "B", "C", "M", "P" ], + 4 : [ "F", "H", "V", "W", "Y" ], + 5 : [ "K"], + 8 : [ "J", "X" ], + 10 : [ "Q", "Z" ] ] let expected = [ "a" : 1, "b" : 3, "c" : 3, "d" : 2, "e" : 1, - "f" : 4, "g" : 2, "h" : 4, "i" : 1, "j" : 8, - "k" : 5, "l" : 1, "m" : 3, "n" : 1, "o" : 1, - "p" : 3, "q" : 10, "r" : 1, "s" : 1, "t" : 1, - "u" : 1, "v" : 4, "w" : 4, "x" : 8, "y" : 4, - "z" : 10 ] + "f" : 4, "g" : 2, "h" : 4, "i" : 1, "j" : 8, + "k" : 5, "l" : 1, "m" : 3, "n" : 1, "o" : 1, + "p" : 3, "q" : 10, "r" : 1, "s" : 1, "t" : 1, + "u" : 1, "v" : 4, "w" : 4, "x" : 8, "y" : 4, + "z" : 10 ] let results = ETL.transform(old) XCTAssertEqual(results, expected) } -} \ No newline at end of file +} diff --git a/exercises/food-chain/FoodChainExample.swift b/exercises/food-chain/FoodChainExample.swift index c37081b10..3e935c7f8 100644 --- a/exercises/food-chain/FoodChainExample.swift +++ b/exercises/food-chain/FoodChainExample.swift @@ -1,27 +1,24 @@ // Foundation not needed - - struct FoodChain { - private static let animals = ["fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"] - + static func song() -> String { let verses = (1...8).map { verse($0) } #if swift(>=3.0) - return verses.joined(separator: "\n\n") + return verses.joined(separator: "\n\n") #else - return verses.joinWithSeparator("\n\n") + return verses.joinWithSeparator("\n\n") #endif } - + static func verse(number: Int) -> String { var result = "" - + var index = number - 1 let animal = animals[index] result += "I know an old lady who swallowed a \(animal).\n" - + switch number { case 2: result += "It wriggled and jiggled and tickled inside her.\n" case 3: result += "How absurd to swallow a bird!\n" @@ -32,7 +29,7 @@ struct FoodChain { case 8: result += "She's dead, of course!"; return result default: break } - + while index >= 1 { result += "She swallowed the \(animals[index]) to catch the \(animals[index - 1])" if index == 2 { @@ -42,8 +39,7 @@ struct FoodChain { index -= 1 } result += "I don't know why she swallowed the fly. Perhaps she'll die." - + return result } - } diff --git a/exercises/food-chain/FoodChainTest.swift b/exercises/food-chain/FoodChainTest.swift index 7b6a30979..f2681cbe5 100644 --- a/exercises/food-chain/FoodChainTest.swift +++ b/exercises/food-chain/FoodChainTest.swift @@ -1,16 +1,13 @@ import XCTest - - class FoodChainTest: XCTestCase { - func testVerse1() { let expected = "I know an old lady who swallowed a fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(1)) } - + func testVerse2() { let expected = "I know an old lady who swallowed a spider.\n" + @@ -19,7 +16,7 @@ class FoodChainTest: XCTestCase { "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(2)) } - + func testVerse5() { let expected = "I know an old lady who swallowed a dog.\n" + @@ -31,7 +28,7 @@ class FoodChainTest: XCTestCase { "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(5)) } - + func testVerse7() { let expected = "I know an old lady who swallowed a cow.\n" + @@ -45,24 +42,24 @@ class FoodChainTest: XCTestCase { "I don't know why she swallowed the fly. Perhaps she'll die." XCTAssertEqual(expected, FoodChain.verse(7)) } - + func testVerse8() { let expected = "I know an old lady who swallowed a horse.\n" + "She's dead, of course!" XCTAssertEqual(expected, FoodChain.verse(8)) } - + func testWholeSong() { let expected = "I know an old lady who swallowed a fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - + "I know an old lady who swallowed a spider.\n" + "It wriggled and jiggled and tickled inside her.\n" + "She swallowed the spider to catch the fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - + "I know an old lady who swallowed a bird.\n" + "How absurd to swallow a bird!\n" + "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + @@ -75,7 +72,7 @@ class FoodChainTest: XCTestCase { "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + "She swallowed the spider to catch the fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - + "I know an old lady who swallowed a dog.\n" + "What a hog, to swallow a dog!\n" + "She swallowed the dog to catch the cat.\n" + @@ -83,7 +80,7 @@ class FoodChainTest: XCTestCase { "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + "She swallowed the spider to catch the fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - + "I know an old lady who swallowed a goat.\n" + "Just opened her throat and swallowed a goat!\n" + "She swallowed the goat to catch the dog.\n" + @@ -92,7 +89,7 @@ class FoodChainTest: XCTestCase { "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + "She swallowed the spider to catch the fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - + "I know an old lady who swallowed a cow.\n" + "I don't know how she swallowed a cow!\n" + "She swallowed the cow to catch the goat.\n" + @@ -102,11 +99,10 @@ class FoodChainTest: XCTestCase { "She swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.\n" + "She swallowed the spider to catch the fly.\n" + "I don't know why she swallowed the fly. Perhaps she'll die.\n\n" + - + "I know an old lady who swallowed a horse.\n" + "She's dead, of course!" XCTAssertEqual(expected, FoodChain.song()) } - } diff --git a/exercises/gigasecond/GigasecondExample.swift b/exercises/gigasecond/GigasecondExample.swift index 72a672371..c10d65f50 100644 --- a/exercises/gigasecond/GigasecondExample.swift +++ b/exercises/gigasecond/GigasecondExample.swift @@ -1,19 +1,16 @@ import Darwin - - -private extension tm{ - +private extension tm { var year:Int32 { return tm_year + 1900 } - + var month:Int32 { return tm_mon + 1 } - + var day:Int32 { return tm_mday } - + var time:(hour:Int32, mins:Int32, secs:Int32){ return (hour: tm_hour, mins: tm_min, secs:tm_sec) } - + init(year:Int32, month:Int32, day:Int32, hour:Int32 = 0, mins:Int32 = 0, secs:Int32 = 0){ self.init() self.tm_year = year - 1900 @@ -22,14 +19,13 @@ private extension tm{ self.tm_hour = hour self.tm_min = mins self.tm_sec = secs - } - + mutating func dateByAddingSeconds(seconds:Int) -> tm { var d1 = timegm(&self) + seconds return gmtime(&d1).memory } - + private func addLeadingZero(input:Int32) -> String{ var addZero = false (0...9).forEach{ @@ -40,31 +36,27 @@ private extension tm{ if addZero { return "0\(input)" } else {return String(input)} - } - + var description:String { - let date = [year, month, day, time.hour, time.mins, time.secs].map{addLeadingZero($0)} - - return date[0] + "-" + date[1] + "-" + date[2] + "T" + date[3] + ":" + date[4] + ":" + date[5] + + return date[0] + "-" + date[1] + "-" + date[2] + "T" + date[3] + ":" + date[4] + ":" + date[5] } } -func == (lhs: Gigasecond, rhs: Gigasecond) -> Bool { +func ==(lhs: Gigasecond, rhs: Gigasecond) -> Bool { return lhs.description == rhs.description } -func == (lhs: String, rhs: Gigasecond) -> Bool { +func ==(lhs: String, rhs: Gigasecond) -> Bool { return lhs == rhs.description } - struct Gigasecond: Equatable, CustomStringConvertible{ - private var startDate:tm! private var gigasecondDate:tm! - + init?(from:String){ if let result = parse(from) { var start = result @@ -74,31 +66,28 @@ struct Gigasecond: Equatable, CustomStringConvertible{ return nil } } - - + private func parse(input:String) -> tm? { - let dateTime = input.characters.split("T").map{String($0)} if dateTime.count > 1 { let date = dateTime[0].characters.split("-").map{String($0)} let time = dateTime[1].characters.split(":").map{String($0)} if date.count == 3 && time.count == date.count { - + let year = Int32(date[0]) ?? 0 let month = Int32(date[1]) ?? 0 let day = Int32(date[2]) ?? 0 let hour = Int32(time[0]) ?? 0 let minute = Int32(time[1]) ?? 0 let second = Int32(time[2]) ?? 0 - + return tm(year: year, month: month, day: day, hour: hour, mins: minute, secs: second) } } return nil } + var description:String { return gigasecondDate.description } - - -} \ No newline at end of file +} diff --git a/exercises/gigasecond/GigasecondTest.swift b/exercises/gigasecond/GigasecondTest.swift index 278715746..93bdf9e3a 100644 --- a/exercises/gigasecond/GigasecondTest.swift +++ b/exercises/gigasecond/GigasecondTest.swift @@ -1,30 +1,23 @@ import XCTest - - - class GigasecondTest: XCTestCase { - - func test1 () { let gs = Gigasecond(from: "2011-04-25T00:00:00")?.description - XCTAssertEqual("2043-01-01T01:46:40", gs) + XCTAssertEqual("2043-01-01T01:46:40", gs) } - + func test2 () { let gs = Gigasecond(from: "1977-06-13T00:00:00")?.description - XCTAssertEqual("2009-02-19T01:46:40", gs) + XCTAssertEqual("2009-02-19T01:46:40", gs) } - + func test3 () { let gs = Gigasecond(from: "1959-07-19T00:00:00")?.description - XCTAssertEqual("1991-03-27T01:46:40", gs) + XCTAssertEqual("1991-03-27T01:46:40", gs) } - + func testTimeWithSeconds () { let gs = Gigasecond(from: "1959-07-19T23:59:59")?.description XCTAssertEqual("1991-03-28T01:46:39", gs) } - - } - +} diff --git a/exercises/grade-school/GradeSchoolExample.swift b/exercises/grade-school/GradeSchoolExample.swift index 7b9ff37bc..7961a033d 100644 --- a/exercises/grade-school/GradeSchoolExample.swift +++ b/exercises/grade-school/GradeSchoolExample.swift @@ -1,11 +1,8 @@ // Foundation not needed - - - struct GradeSchool { var roster = [Int: Set]() - + mutating func addStudent(name: String, grade: Int) { if let students = roster[grade] { var students = students @@ -15,19 +12,19 @@ struct GradeSchool { roster[grade] = Set(arrayLiteral: name) } } - + func studentsInGrade(grade: Int) -> Set { return roster[grade] ?? Set() } - + var sortedRoster: [Int: Set] { var sortedRoster = [Int: Set](minimumCapacity: roster.count) for (grade, students) in roster { - #if swift(>=3.0) - sortedRoster[grade] = Set(students.sorted()) - #else - sortedRoster[grade] = Set(students.sort()) - #endif + #if swift(>=3.0) + sortedRoster[grade] = Set(students.sorted()) + #else + sortedRoster[grade] = Set(students.sort()) + #endif } return sortedRoster } diff --git a/exercises/grade-school/GradeSchoolTest.swift b/exercises/grade-school/GradeSchoolTest.swift index f23c8729d..6343a8109 100644 --- a/exercises/grade-school/GradeSchoolTest.swift +++ b/exercises/grade-school/GradeSchoolTest.swift @@ -1,10 +1,6 @@ import XCTest - - private extension XCTestCase { - - // Workaround unit test liminitaiton on Optional Arrays/Sets #if swift(>=3.0) private func sameCollection(result: C?, _ expected: [String]?) -> Bool { guard let result = result, expected = expected where similar(result, expected) else { return false } @@ -13,39 +9,36 @@ private extension XCTestCase { } return true } - #else // Swift 2.2 and below + #else private func sameCollection(result: C?, _ expected: [String]?) -> Bool { guard let result = result, expected = expected where similar(result, expected) else { return false } for (index, student) in result.enumerate() { guard index < expected.count && expected.contains(student) else { return false } } return true - } + } #endif - + private func similar(result: C, _ expected: [String]) -> Bool { return result.count.toIntMax() == IntMax(expected.count) } - + func XCTAssertEqualCollection (collectionS : Set? , _ collectionA : [String]? ) { XCTAssert(sameCollection(collectionS, collectionA)) } - + func XCTAssertEqualCollection (collectionA1 : [String]?, _ collectionA2 : [String]? ) { XCTAssert(sameCollection(collectionA1, collectionA2)) } } - class GradeSchoolTest: XCTestCase { - func testAnEmptySchool() { let school = GradeSchool() let result = school.roster XCTAssertTrue(result.isEmpty) - } - + func testAddStudent() { var school = GradeSchool() school.addStudent("Aimee", grade: 2) @@ -54,7 +47,7 @@ class GradeSchoolTest: XCTestCase { XCTAssertEqual(Array(result.keys), Array(expected.keys)) XCTAssertEqualCollection(result[2], expected[2]) } - + func testAddMoreStudentsInSameClass() { var school = GradeSchool() school.addStudent("Fred", grade: 2) @@ -65,14 +58,14 @@ class GradeSchoolTest: XCTestCase { XCTAssertEqual(Array(result.keys), Array(expected.keys)) XCTAssertEqualCollection(result[2], expected[2]) } - + func testAddStudentsToDifferentGrades() { var school = GradeSchool() school.addStudent("Chelsea", grade:3) school.addStudent("Logan", grade: 7) let result = school.roster let expected = [3: ["Chelsea"], 7: ["Logan"]] - + #if swift(>=3.0) XCTAssertEqual(Array(result.keys).sorted(isOrderedBefore: >), Array(expected.keys).sorted(isOrderedBefore: >)) #else @@ -80,7 +73,7 @@ class GradeSchoolTest: XCTestCase { #endif XCTAssertEqualCollection(result[3], expected[3]) } - + func testGetStudentsInAGrade() { var school = GradeSchool() school.addStudent("Franklin", grade: 5) @@ -90,15 +83,15 @@ class GradeSchoolTest: XCTestCase { let expected = ["Franklin", "Bradley"] XCTAssertEqualCollection(result, expected) } - + func testGetStudentsInANonExistantGrade() { let school = GradeSchool() let result = school.studentsInGrade(1) - + let expected = [String]() XCTAssertEqualCollection(result, expected) } - + func testSortSchool() { var school = GradeSchool() school.addStudent("Jennifer", grade: 4) @@ -106,11 +99,11 @@ class GradeSchoolTest: XCTestCase { school.addStudent("Christopher", grade: 4) school.addStudent("Kyle", grade: 3) let result = school.sortedRoster - + let expected = [ - 3 : ["Kyle"], - 4 : ["Christopher", "Jennifer"], - 6 : ["Kareem"] + 3 : ["Kyle"], + 4 : ["Christopher", "Jennifer"], + 6 : ["Kareem"] ] #if swift(>=3.0) XCTAssertEqual(Array(result.keys).sorted(isOrderedBefore: >), Array(expected.keys).sorted(isOrderedBefore: >)) @@ -121,5 +114,4 @@ class GradeSchoolTest: XCTestCase { XCTAssertEqualCollection(result[4], expected[4]) XCTAssertEqualCollection(result[6], expected[6]) } - } diff --git a/exercises/grains/GrainsExample.swift b/exercises/grains/GrainsExample.swift index 836626130..1bd3c6e78 100644 --- a/exercises/grains/GrainsExample.swift +++ b/exercises/grains/GrainsExample.swift @@ -1,10 +1,7 @@ import Darwin - - - struct Grains { - + enum Error: ErrorType { case inputTooLow(String) case inputTooHigh(String) @@ -15,20 +12,20 @@ struct Grains { let message = "Input[\(num)] invalid. Input should be between 1 and 64 (inclusive)" throw Error.inputTooLow(message) } - + guard num <= 64 else { let message = "Input[\(num)] invalid. Input should be between 1 and 64 (inclusive)" throw Error.inputTooHigh(message) } - + let one: UInt64 = 1 let shift = UInt64(num - 1) return one << shift } - + static var total:UInt64 { let numbers = (1...64).map { $0 } - + return numbers.reduce(UInt64(0)) { let squared = try! square($1) return $0 + squared diff --git a/exercises/grains/GrainsTest.swift b/exercises/grains/GrainsTest.swift index e32e6c411..60471964b 100644 --- a/exercises/grains/GrainsTest.swift +++ b/exercises/grains/GrainsTest.swift @@ -1,18 +1,13 @@ - import XCTest - - - class GrainsTest: XCTestCase { - func testInvalidInput1() { var throwsInputTooHighError = false - + defer { XCTAssertTrue(throwsInputTooHighError) } - + do { let _ = try Grains.square(65) } catch Grains.Error.inputTooHigh(let message) { @@ -21,16 +16,15 @@ class GrainsTest: XCTestCase { } catch { return } - } - + func testInvalidInput2() { var throwsInputTooLowError = false - + defer { XCTAssertTrue(throwsInputTooLowError) } - + do { let _ = try Grains.square(0) } catch Grains.Error.inputTooLow(let message) { @@ -40,14 +34,14 @@ class GrainsTest: XCTestCase { return } } - + func testInvalidInput3() { var throwsInputTooLowError = false - + defer { XCTAssertTrue(throwsInputTooLowError) } - + do { let _ = try Grains.square(-1) } catch Grains.Error.inputTooLow(let message) { @@ -57,11 +51,11 @@ class GrainsTest: XCTestCase { return } } - + func testSquare1() { XCTAssertEqual(try! Grains.square(1), 1) } - + func testSquare2() { XCTAssertEqual(try! Grains.square(2), 2) } @@ -85,7 +79,7 @@ class GrainsTest: XCTestCase { func testSquare64() { XCTAssertEqual(try! Grains.square(64), 9_223_372_036_854_775_808) } - + func testTotalGrains() { XCTAssertEqual(Grains.total, 18_446_744_073_709_551_615) } diff --git a/exercises/hamming/HammingExample.swift b/exercises/hamming/HammingExample.swift index a488057d8..7b090c677 100644 --- a/exercises/hamming/HammingExample.swift +++ b/exercises/hamming/HammingExample.swift @@ -1,14 +1,12 @@ // Foundation not needed - - struct Hamming { static func compute(input: String, against: String) -> Int? { var differences = 0 - + let char1 = convertStringToArray(input) let char2 = convertStringToArray(against) - + if char1.count != char2.count { return nil } for i in 0.. [Character] { var characterArray: [Character] = [] - + for character in input.characters { characterArray.append(character) } - + return characterArray } diff --git a/exercises/hamming/HammingTest.swift b/exercises/hamming/HammingTest.swift index f576e2ce9..0cdadc82a 100644 --- a/exercises/hamming/HammingTest.swift +++ b/exercises/hamming/HammingTest.swift @@ -1,43 +1,41 @@ import XCTest - - class HammingTests: XCTestCase { func testNoDifferenceBetweenEmptyStrands() { let result = Hamming.compute("", against: "")! let expected = 0 XCTAssertEqual(expected, result) } - + func testNoDifferenceBetweenIdenticalStrands() { let result = Hamming.compute("GGACTGA", against:"GGACTGA")! let expected = 0 XCTAssertEqual(expected,result) } - + func testCompleteHammingDistanceInSmallStrand() { let result = Hamming.compute("ACT", against: "GGA")! let expected = 3 XCTAssertEqual(expected,result) } - + func testSmallHammingDistanceInMiddleSomewhere() { let result = Hamming.compute("GGACG", against:"GGTCG")! let expected = 1 XCTAssertEqual(expected,result) } - + func testLargerDistance() { let result = Hamming.compute("ACCAGGG", against:"ACTATGG")! let expected = 2 XCTAssertEqual(expected,result) } - + func testReturnsNilWhenOtherStrandLonger() { let result = Hamming.compute("AAACTAGGGG", against:"AGGCTAGCGGTAGGAC") XCTAssertNil(result, "Different length strands return nil") } - + func testReturnsNilWhenOriginalStrandLonger() { let result = Hamming.compute("GACTACGGACAGGGTAGGGAAT", against:"GACATCGCACACC") XCTAssertNil(result, "Different length strands return nil") diff --git a/exercises/hexadecimal/HexadecimalExample.swift b/exercises/hexadecimal/HexadecimalExample.swift index 3688ed38c..d96897139 100644 --- a/exercises/hexadecimal/HexadecimalExample.swift +++ b/exercises/hexadecimal/HexadecimalExample.swift @@ -1,12 +1,9 @@ // Foundation not needed - - struct Hexadecimal { - let hexString: String let intValue: Int? - + private static let hexDigits = [ "0" : 0, "1" : 1, @@ -25,40 +22,38 @@ struct Hexadecimal { "e" : 14, "f" : 15 ] - + init(_ hexString: String) { self.hexString = hexString self.intValue = Hexadecimal.getIntFromHexString(hexString) } - + private static func getIntFromHexString(hexString: String) -> Int? { var result = 0 var multiplier = 1 - + let digits = hexString.characters.map { String($0).lowercaseString }.reverse() - + for digit in digits { guard let intValue = hexDigits[digit] else { // Invalid hex string return nil } - + result += intValue * multiplier multiplier *= 16 } - + return result } } extension Int { - init?(_ hex: Hexadecimal) { guard let intValue = hex.intValue else { return nil } - + self = intValue } - -} \ No newline at end of file +} diff --git a/exercises/hexadecimal/HexadecimalTest.swift b/exercises/hexadecimal/HexadecimalTest.swift index a671e0ca4..d9abcc48d 100644 --- a/exercises/hexadecimal/HexadecimalTest.swift +++ b/exercises/hexadecimal/HexadecimalTest.swift @@ -1,47 +1,43 @@ import XCTest - - class HexadecimalTest: XCTestCase { - func testHex1IsDecimal1() { XCTAssertEqual(1, Int(Hexadecimal("1"))) } - + func testHexCIsDecimal12() { XCTAssertEqual(12, Int(Hexadecimal("c"))) } - + func testHex10IsDecimal16() { XCTAssertEqual(16, Int(Hexadecimal("10"))) } - + func testHexAFIsDecimal175() { XCTAssertEqual(175, Int(Hexadecimal("af"))) } - + func testHex100IsDecimal256() { XCTAssertEqual(256, Int(Hexadecimal("100"))) } - + func testHex19aceIsDecimal105166() { XCTAssertEqual(105_166, Int(Hexadecimal("19ace"))) } - + func testInvalidHexIsNil() { XCTAssertNil(Int(Hexadecimal("carrot"))) } - + func testBlack() { XCTAssertEqual(0, Int(Hexadecimal("000000"))) } - + func testWhite() { XCTAssertEqual(16_777_215, Int(Hexadecimal("ffffff"))) } - + func testYellow() { XCTAssertEqual(16_776_960, Int(Hexadecimal("ffff00"))) } - -} \ No newline at end of file +} diff --git a/exercises/house/HouseExample.swift b/exercises/house/HouseExample.swift index 96da211aa..156e7727e 100644 --- a/exercises/house/HouseExample.swift +++ b/exercises/house/HouseExample.swift @@ -1,9 +1,6 @@ // Foundation not needed - - struct House { - private static let pieces = [ ["the horse and the hound and the horn", "that belonged to"], ["the farmer sowing his corn", "that kept"], @@ -18,26 +15,24 @@ struct House { ["the malt", "that lay in"], ["the house that Jack built"] ] - + static func recite() -> String { #if swift(>=3.0) - return (1...pieces.count).map { line($0) }.joined(separator: "\n\n") + return (1...pieces.count).map { line($0) }.joined(separator: "\n\n") #else - return (1...pieces.count).map { line($0) }.joinWithSeparator("\n\n") + return (1...pieces.count).map { line($0) }.joinWithSeparator("\n\n") #endif } - + private static func line(number: Int) -> String { let startIndex = pieces.count - number let endIndex = pieces.count let selectedPieces = pieces[startIndex ..< endIndex] #if swift(>=3.0) - let text = selectedPieces.map { $0.joined(separator: "\n") }.joined(separator: " ") + let text = selectedPieces.map { $0.joined(separator: "\n") }.joined(separator: " ") #else - let text = selectedPieces.map { $0.joinWithSeparator("\n") }.joinWithSeparator(" ") + let text = selectedPieces.map { $0.joinWithSeparator("\n") }.joinWithSeparator(" ") #endif return "This is \(text)." } - } - diff --git a/exercises/house/HouseTest.swift b/exercises/house/HouseTest.swift index 5c1d0b811..452c96eb5 100644 --- a/exercises/house/HouseTest.swift +++ b/exercises/house/HouseTest.swift @@ -1,38 +1,35 @@ import XCTest - - class HouseTest: XCTestCase { - func testRhyme() { let expected = "This is the house that Jack built.\n\n" + - + "This is the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the cat\n" + "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the dog\n" + "that worried the cat\n" + "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the cow with the crumpled horn\n" + "that tossed the dog\n" + "that worried the cat\n" + "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the maiden all forlorn\n" + "that milked the cow with the crumpled horn\n" + "that tossed the dog\n" + @@ -49,7 +46,7 @@ class HouseTest: XCTestCase { "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the priest all shaven and shorn\n" + "that married the man all tattered and torn\n" + "that kissed the maiden all forlorn\n" + @@ -59,7 +56,7 @@ class HouseTest: XCTestCase { "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the rooster that crowed in the morn\n" + "that woke the priest all shaven and shorn\n" + "that married the man all tattered and torn\n" + @@ -70,7 +67,7 @@ class HouseTest: XCTestCase { "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the farmer sowing his corn\n" + "that kept the rooster that crowed in the morn\n" + "that woke the priest all shaven and shorn\n" + @@ -82,7 +79,7 @@ class HouseTest: XCTestCase { "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built.\n\n" + - + "This is the horse and the hound and the horn\n" + "that belonged to the farmer sowing his corn\n" + "that kept the rooster that crowed in the morn\n" + @@ -95,9 +92,7 @@ class HouseTest: XCTestCase { "that killed the rat\n" + "that ate the malt\n" + "that lay in the house that Jack built." - + XCTAssertEqual(expected, House.recite()) } - - } diff --git a/exercises/kindergarten-garden/KindergartenGardenExample.swift b/exercises/kindergarten-garden/KindergartenGardenExample.swift index d9d25aec0..46c9b083d 100644 --- a/exercises/kindergarten-garden/KindergartenGardenExample.swift +++ b/exercises/kindergarten-garden/KindergartenGardenExample.swift @@ -1,7 +1,5 @@ import Foundation - - enum Plant: String { case Grass = "G" case Clover = "C" @@ -11,20 +9,20 @@ enum Plant: String { struct Garden { static private let defaultChildren = ["Alice", "Bob", "Charlie", "David", "Eve", "Fred", "Ginny", "Harriet", "Ileana", "Joseph", "Kincaid", "Larry"] - + private let pots: [String : [Plant]] - + init(_ diagram: String, children: [String] = defaultChildren) { self.pots = Garden.parse(diagram, children: children) } - + func plantsForChild(child: String) -> [Plant] { guard let plants = pots[child] else { return [] } return plants } - + private static func parse(diagram: String, children: [String]) -> [String : [Plant]] { #if swift(>=3.0) let sortedChildren = children.sorted(isOrderedBefore: <) @@ -33,32 +31,32 @@ struct Garden { let sortedChildren = children.sort(<) let lines = diagram.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) #endif - + var result = [String : [Plant]]() var line1 = lines[0].characters.map { String($0) } var line2 = lines[1].characters.map { String($0) } - + var index = 0 - + for child in sortedChildren { guard index < line1.count else { break } - + var pots = [Plant]() - + if let plant1 = Plant(rawValue: line1[index]), plant2 = Plant(rawValue: line1[index + 1]), plant3 = Plant(rawValue: line2[index]), plant4 = Plant(rawValue: line2[index + 1]) { pots = [plant1, plant2, plant3, plant4] } - + result[child] = pots - + index += 2 } - + return result } -} \ No newline at end of file +} diff --git a/exercises/kindergarten-garden/KindergartenGardenTest.swift b/exercises/kindergarten-garden/KindergartenGardenTest.swift index 5e370f6bc..7cf1a94cf 100644 --- a/exercises/kindergarten-garden/KindergartenGardenTest.swift +++ b/exercises/kindergarten-garden/KindergartenGardenTest.swift @@ -1,104 +1,101 @@ import XCTest - - class KindergartenGardenTest: XCTestCase { - private let fullGarden = Garden("VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV") private let disorderedGarden = Garden("VCRRGVRG\nRVGCCGCV", children: ["Samantha", "Patricia", "Xander", "Roger"]) private static let diagram = "VCRRGVRG\nRVGCCGCV" private let garden1 = Garden(diagram, children: ["Alice", "Bob", "Charlie", "Dan"]) private let garden2 = Garden(diagram, children: ["Bob", "Charlie", "Dan", "Erin"]) - + func testAlicesGarden() { let garden = Garden("RC\nGG") XCTAssertEqual([.Radishes, .Clover, .Grass, .Grass], garden.plantsForChild("Alice")) } - + func testDifferentGardenForAlice() { let garden = Garden("VC\nRC") XCTAssertEqual([.Violets, .Clover, .Radishes, .Clover], garden.plantsForChild("Alice")) } - + func testBobsGarden() { let garden = Garden("VVCG\nVVRC") XCTAssertEqual([.Clover, .Grass, .Radishes, .Clover], garden.plantsForChild("Bob")) } - + func testBobAndCharliesGardens() { let garden = Garden("VVCCGG\nVVCCGG") XCTAssertEqual([.Clover, .Clover, .Clover, .Clover], garden.plantsForChild("Bob")) XCTAssertEqual([.Grass, .Grass, .Grass, .Grass], garden.plantsForChild("Charlie")) } - + // MARK: - Test full garden - + func testAlice() { XCTAssertEqual([.Violets, .Radishes, .Violets, .Radishes], fullGarden.plantsForChild("Alice")) } - + func testBob() { XCTAssertEqual([.Clover, .Grass, .Clover, .Clover], fullGarden.plantsForChild("Bob")) } - + func testCharlie() { XCTAssertEqual([.Violets, .Violets, .Clover, .Grass], fullGarden.plantsForChild("Charlie")) } - + func testDavid() { XCTAssertEqual([.Radishes, .Violets, .Clover, .Radishes], fullGarden.plantsForChild("David")) } - + func testEve() { XCTAssertEqual([.Clover, .Grass, .Radishes, .Grass], fullGarden.plantsForChild("Eve")) } - + func testFred() { XCTAssertEqual([.Grass, .Clover, .Violets, .Clover], fullGarden.plantsForChild("Fred")) } - + func testGinny() { XCTAssertEqual([.Clover, .Grass, .Grass, .Clover], fullGarden.plantsForChild("Ginny")) } - + func testHarriet() { XCTAssertEqual([.Violets, .Radishes, .Radishes, .Violets], fullGarden.plantsForChild("Harriet")) } - + func testIleana() { XCTAssertEqual([.Grass, .Clover, .Violets, .Clover], fullGarden.plantsForChild("Ileana")) } - + func testJoseph() { XCTAssertEqual([.Violets, .Clover, .Violets, .Grass], fullGarden.plantsForChild("Joseph")) } - + func testKincaid() { XCTAssertEqual([.Grass, .Clover, .Clover, .Grass], fullGarden.plantsForChild("Kincaid")) } - + func testLarry() { XCTAssertEqual([.Grass, .Violets, .Clover, .Violets], fullGarden.plantsForChild("Larry")) } - + // MARK: - Test disordered garden - + func testPatricia() { XCTAssertEqual([.Violets, .Clover, .Radishes, .Violets], disorderedGarden.plantsForChild("Patricia")) } - + func testRoger() { XCTAssertEqual([.Radishes, .Radishes, .Grass, .Clover], disorderedGarden.plantsForChild("Roger")) } - + func testSamantha() { XCTAssertEqual([.Grass, .Violets, .Clover, .Grass], disorderedGarden.plantsForChild("Samantha")) } - + func testXander() { XCTAssertEqual([.Radishes, .Grass, .Clover, .Violets], disorderedGarden.plantsForChild("Xander")) } - + // MARK: - Test two gardens, different students func testBobAndCharliePerGarden() { @@ -107,5 +104,4 @@ class KindergartenGardenTest: XCTestCase { XCTAssertEqual([.Grass, .Violets, .Clover, .Grass], garden1.plantsForChild("Charlie")) XCTAssertEqual([.Radishes, .Radishes, .Grass, .Clover], garden2.plantsForChild("Charlie")) } - } diff --git a/exercises/largest-series-product/LargestSeriesProductExample.swift b/exercises/largest-series-product/LargestSeriesProductExample.swift index 6d263330f..e6f89b2af 100644 --- a/exercises/largest-series-product/LargestSeriesProductExample.swift +++ b/exercises/largest-series-product/LargestSeriesProductExample.swift @@ -1,15 +1,14 @@ // Foundation not needed struct NumberSeries { - enum Error: ErrorType { case InvalidCharacter case SpanLongerThanStringLength case NegativeSpan } - + let numbers: [Int] - + init(_ numberString: String) throws { self.numbers = try numberString.characters.map { guard let intValue = Int(String($0)) else { @@ -18,34 +17,33 @@ struct NumberSeries { return intValue } } - + func largestProduct(numberOfDigits: Int) throws -> Int { guard numberOfDigits >= 0 else { throw Error.NegativeSpan } - + let endIndex = numbers.count - numberOfDigits guard endIndex >= 0 else { throw Error.SpanLongerThanStringLength } - + var result = 0 - + for startIndex in 0 ... endIndex { let selectedNumbers = numbers[startIndex ..< startIndex + numberOfDigits] - + var total = 1 - + for selectedNumber in selectedNumbers { total *= selectedNumber } - + if total > result { result = total } } - + return result } - } diff --git a/exercises/largest-series-product/LargestSeriesProductTest.swift b/exercises/largest-series-product/LargestSeriesProductTest.swift index f16e08ffd..361f1f26d 100644 --- a/exercises/largest-series-product/LargestSeriesProductTest.swift +++ b/exercises/largest-series-product/LargestSeriesProductTest.swift @@ -1,60 +1,57 @@ import XCTest - - class LargestSeriesProductTest: XCTestCase { - func testCanFindTheLargestProductOf2WithNumbersInOrder() { XCTAssertEqual(72, try? NumberSeries("0123456789").largestProduct(2)) } - + func testCanFindTheLargestProductOf2() { XCTAssertEqual(48, try? NumberSeries("576802143").largestProduct(2)) } - + func testFindsTheLargestProductIfSpanEqualsLength() { XCTAssertEqual(18, try? NumberSeries("29").largestProduct(2)) } - + func testCanFindTheLargestProductOf3WithNumbersInOrder() { XCTAssertEqual(504, try? NumberSeries("0123456789").largestProduct(3)) } - + func testCanFindTheLargestProductOf3() { XCTAssertEqual(270, try? NumberSeries("1027839564").largestProduct(3)) } - + func testCanFindTheLargestProductOf5WithNumbersInOrder() { XCTAssertEqual(15120, try? NumberSeries("0123456789").largestProduct(5)) } - + func testCanGetTheLargestProductOfABigNumber() { XCTAssertEqual(23520, try? NumberSeries("73167176531330624919225119674426574742355349194934").largestProduct(6)) } - + func testCanGetTheLargestProductOfAnotherBigNumber() { XCTAssertEqual(28350, try? NumberSeries("52677741234314237566414902593461595376319419139427").largestProduct(6)) } - + func testCanGetTheLargestProductOfABigNumberProjectEuler() { XCTAssertEqual(23514624000, try? NumberSeries("7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450").largestProduct(13)) } - + func testReportsZeroIfTheOnlyDigitsAreZero() { XCTAssertEqual(0, try? NumberSeries("0000").largestProduct(2)) } - + func testReportsZeroIfAllSpansIncludeZero() { XCTAssertEqual(0, try? NumberSeries("99099").largestProduct(3)) } - + func testRejectsSpanLongerThanStringLength() { var throwsSpanLongerThanStringLengthError = false - + defer { XCTAssertTrue(throwsSpanLongerThanStringLengthError) } - + do { let _ = try NumberSeries("123").largestProduct(4) } catch NumberSeries.Error.SpanLongerThanStringLength { @@ -63,22 +60,22 @@ class LargestSeriesProductTest: XCTestCase { return } } - + func testReports1ForEmptyStringAndEmptyProduct0Span() { XCTAssertEqual(1, try? NumberSeries("").largestProduct(0)) } - + func testReports1ForNonemptyStringAndEmptyProduct0Span() { XCTAssertEqual(1, try? NumberSeries("123").largestProduct(0)) } - + func testRejectsEmptyStringAndNonzeroSpan() { var throwsSpanLongerThanStringLengthError = false - + defer { XCTAssertTrue(throwsSpanLongerThanStringLengthError) } - + do { let _ = try NumberSeries("").largestProduct(1) } catch NumberSeries.Error.SpanLongerThanStringLength { @@ -87,14 +84,14 @@ class LargestSeriesProductTest: XCTestCase { return } } - + func testRejectsInvalidCharacterInDigits() { var throwsInvalidCharacterError = false - + defer { XCTAssertTrue(throwsInvalidCharacterError) } - + do { let _ = try NumberSeries("1234a5").largestProduct(2) } catch NumberSeries.Error.InvalidCharacter { @@ -103,14 +100,14 @@ class LargestSeriesProductTest: XCTestCase { return } } - + func testRejectsNegativeSpan() { var throwsNegativeSpanError = false - + defer { XCTAssertTrue(throwsNegativeSpanError) } - + do { let _ = try NumberSeries("12345").largestProduct(-1) } catch NumberSeries.Error.NegativeSpan { @@ -119,5 +116,4 @@ class LargestSeriesProductTest: XCTestCase { return } } - } diff --git a/exercises/leap/LeapExample.swift b/exercises/leap/LeapExample.swift index 41764fa65..85e27345d 100644 --- a/exercises/leap/LeapExample.swift +++ b/exercises/leap/LeapExample.swift @@ -1,15 +1,15 @@ // Foundation not needed - - struct Year { var year = 1900 + init(calendarYear: Int) { year = calendarYear } + var isLeapYear: Bool { - get { - return (year%4 == 0 && year%100 != 0 ) || year%400 == 0 - } + get { + return (year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 + } } -} \ No newline at end of file +} diff --git a/exercises/leap/LeapTest.swift b/exercises/leap/LeapTest.swift index b4a6bc03b..bd88e40d8 100644 --- a/exercises/leap/LeapTest.swift +++ b/exercises/leap/LeapTest.swift @@ -1,27 +1,23 @@ import XCTest - - class LeapTest : XCTestCase { - - func testVanillaLeapYear() { - let year = Year(calendarYear: 1996) - XCTAssertTrue(year.isLeapYear) - } - - func testAnyOldYear() { - let year = Year(calendarYear: 1997) - XCTAssertFalse(year.isLeapYear) - } - - func testCentury() { - let year = Year(calendarYear: 1900) - XCTAssertFalse(year.isLeapYear) - } - - func testExceptionalCentury() { - let year = Year(calendarYear: 2400) - XCTAssertTrue(year.isLeapYear) - } - -} \ No newline at end of file + func testVanillaLeapYear() { + let year = Year(calendarYear: 1996) + XCTAssertTrue(year.isLeapYear) + } + + func testAnyOldYear() { + let year = Year(calendarYear: 1997) + XCTAssertFalse(year.isLeapYear) + } + + func testCentury() { + let year = Year(calendarYear: 1900) + XCTAssertFalse(year.isLeapYear) + } + + func testExceptionalCentury() { + let year = Year(calendarYear: 2400) + XCTAssertTrue(year.isLeapYear) + } +} diff --git a/exercises/linked-list/LinkedListExample.swift b/exercises/linked-list/LinkedListExample.swift index 7c650a615..82494b2cc 100644 --- a/exercises/linked-list/LinkedListExample.swift +++ b/exercises/linked-list/LinkedListExample.swift @@ -1,36 +1,32 @@ // Foundation not needed - - class Node { var value: T? = nil var next: Node? = nil var prev: Node? = nil - + init() { } - + init(value: T) { self.value = value } - } class Deque { var count: Int = 0 var head: Node var tail: Node - + init() { self.head = Node() self.tail = head - } - + func isEmpty() -> Bool { return self.count == 0 } - + func push(value: T) { let node = Node(value: value) if self.isEmpty() { @@ -43,7 +39,7 @@ class Deque { } self.count += 1 } - + func unshift(value: T) { let node = Node(value: value) if self.isEmpty() { @@ -56,10 +52,7 @@ class Deque { } self.count += 1 } - - - - + func pop() -> T? { if self.isEmpty() { return nil @@ -74,8 +67,7 @@ class Deque { return temp.value } } - - + func shift() -> T? { if self.isEmpty() { return nil @@ -91,4 +83,3 @@ class Deque { } } } - diff --git a/exercises/linked-list/LinkedListTest.swift b/exercises/linked-list/LinkedListTest.swift index d28f17020..c24c0264d 100644 --- a/exercises/linked-list/LinkedListTest.swift +++ b/exercises/linked-list/LinkedListTest.swift @@ -1,12 +1,7 @@ - -import XCTest - - - // Use Optionals and Generic Classes +import XCTest class LinkedListTest: XCTestCase { - func testPushPop() { let deque = Deque() deque.push(10) @@ -14,7 +9,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(20, deque.pop() ?? 0 ) XCTAssertEqual(10, deque.pop() ?? 0 ) } - + func testPushShift() { let deque = Deque() deque.push(10) @@ -22,7 +17,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(10, deque.shift() ?? 0 ) XCTAssertEqual(20, deque.shift() ?? 0 ) } - + func testUnshiftShift() { let deque = Deque() deque.unshift(10) @@ -30,7 +25,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(20, deque.shift() ?? 0 ) XCTAssertEqual(10, deque.shift() ?? 0 ) } - + func testUnshiftPop() { let deque = Deque() deque.unshift(10) @@ -38,7 +33,7 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(10, deque.pop() ?? 0 ) XCTAssertEqual(20, deque.pop() ?? 0 ) } - + func testExampleMethodLength() { let deque = Deque() deque.push(10) @@ -52,5 +47,4 @@ class LinkedListTest: XCTestCase { XCTAssertEqual(50, deque.pop() ?? 0 ) XCTAssertEqual(30, deque.shift() ?? 0 ) } - } diff --git a/exercises/luhn/LuhnExample.swift b/exercises/luhn/LuhnExample.swift index 936dcbea0..3c5503539 100644 --- a/exercises/luhn/LuhnExample.swift +++ b/exercises/luhn/LuhnExample.swift @@ -1,88 +1,78 @@ import Darwin - - struct Luhn { - - var number:Int64 = 0 - var addends:[Int] { return addendsFunc(number)} - var checksum:Int {return addends.reduce(0, combine: +) } - var isValid : Bool { return checksum % 10 == 0} - - init(_ num:Int64){ + var number: Int64 = 0 + var addends: [Int] { return addendsFunc(number) } + var checksum: Int { return addends.reduce(0, combine: +) } + var isValid : Bool { return checksum % 10 == 0 } + + init(_ num: Int64) { self.number = num } - - static func create (num:Int64)->Double{ - - func createCheckDigit(value:Int) -> Int{ + + static func create(num: Int64) -> Double { + func createCheckDigit(value:Int) -> Int { let nearestTen = Int(ceil((Double(value) / 10.00)) * 10) return nearestTen - value } - + let zeroCheckDigitNumber = num * 10 let luhn = Luhn(zeroCheckDigitNumber) - + if luhn.isValid { return Double(zeroCheckDigitNumber)} - + return Double((zeroCheckDigitNumber) + createCheckDigit(luhn.checksum)) - } - - func addendsFunc(num:Int64)->[Int]{ - + + func addendsFunc(num: Int64) -> [Int] { #if swift(>=3.0) - func oddIndexInt64Minus9( input:[Int])->[Int]{ - var input = input - input = Array(input.reversed()) - var tempArray:[Int] = [] - for (inx, each) in input.enumerated(){ - var tempEach:Int = each - if (inx+1) % 2 == 0 { - tempEach *= 2 - if tempEach > 10 { - tempEach -= 9 + func oddIndexInt64Minus9(input: [Int]) -> [Int] { + var input = input + input = Array(input.reversed()) + var tempArray: [Int] = [] + for (inx, each) in input.enumerated() { + var tempEach: Int = each + if (inx+1) % 2 == 0 { + tempEach *= 2 + if tempEach > 10 { + tempEach -= 9 + } + tempArray.insert(tempEach, at: 0) + } else { + tempArray.insert(tempEach, at: 0) } - tempArray.insert(tempEach, at: 0) - } else { - tempArray.insert(tempEach, at: 0) } + return tempArray } - return tempArray - } - #else - func oddIndexInt64Minus9( input:[Int])->[Int]{ - var input = input - input = Array(input.reverse()) - var tempArray:[Int] = [] - for (inx, each) in input.enumerate(){ - var tempEach:Int = each - if (inx+1) % 2 == 0 { - tempEach *= 2 - if tempEach > 10 { - tempEach -= 9 - } - tempArray.insert(tempEach, atIndex: 0) - } else { - tempArray.insert(tempEach, atIndex: 0) - } - } - return tempArray + func oddIndexInt64Minus9(input:[Int]) -> [Int] { + var input = input + input = Array(input.reverse()) + var tempArray: [Int] = [] + for (inx, each) in input.enumerate() { + var tempEach: Int = each + if (inx+1) % 2 == 0 { + tempEach *= 2 + if tempEach > 10 { + tempEach -= 9 + } + tempArray.insert(tempEach, atIndex: 0) + } else { + tempArray.insert(tempEach, atIndex: 0) + } + } + return tempArray } #endif - - func char2Int(input:Character)-> Int{ + + func char2Int(input: Character) -> Int { let tempInt = Int(String(input)) ?? -1 // -1 = error return tempInt } - + let tempString = "\(num)" - + return oddIndexInt64Minus9(Array(tempString.characters).map{char2Int($0)}) } - - - } diff --git a/exercises/luhn/LuhnTest.swift b/exercises/luhn/LuhnTest.swift index 5b9ebfd9a..c20e1717b 100644 --- a/exercises/luhn/LuhnTest.swift +++ b/exercises/luhn/LuhnTest.swift @@ -1,52 +1,48 @@ import XCTest - - class LuhnTest: XCTestCase { - func testAddends() { let luhn = Luhn(12_121) XCTAssertEqual([1, 4, 1, 4, 1], luhn.addends) } - + func testTooLargeAddend() { let luhn = Luhn(8631) XCTAssertEqual([7, 6, 6, 1], luhn.addends) } - + func testChecksum() { let luhn = Luhn(4913) XCTAssertEqual(22, luhn.checksum) } - + func testChecksumAgain() { let luhn = Luhn(201_773) XCTAssertEqual(21, luhn.checksum) } - + func testInvalidNumber() { let luhn = Luhn(738) XCTAssertEqual (false ,luhn.isValid) } - + func testValidNumber() { let luhn = Luhn(8_739_567) XCTAssertEqual (true, luhn.isValid) } - + func testCreateValidNumber() { let number = Luhn.create(123) XCTAssertEqual(1230, number) } - + func testCreateOtherValidNumber() { let number = Luhn.create(873_956) XCTAssertEqual(8_739_567, number) } - + func testCreateYetAnotherValidNumber() { let number = Luhn.create(837_263_756) XCTAssertEqual(8_372_637_564, number) } - } diff --git a/exercises/matrix/MatrixExample.swift b/exercises/matrix/MatrixExample.swift index fff695020..e12eeabb3 100644 --- a/exercises/matrix/MatrixExample.swift +++ b/exercises/matrix/MatrixExample.swift @@ -1,44 +1,37 @@ // Foundation not needed - - - - struct Matrix { - let rows: [[Int]] let columns: [[Int]] - + init(_ stringRepresentation: String) { var rows = [[Int]]() var columns = [[Int]]() - - + #if swift(>=3.0) - let rowItems = stringRepresentation.characters.split(separator: "\n") - for item in rowItems { - let elements = item.split(separator: " ").flatMap { Int(String($0)) } - rows.append(elements) - } + let rowItems = stringRepresentation.characters.split(separator: "\n") + for item in rowItems { + let elements = item.split(separator: " ").flatMap { Int(String($0)) } + rows.append(elements) + } #else let rowItems = stringRepresentation.characters.split("\n") for item in rowItems { - let elements = item.split(" ").flatMap { Int(String($0)) } - rows.append(elements) + let elements = item.split(" ").flatMap { Int(String($0)) } + rows.append(elements) } #endif - + for i in 0 ..< rows[0].count { var column = [Int]() for row in rows { column.append(row[i]) } - + columns.append(column) } - + self.rows = rows self.columns = columns } - -} \ No newline at end of file +} diff --git a/exercises/matrix/MatrixTest.swift b/exercises/matrix/MatrixTest.swift index c82bc77f6..e6b0d5da8 100644 --- a/exercises/matrix/MatrixTest.swift +++ b/exercises/matrix/MatrixTest.swift @@ -1,37 +1,33 @@ import XCTest - - class MatrixTest: XCTestCase { - func testExtractARow() { let matrix = Matrix("1 2\n10 20") XCTAssertEqual([1, 2], matrix.rows[0]) } - + func testExtractSameRowAgain() { let matrix = Matrix("9 7\n8 6") XCTAssertEqual([9, 7], matrix.rows[0]) } - + func testExtractOtherRow() { let matrix = Matrix("9 8 7\n19 18 17") XCTAssertEqual([19, 18, 17], matrix.rows[1]) } - + func testExtractOtherRowAgain() { let matrix = Matrix("1 4 9\n16 25 36") XCTAssertEqual([16, 25, 36], matrix.rows[1]) } - + func testExtractAColumn() { let matrix = Matrix("1 2 3\n4 5 6\n7 8 9\n 8 7 6") XCTAssertEqual([1, 4, 7, 8], matrix.columns[0]) } - + func testExtractAnotherColumn() { let matrix = Matrix("89 1903 3\n18 3 1\n9 4 800") XCTAssertEqual([1903, 3, 4], matrix.columns[1]) } - } diff --git a/exercises/meetup/MeetupExample.swift b/exercises/meetup/MeetupExample.swift index fd4b3aee4..3fc0aafff 100644 --- a/exercises/meetup/MeetupExample.swift +++ b/exercises/meetup/MeetupExample.swift @@ -1,27 +1,23 @@ import Darwin - - -func == (lhs: String, rhs: Date) -> Bool { +func ==(lhs: String, rhs: Date) -> Bool { return lhs == rhs.description } -func == (lhs: Date, rhs: Date) -> Bool { +func ==(lhs: Date, rhs: Date) -> Bool { return lhs.description == rhs.description } - -struct Date{ - +struct Date { enum DateFormatingOption { case yyyy_MM_dd case yyyy_MM_dd_T_HH_mm_ss } - - var descriptionStyle:DateFormatingOption = .yyyy_MM_dd - - private var tmDateBacking:tm = tm() - + + var descriptionStyle: DateFormatingOption = .yyyy_MM_dd + + private var tmDateBacking: tm = tm() + var year:Int32 { return tmDateBacking.tm_year + 1900 } var month:Int32 { return tmDateBacking.tm_mon + 1 } var day:Int32 { return tmDateBacking.tm_mday } @@ -29,17 +25,17 @@ struct Date{ var mins:Int32 { return tmDateBacking.tm_min } var secs:Int32 { return tmDateBacking.tm_sec } var weekday:Int32 { return tmDateBacking.tm_wday + 1 } - - init(_ input:tm){ + + init(_ input: tm) { self.tmDateBacking = input } - - init(){ + + init() { let temp = tm() Date.init(temp).tmDateBacking } - - init(year:Int32, month:Int32, day:Int32, hour:Int32 = 0, mins:Int32 = 0, secs:Int32 = 0){ + + init(year: Int32, month: Int32, day: Int32, hour: Int32 = 0, mins: Int32 = 0, secs: Int32 = 0){ var date = tm() date.tm_year = year - 1900 date.tm_mon = month - 1 @@ -47,62 +43,59 @@ struct Date{ date.tm_hour = hour date.tm_min = mins date.tm_sec = secs - + // Automaticly sets the week day var d1 = timegm(&date) self.tmDateBacking = gmtime(&d1).memory } - + mutating func dateByAddingSeconds(seconds:Int) -> Date { var d1 = timegm(&tmDateBacking) + seconds let d2 = gmtime(&d1).memory return Date.init(d2) } - } -extension Date:CustomStringConvertible { +extension Date: CustomStringConvertible { + private func addLeadingZero(input: Int32) -> String { - - private func addLeadingZero(input:Int32) -> String { - if (0...9).contains(input) { - return "0\(input)" } - else { return String(input) } + return "0\(input)" + } else { + return String(input) + } } - + var description:String { - - let date = [year, month, day, hour, mins, secs].map{addLeadingZero($0)} - + let date = [year, month, day, hour, mins, secs].map { addLeadingZero($0) } + let dateOnly = date[0] + "-" + date[1] + "-" + date[2] let dateTime = dateOnly + "T" + date[3] + ":" + date[4] + ":" + date[5] - - switch descriptionStyle{ + + switch descriptionStyle { case .yyyy_MM_dd : return dateOnly case .yyyy_MM_dd_T_HH_mm_ss : return dateTime } } } -extension Date{ - - init?(from:String){ +extension Date { + init?(from: String) { guard let date = Date.dateFromString(from) else { return nil } tmDateBacking = date.tmDateBacking if from.characters.count > 10 { self.descriptionStyle = .yyyy_MM_dd_T_HH_mm_ss } } - - static func dateFromString(input:String) -> Date? { + + static func dateFromString(input: String) -> Date? { var year = Int32() var month = Int32() var day = Int32() var hour = Int32() var minute = Int32() var second = Int32() - + let dateTime = input.characters.split("T").map{String($0)} let date = dateTime[0].characters.split("-").map{String($0)} if date.count == 3 { @@ -110,56 +103,55 @@ extension Date{ month = Int32(date[1]) ?? 0 day = Int32(date[2]) ?? 0 } - + if dateTime.count == 2 { let time = dateTime[1].characters.split(":").map{String($0)} if time.count == 3 { hour = Int32(time[0]) ?? 0 minute = Int32(time[1]) ?? 0 second = Int32(time[2]) ?? 0 - - } } + + } + } + if year + month + day >= 3 { return Date(year: year, month: month, day: day, hour: hour, mins: minute, secs: second) - - } else { return nil } + } else { + return nil + } } } - - -struct Meetup{ +struct Meetup { private var dateStart = Date() private var dateEnd = Date() - - func newDate(input:String) -> Date{ - + func newDate(input: String) -> Date { return Date(from: input) ?? Date() } - - func day(dayOfTheWeek:Int, which:String) -> Date{ + + func day(dayOfTheWeek: Int, which: String) -> Date { var dateMonthWeekDays = [[Int32(),Int32()]] var dateWeekDays = [Int32()] - + let starDay = dateStart.weekday - var month = Array(dateStart.day ... dateEnd.day).map{(($0 + 5 + starDay) % 7) + 1 } - - for (index , eachDay) in month.enumerate(){ + var month = Array(dateStart.day ... dateEnd.day).map{(($0 + 5 + starDay) % 7) + 1 } + + for (index , eachDay) in month.enumerate() { dateMonthWeekDays.append([index + 1,eachDay]) - dateWeekDays.append(eachDay)} - - func which2date(dateInput:String)->Date{ - + dateWeekDays.append(eachDay) + } + + func which2date(dateInput: String) -> Date { if which == "teenth" { let teenthRange = Array(dateMonthWeekDays[13...19]) let teenth = teenthRange.filter({$0[1] == Int32(dayOfTheWeek) })[0][0] return Date(from: "\(dateStart.year)-\(dateStart.month)-\(teenth)") ?? Date() - + } - let count = dateMonthWeekDays.filter({$0[1] == Int32(dayOfTheWeek) }).count - var dayIndex:Int = 0 - switch dateInput{ + let count = dateMonthWeekDays.filter({$0[1] == Int32(dayOfTheWeek) }).count + var dayIndex: Int = 0 + switch dateInput { case "1st": dayIndex = 0 case "2nd": dayIndex = 1 case "3rd": dayIndex = 2 @@ -168,21 +160,20 @@ struct Meetup{ case "last": dayIndex = (count - 1) default: dayIndex = -1 } - + let first2last = dateMonthWeekDays.filter({$0[1] == Int32(dayOfTheWeek) })[dayIndex][0] ?? 0 - + return Date(from:"\(dateStart.year)-\(dateStart.month)-\(first2last)") ?? Date() } - + return which2date(which) } - - init(year:Int, month:Int){ + + init(year: Int, month: Int) { let meetDate1 = Date(from: "\(year)-\(month)-\(1)") ?? Date() var meetDate2 = Date(from: "\(year)-\(month+1)-\(1)") ?? Date() meetDate2 = meetDate2.dateByAddingSeconds(-1*24*60*60) self.dateStart = meetDate1 self.dateEnd = meetDate2 - } } diff --git a/exercises/meetup/MeetupTest.swift b/exercises/meetup/MeetupTest.swift index 301c10111..7248d172e 100644 --- a/exercises/meetup/MeetupTest.swift +++ b/exercises/meetup/MeetupTest.swift @@ -1,58 +1,52 @@ import XCTest - - class MeetupTest: XCTestCase { - let dayOfWeek = (Sunday:1, Monday:2, Tuesday:3, Wednesday:4, Thursday:5, Friday:6, Saturday:7) - + let whichOptions = (first:"1st", second:"2nd", third:"3rd", fourth:"4th", last:"last",teenth:"teenth") - - + func testMonteenthOfMay2013() { let meetUp = Meetup(year: 2013, month: 5) XCTAssertEqual("2013-05-13", meetUp.day(dayOfWeek.Monday, which: whichOptions.teenth).description) } - + func testSaturteenthOfFebruary2013() { let meetUp = Meetup(year: 2013, month: 2) XCTAssertEqual ("2013-02-16", meetUp.day(dayOfWeek.Saturday, which: whichOptions.teenth).description) } - + func testFirstTuesdayOfMay2013() { let meetUp = Meetup(year: 2013, month: 5) XCTAssertEqual("2013-05-07", meetUp.day(dayOfWeek.Tuesday, which: whichOptions.first).description) } - + func testSecondMondayOfApril2013() { let meetUp = Meetup(year: 2013, month: 4) XCTAssertEqual("2013-04-08", meetUp.day(dayOfWeek.Monday, which: whichOptions.second).description) } - + func testThirdThursdayOfSeptember2013() { let meetUp = Meetup(year: 2013, month: 9) XCTAssertEqual("2013-09-19", meetUp.day(dayOfWeek.Thursday, which: whichOptions.third).description) } - + func testFourthSundayOfMarch2013() { let meetUp = Meetup(year: 2013, month: 3) XCTAssertEqual("2013-03-24", meetUp.day(dayOfWeek.Sunday, which: whichOptions.fourth).description) } - + func testLastThursdayOfOctober2013() { let meetUp = Meetup(year: 2013, month: 10) XCTAssertEqual("2013-10-31", meetUp.day(dayOfWeek.Thursday, which: whichOptions.last).description) } - + func testLastWednesdayOfFebruary2012() { let meetUp = Meetup(year: 2012, month: 2) XCTAssertEqual("2012-02-29", meetUp.day(dayOfWeek.Wednesday, which: whichOptions.last).description) } - + func testFirstFridayOfDecember2012() { let meetUp = Meetup(year: 2012, month: 12) XCTAssertEqual("2012-12-07", meetUp.day(dayOfWeek.Friday, which: whichOptions.first).description) } - - } diff --git a/exercises/minesweeper/MinesweeperExample.swift b/exercises/minesweeper/MinesweeperExample.swift index 651750b48..b777f3353 100644 --- a/exercises/minesweeper/MinesweeperExample.swift +++ b/exercises/minesweeper/MinesweeperExample.swift @@ -1,12 +1,9 @@ import Foundation - - struct Board { - private let validCharacters: [Character] = ["+", "-", "|", "*", " "] private let rows: [String] - + #if swift(>=3.0) enum Error: ErrorProtocol { case DifferentLength @@ -20,36 +17,34 @@ struct Board { case InvalidCharacter } #endif - + init(_ rows: [String]) throws { self.rows = rows - try validateInput() } - + func transform() -> [String] { var result = [String]() #if swift(>=3.0) - let rowsEnumarated = rows.enumerated() + let rowsEnumarated = rows.enumerated() #else let rowsEnumarated = rows.enumerate() #endif - for (i, row) in rowsEnumarated { var newRow = "" #if swift(>=3.0) - let rowCharsEnumarated = row.characters.enumerated() + let rowCharsEnumarated = row.characters.enumerated() #else - let rowCharsEnumarated = row.characters.enumerate() + let rowCharsEnumarated = row.characters.enumerate() #endif - + for (j, character) in rowCharsEnumarated { if character != " " { newRow += String(character) } else { let mineCount = mineCountForRow(row, i: i, j: j) - + if mineCount > 0 { newRow += String(mineCount) } else { @@ -59,41 +54,41 @@ struct Board { } result.append(newRow) } - + return result } - + private func mineCountForRow(row: String, i: Int, j: Int) -> Int { // Must be split up to avoid error: "Expression was too complex to be solved in reasonable time." var surroundings = [row[j - 1], row[j + 1], rows[i - 1][j - 1]] surroundings += [rows[i - 1][j], rows[i - 1][j + 1]] surroundings += [rows[i + 1][j - 1], rows[i + 1][j], rows[i + 1][j + 1]] - + return surroundings.filter { isMine($0) }.count } - + private func isMine(character: Character) -> Bool { return character == "*" } - + private func validateInput() throws { try validateSize() try validateData() try validateBorders() } - + private func validateSize() throws { guard let count = rows.first?.characters.count else { throw Error.DifferentLength } - + try rows.forEach { guard $0.characters.count == count else { throw Error.DifferentLength } } } - + private func validateData() throws { try rows.forEach { try $0.characters.forEach { @@ -103,7 +98,7 @@ struct Board { } } } - + private func validateBorders() throws { let firstAndLast = [rows[0], rows[rows.count - 1]] try firstAndLast.forEach { @@ -111,7 +106,7 @@ struct Board { throw Error.FaultyBorder } } - + let middleRows = rows[1 ..< rows.count - 2] try middleRows.forEach { guard $0.matchesRegex("^\\|.+\\|$") else { @@ -122,40 +117,39 @@ struct Board { } #if swift(>=3.0) -private extension String { - func matchesRegex(pattern: String) -> Bool { - let options = NSRegularExpressionOptions.dotMatchesLineSeparators - let regex = try? NSRegularExpression(pattern: pattern, options: options) - var matches = 0 - if let regex = regex { - matches = regex.numberOfMatches(in: self, - options: [], - range: NSMakeRange(0, (self as NSString).length)) + private extension String { + func matchesRegex(pattern: String) -> Bool { + let options = NSRegularExpressionOptions.dotMatchesLineSeparators + let regex = try? NSRegularExpression(pattern: pattern, options: options) + var matches = 0 + if let regex = regex { + let range = NSMakeRange(0, (self as NSString).length) + matches = regex.numberOfMatches(in: self, options: [], range: range) + } + return matches > 0 + } + + subscript(index: Int) -> Character { + let index = startIndex.advanced(by:index) + return self[index] } - return matches > 0 - } - subscript(index: Int) -> Character { - let index = startIndex.advanced(by:index) - return self[index] } -} - #else private extension String { - func matchesRegex(pattern: String) -> Bool { - let options = NSRegularExpressionOptions.DotMatchesLineSeparators - let regex = try? NSRegularExpression(pattern: pattern, options: options) - var matches = 0 - if let regex = regex { - matches = regex.numberOfMatchesInString(self, - options: [], - range: NSMakeRange(0, (self as NSString).length)) - } - return matches > 0 - } - subscript(index: Int) -> Character { - let index = startIndex.advancedBy(index) - return self[index] - } + func matchesRegex(pattern: String) -> Bool { + let options = NSRegularExpressionOptions.DotMatchesLineSeparators + let regex = try? NSRegularExpression(pattern: pattern, options: options) + var matches = 0 + if let regex = regex { + let range = NSMakeRange(0, (self as NSString).length) + matches = regex.numberOfMatchesInString(self, options: [], range: range) + } + return matches > 0 + } + + subscript(index: Int) -> Character { + let index = startIndex.advancedBy(index) + return self[index] + } } #endif \ No newline at end of file diff --git a/exercises/minesweeper/MinesweeperTest.swift b/exercises/minesweeper/MinesweeperTest.swift index b7e6d8457..3e3e62bf7 100644 --- a/exercises/minesweeper/MinesweeperTest.swift +++ b/exercises/minesweeper/MinesweeperTest.swift @@ -1,77 +1,188 @@ import XCTest - - class MinesweeperTest: XCTestCase { - func testTransform1() { - let input = ["+------+", "| * * |", "| * |", "| * |", "| * *|", - "| * * |", "| |", "+------+"] - let output = ["+------+", "|1*22*1|", "|12*322|", "| 123*2|", "|112*4*|", - "|1*22*2|", "|111111|", "+------+"] + let input = [ + "+------+", + "| * * |", + "| * |", + "| * |", + "| * *|", + "| * * |", + "| |", + "+------+" + ] + let output = [ + "+------+", + "|1*22*1|", + "|12*322|", + "| 123*2|", + "|112*4*|", + "|1*22*2|", + "|111111|", + "+------+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform2() { - let input = ["+-----+", "| * * |", "| |", "| * |", "| * *|", - "| * * |", "+-----+"] - let output = ["+-----+", "|1*2*1|", "|11322|", "| 12*2|", "|12*4*|", - "|1*3*2|", "+-----+"] + let input = [ + "+-----+", + "| * * |", + "| |", + "| * |", + "| * *|", + "| * * |", + "+-----+" + ] + let output = [ + "+-----+", + "|1*2*1|", + "|11322|", + "| 12*2|", + "|12*4*|", + "|1*3*2|", + "+-----+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform3() { - let input = ["+-----+", "| * * |", "+-----+"] - let output = ["+-----+", "|1*2*1|", "+-----+"] + let input = [ + "+-----+", + "| * * |", + "+-----+" + ] + let output = [ + "+-----+", + "|1*2*1|", + "+-----+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func test_transform4() { - let input = ["+-+", "|*|", "| |", "|*|", "| |", "| |", "+-+"] - let output = ["+-+", "|*|", "|2|", "|*|", "|1|", "| |", "+-+"] + let input = [ + "+-+", + "|*|", + "| |", + "|*|", + "| |", + "| |", + "+-+" + ] + let output = [ + "+-+", + "|*|", + "|2|", + "|*|", + "|1|", + "| |", + "+-+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform5() { - let input = ["+-+", "|*|", "+-+"] - let output = ["+-+", "|*|", "+-+"] + let input = [ + "+-+", + "|*|", + "+-+" + ] + let output = [ + "+-+", + "|*|", + "+-+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform6() { - let input = ["+--+", "|**|", "|**|", "+--+"] - let output = ["+--+", "|**|", "|**|", "+--+"] + let input = [ + "+--+", + "|**|", + "|**|", + "+--+" + ] + let output = [ + "+--+", + "|**|", + "|**|", + "+--+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform7() { - let input = ["+--+", "|**|", "|**|", "+--+"] - let output = ["+--+", "|**|", "|**|", "+--+"] + let input = [ + "+--+", + "|**|", + "|**|", + "+--+" + ] + let output = [ + "+--+", + "|**|", + "|**|", + "+--+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform8() { - let input = ["+---+", "|***|", "|* *|", "|***|", "+---+"] - let output = ["+---+", "|***|", "|*8*|", "|***|", "+---+"] + let input = [ + "+---+", + "|***|", + "|* *|", + "|***|", + "+---+" + ] + let output = [ + "+---+", + "|***|", + "|*8*|", + "|***|", + "+---+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testTransform9() { - let input = ["+-----+", "| |", "| * |", "| |", "| |", - "| * |", "+-----+"] - let output = ["+-----+", "| 111|", "| 1*1|", "| 111|", "|111 |", - "|1*1 |", "+-----+"] + let input = [ + "+-----+", + "| |", + "| * |", + "| |", + "| |", + "| * |", + "+-----+" + ] + let output = [ + "+-----+", + "| 111|", + "| 1*1|", + "| 111|", + "|111 |", + "|1*1 |", + "+-----+" + ] XCTAssertEqual(output, try! Board(input).transform()) } - + func testDifferentLength() { var throwsDifferentLengthError = false - + defer { XCTAssertTrue(throwsDifferentLengthError) } - - let input = ["+-+", "| |", "|* |", "| |", "+-+"] + + let input = [ + "+-+", + "| |", + "|* |", + "| |", + "+-+" + ] do { let _ = try Board(input) } catch Board.Error.DifferentLength { @@ -80,15 +191,19 @@ class MinesweeperTest: XCTestCase { return } } - + func testFaultyBorder() { var throwsFaultyBorderError = false - + defer { XCTAssertTrue(throwsFaultyBorderError) } - - let input = ["+-----+", "* * |", "+-- --+"] + + let input = [ + "+-----+", + "* * |", + "+-- --+" + ] do { let _ = try Board(input) } catch Board.Error.FaultyBorder { @@ -97,15 +212,19 @@ class MinesweeperTest: XCTestCase { return } } - + func testInvalidCharacter() { var throwsInvalidCharacterError = false - + defer { XCTAssertTrue(throwsInvalidCharacterError) } - - let input = ["+-----+", "|X * |", "+-----+"] + + let input = [ + "+-----+", + "|X * |", + "+-----+" + ] do { let _ = try Board(input) } catch Board.Error.InvalidCharacter { @@ -114,5 +233,4 @@ class MinesweeperTest: XCTestCase { return } } - } diff --git a/exercises/nth-prime/NthPrimeExample.swift b/exercises/nth-prime/NthPrimeExample.swift index 02a86a8ac..b27e65ea2 100644 --- a/exercises/nth-prime/NthPrimeExample.swift +++ b/exercises/nth-prime/NthPrimeExample.swift @@ -1,39 +1,37 @@ import Darwin - - struct Prime { static func nth(nth: Int) -> Int? { if nth < 1 { return nil } - + var primes = 0 var i = 1 - + while primes < nth { i += 1 if isPrime(i) { primes += 1 } } - + return i } - + private static func isPrime(number: Int) -> Bool { if number == 1 { return false } else if number == 2 { return true } - + for i in 2...Int(ceil(sqrt(Double(number)))) { if number % i == 0 { return false } } - + return true } } diff --git a/exercises/nth-prime/NthPrimeTest.swift b/exercises/nth-prime/NthPrimeTest.swift index 847608b32..375b223ac 100644 --- a/exercises/nth-prime/NthPrimeTest.swift +++ b/exercises/nth-prime/NthPrimeTest.swift @@ -1,27 +1,23 @@ import XCTest - - class NthPrimeTest: XCTestCase { - func testFirst() { XCTAssertEqual(2, Prime.nth(1)) } - + func testSecond() { XCTAssertEqual(3, Prime.nth(2)) } - + func testSixthPrime() { XCTAssertEqual(13, Prime.nth(6)) } - + func testBigPrime() { XCTAssertEqual(104_743, Prime.nth(10_001)) } - + func testWeirdCase() { XCTAssertNil(Prime.nth(0)) } - } diff --git a/exercises/nucleotide-count/NucleotideCountExample.swift b/exercises/nucleotide-count/NucleotideCountExample.swift index 06b3c9740..eb4b19af2 100644 --- a/exercises/nucleotide-count/NucleotideCountExample.swift +++ b/exercises/nucleotide-count/NucleotideCountExample.swift @@ -1,7 +1,5 @@ // Foundation not needed - - enum Nucleobase: Character { case Adenine = "A", Cytosine = "C", @@ -10,14 +8,13 @@ enum Nucleobase: Character { } struct DNA { - var nucleotideCounts:[Nucleobase:Int] = [ .Adenine: 0, .Thymine: 0, .Cytosine: 0 , .Guanine : 0 ] - + init?(strand: String) { #if swift(>=3.0) - let enumarated = strand.characters.enumerated() + let enumarated = strand.characters.enumerated() #else - let enumarated = strand.characters.enumerate() + let enumarated = strand.characters.enumerate() #endif for (_, value) in enumarated { if let possibleNucleobase = Nucleobase(rawValue: value) { @@ -28,11 +25,11 @@ struct DNA { } } } - + func count(value :Character)-> Int { return nucleotideCounts[Nucleobase(rawValue: value)!]! } - + func counts()->[String: Int] { var nCounts:[String:Int] = [:] for (k, v) in nucleotideCounts { @@ -40,6 +37,4 @@ struct DNA { } return nCounts } - } - diff --git a/exercises/nucleotide-count/NucleotideCountTest.swift b/exercises/nucleotide-count/NucleotideCountTest.swift index b98f1324f..1cc3a0d3b 100644 --- a/exercises/nucleotide-count/NucleotideCountTest.swift +++ b/exercises/nucleotide-count/NucleotideCountTest.swift @@ -1,55 +1,52 @@ import XCTest - - -class NucleotideCountTests: XCTestCase -{ +class NucleotideCountTests: XCTestCase { func testEmptyDNAStringHasNoAdenosine() { let dna = DNA(strand: "")! let result = dna.count("A") let expected = 0 XCTAssertEqual(result, expected) } - + func testEmptyDNAStringHasNoNucleotides() { let dna = DNA(strand: "")! let results = dna.counts() let expected = ["T": 0, "A": 0, "C": 0, "G": 0] XCTAssertEqual(results, expected) } - + func testRepetitiveCytidineGetsCounted() { let dna = DNA(strand: "CCCCC")! let result = dna.count("C") let expected = 5 XCTAssertEqual(result, expected) } - + func testRepetitiveSequenceHasOnlyGuanosine() { let dna = DNA(strand: "GGGGGGGG")! let results = dna.counts() let expected = [ "A": 0, "T": 0, "C": 0 , "G": 8 ] XCTAssertEqual(results, expected) } - + func testCountsByThymidine() { let dna = DNA(strand: "GGGGGTAACCCGG")! let result = dna.count("T") let expected = 1 XCTAssertEqual(result, expected) } - + func testCountsANucleotideOnlyOnce() { let dna = DNA(strand: "CGATTGGG")! let result = dna.count("T") let expected = 2 XCTAssertEqual(result, expected) } - + func testValidatesDNA() { XCTAssert(DNA(strand: "John") == nil ) } - + func testCountsAllNucleotides() { let longStrand = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC" let dna = DNA(strand: longStrand)! @@ -57,4 +54,4 @@ class NucleotideCountTests: XCTestCase let expected = [ "A": 20, "T": 21,"C": 12 , "G" : 17 ] XCTAssertEqual(results, expected) } -} \ No newline at end of file +} diff --git a/exercises/ocr-numbers/OcrNumbersExample.swift b/exercises/ocr-numbers/OcrNumbersExample.swift index ccb8daf1e..70aee71d7 100644 --- a/exercises/ocr-numbers/OcrNumbersExample.swift +++ b/exercises/ocr-numbers/OcrNumbersExample.swift @@ -1,78 +1,76 @@ // Foundation not needed - - struct OCR { - + let lines: [String] let patterns = [ - [" _ ", "| |", "|_|", " "] : "0", - [" ", " |", " |", " "] : "1", - [" _ ", " _|", "|_ ", " "] : "2", - [" _ ", " _|", " _|", " "] : "3", - [" ", "|_|", " |", " "] : "4", - [" _ ", "|_ ", " _|", " "] : "5", - [" _ ", "|_ ", "|_|", " "] : "6", - [" _ ", " |", " |", " "] : "7", - [" _ ", "|_|", "|_|", " "] : "8", - [" _ ", "|_|", " _|", " "] : "9" + [" _ ", "| |", "|_|", " "] : "0", + [" ", " |", " |", " "] : "1", + [" _ ", " _|", "|_ ", " "] : "2", + [" _ ", " _|", " _|", " "] : "3", + [" ", "|_|", " |", " "] : "4", + [" _ ", "|_ ", " _|", " "] : "5", + [" _ ", "|_ ", "|_|", " "] : "6", + [" _ ", " |", " |", " "] : "7", + [" _ ", "|_|", "|_|", " "] : "8", + [" _ ", "|_|", " _|", " "] : "9" ] - + #if swift(>=3.0) enum Error: ErrorProtocol { - case InvalidNumberOfLines - case InvalidNumberOfColumns + case InvalidNumberOfLines + case InvalidNumberOfColumns } #else enum Error: ErrorType { - case InvalidNumberOfLines - case InvalidNumberOfColumns + case InvalidNumberOfLines + case InvalidNumberOfColumns } #endif - + init(_ text: String) throws { #if swift(>=3.0) let lines = text.characters.split(separator: "\n").map { String($0) } #else let lines = text.characters.split("\n").map { String($0) } - + #endif - + let rowCount = lines.count - + guard rowCount > 0 && rowCount % 4 == 0 else { throw Error.InvalidNumberOfLines } - + let columnCount = lines[0].characters.count - + guard columnCount > 0 && columnCount % 3 == 0 else { throw Error.InvalidNumberOfColumns } - + try lines.forEach { guard $0.characters.count == columnCount else { throw Error.InvalidNumberOfColumns } } - + self.lines = lines } - + func converted() -> String { var resultArray = [String]() - + var rowIndex = 0 - + while rowIndex < lines.count { let selectedLines = lines[rowIndex ... rowIndex + 3] var result = "" - + var columnIndex = 0 - + while columnIndex < lines[0].characters.count { var grouping = [String]() - + for line in selectedLines { #if swift(>=3.0) let startIndex = line.startIndex.advanced(by:columnIndex) @@ -84,29 +82,27 @@ struct OCR { grouping.append(line[startIndex...endIndex]) #endif - + } - + result += patternForGrouping(grouping) columnIndex += 3 } - + resultArray.append(result) rowIndex += 4 } #if swift(>=3.0) - return resultArray.joined(separator: ",") + return resultArray.joined(separator: ",") #else - return resultArray.joinWithSeparator(",") + return resultArray.joinWithSeparator(",") #endif } - + func patternForGrouping(grouping: [String]) -> String { guard let number = patterns[grouping] else { return "?" } return number } - } - diff --git a/exercises/ocr-numbers/OcrNumbersTest.swift b/exercises/ocr-numbers/OcrNumbersTest.swift index eaddfa7d0..3caa9b8ba 100644 --- a/exercises/ocr-numbers/OcrNumbersTest.swift +++ b/exercises/ocr-numbers/OcrNumbersTest.swift @@ -1,9 +1,6 @@ import XCTest - - class OcrNumbersTest: XCTestCase { - func testRecognizeZero() { let text = " _ \n" + "| |\n" + @@ -11,7 +8,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("0", try? OCR(text).converted()) } - + func testRecognizeOne() { let text = " \n" + " |\n" + @@ -27,7 +24,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("2", try? OCR(text).converted()) } - + func testRecognizeThree() { let text = " _ \n" + " _|\n" + @@ -35,7 +32,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("3", try? OCR(text).converted()) } - + func testRecognizeFour() { let text = " \n" + "|_|\n" + @@ -43,7 +40,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("4", try? OCR(text).converted()) } - + func testRecognizeFive() { let text = " _ \n" + "|_ \n" + @@ -51,7 +48,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("5", try? OCR(text).converted()) } - + func testRecognizeSix() { let text = " _ \n" + "|_ \n" + @@ -67,7 +64,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("7", try? OCR(text).converted()) } - + func testRecognizeEight() { let text = " _ \n" + "|_|\n" + @@ -83,7 +80,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("9", try? OCR(text).converted()) } - + func testIdentifyGarble() { let text = " \n" + "| |\n" + @@ -91,7 +88,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("?", try? OCR(text).converted()) } - + func testIdentify10() { let text = " _ \n" + " || |\n" + @@ -99,7 +96,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("10", try? OCR(text).converted()) } - + func testIdentify110101100() { let text = " _ _ _ _ \n" + @@ -108,7 +105,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("110101100", try? OCR(text).converted()) } - + func testIdentifyWithGarble() { let text = " _ _ _ \n" + @@ -117,7 +114,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("11?10?1?0", try? OCR(text).converted()) } - + func testIdentify1234567890() { let text = " _ _ _ _ _ _ _ _ \n" + @@ -126,7 +123,7 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("1234567890", try? OCR(text).converted()) } - + func testIdentify123_456_789() { let text = " _ _ \n" + @@ -143,14 +140,14 @@ class OcrNumbersTest: XCTestCase { " " XCTAssertEqual("123,456,789", try? OCR(text).converted()) } - + func testThrowsInvalidNumberOfLinesError() { var throwsInvalidNumberOfLinesError = false - + defer { XCTAssertTrue(throwsInvalidNumberOfLinesError) } - + do { let text = " _ _ \n" + @@ -163,14 +160,14 @@ class OcrNumbersTest: XCTestCase { return } } - + func testThrowsInvalidNumberOfColumnsError() { var throwsInvalidNumberOfColumnsError = false - + defer { XCTAssertTrue(throwsInvalidNumberOfColumnsError) } - + do { let text = " _\n" + @@ -185,5 +182,4 @@ class OcrNumbersTest: XCTestCase { return } } - } diff --git a/exercises/octal/OctalExample.swift b/exercises/octal/OctalExample.swift index 89945d623..aac5e6d9f 100644 --- a/exercises/octal/OctalExample.swift +++ b/exercises/octal/OctalExample.swift @@ -1,13 +1,9 @@ import Darwin - - extension Int{ - init(_ value:Octal){ self = value.toDecimal } - } struct Octal { @@ -16,7 +12,7 @@ struct Octal { private func isValidOctal() -> Bool{ return (Int(stringValue) ?? -1) > -1 ? true : false } - + private func oct2int(input:String)->Int{ let orderedInput = Array(input.characters.reverse()) var tempInt:Int = 0 @@ -28,15 +24,12 @@ struct Octal { } return tempInt } - - + init( _ sv:String){ self.stringValue = sv - + if isValidOctal() { self.toDecimal = oct2int(sv) } - } - -} \ No newline at end of file +} diff --git a/exercises/octal/OctalTest.swift b/exercises/octal/OctalTest.swift index e97e4d103..b5d6eab6e 100644 --- a/exercises/octal/OctalTest.swift +++ b/exercises/octal/OctalTest.swift @@ -1,65 +1,59 @@ import XCTest - - -class OctalTest: XCTestCase -{ - +class OctalTest: XCTestCase { func testOctal1IsDecimal1() { XCTAssertEqual(1, Int(Octal("1"))) } - + func testOctal10IsDecimal8() { XCTAssertEqual(8, Int(Octal("10"))) } - + func testOctal17IsDecimal15() { XCTAssertEqual(15, Int(Octal("17"))) } - + func testOctal11IsDecimal9() { XCTAssertEqual(9, Int(Octal("11"))) } - + func testOctal130IsDecimal88() { XCTAssertEqual(88, Int(Octal("130"))) } - + func testOctal2047IsDecimal1063() { XCTAssertEqual(1063, Int(Octal("2047"))) } - + func testOctal7777IsDecimal4095() { XCTAssertEqual(4095, Int(Octal("7777"))) } - + func testOctal1234567IsDecimal342391() { XCTAssertEqual(342391, Int(Octal("1234567"))) } - + func testInvalidOctalIsDecimal0() { XCTAssertEqual(0, Int(Octal("carrot"))) } - + func test8IsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("8"))) } - + func test9IsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("9"))) } - + func test6789IsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("6789"))) } - + func testabc1zIsseenasInvalidandreturns0() { XCTAssertEqual(0, Int(Octal("abc1z"))) } - + func testvalidOctalformattedstring011IsDecimal9() { XCTAssertEqual(9, Int(Octal("011"))) } - - -} \ No newline at end of file +} diff --git a/exercises/palindrome-products/PalindromeProductsExample.swift b/exercises/palindrome-products/PalindromeProductsExample.swift index ac38ef345..e6340fa34 100644 --- a/exercises/palindrome-products/PalindromeProductsExample.swift +++ b/exercises/palindrome-products/PalindromeProductsExample.swift @@ -1,10 +1,9 @@ -import Foundation // Apple Swift version 2.1 +import Foundation private extension String { - var length: Int {return self.characters.count} - + func reverse() -> String { var result:String = "" for char in self.characters { @@ -15,29 +14,27 @@ private extension String { } struct PalindromeProducts{ - typealias Palindrome = (value:Int, factor:[Int]) private let maxFactor:Int private let minFactor:Int - + var largest:Palindrome {return calculate(.max)} var smallest:Palindrome {return calculate(.min)} - + init(maxFactor: Int, minFactor: Int = 1) { self.maxFactor = maxFactor self.minFactor = minFactor } - + private enum Mode { case max, min } private func calculate(upTo:Mode)->Palindrome{ - let rangeOuter = minFactor...maxFactor var multiplications = [Palindrome]() - - //Multitreaded code + + // Multi-threaded code let queue = dispatch_queue_create("io.exercism.multiQueuePali", DISPATCH_QUEUE_CONCURRENT) var results = [[Palindrome]](count: rangeOuter.count, repeatedValue: [Palindrome]()) - + dispatch_apply(rangeOuter.count, queue){ advanceByIndex in var multiplicationsTemp = [Palindrome]() @@ -53,7 +50,7 @@ struct PalindromeProducts{ results[advanceByIndex] = multiplicationsTemp } multiplications = results.flatten().sort({$0.0 > $1.0}) - + if let large = multiplications.first, let small = multiplications.last{ switch upTo{ case .max : return large @@ -67,5 +64,3 @@ struct PalindromeProducts{ } } } - - diff --git a/exercises/palindrome-products/PalindromeProductsTest.swift b/exercises/palindrome-products/PalindromeProductsTest.swift index ec860d14c..69cdb59d2 100644 --- a/exercises/palindrome-products/PalindromeProductsTest.swift +++ b/exercises/palindrome-products/PalindromeProductsTest.swift @@ -1,16 +1,13 @@ import XCTest - - class PalindromeProductsTest: XCTestCase { - func testLargestPalindromeFromSingleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 9) let largest = palindromes.largest XCTAssertEqual(9, largest.value) XCTAssertTrue(Set([1, 9]) == Set(largest.factor) || Set([3, 3]) == Set(largest.factor) ) } - + func testLargestPalindromeFromDoubleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 99, minFactor: 10) let largest = palindromes.largest @@ -24,19 +21,18 @@ class PalindromeProductsTest: XCTestCase { XCTAssertEqual(121, smallest.value) XCTAssertEqual(Set([11, 11]), Set(smallest.factor)) } - + func testLargestPalindromeFromTripleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 999, minFactor: 100) let largest = palindromes.largest XCTAssertEqual(906_609, largest.value) XCTAssertEqual(Set([913, 993]), Set(largest.factor)) } - + func testSmallestPalindromeFromTripleDigitFactors() { let palindromes = PalindromeProducts(maxFactor: 999, minFactor: 100) let smallest = palindromes.smallest XCTAssertEqual(10_201, smallest.value) XCTAssertEqual(Set([101, 101]), Set(smallest.factor)) } - } diff --git a/exercises/pascals-triangle/PascalsTriangleExample.swift b/exercises/pascals-triangle/PascalsTriangleExample.swift index aa8b8dc83..41bd05a4e 100644 --- a/exercises/pascals-triangle/PascalsTriangleExample.swift +++ b/exercises/pascals-triangle/PascalsTriangleExample.swift @@ -1,14 +1,11 @@ // Foundation not needed - - struct PascalsTriangle { - let rows: [[Int]] - + init(_ numberOfRows: Int) { var triangle = [[Int]]() - + for rowNumber in 0..Int { - return Array(1..<(input-1)).filter( {input % $0 == 0} ).reduce(0,combine: +) + return Array(1..<(input-1)).filter( {input % $0 == 0} ).reduce(0,combine: +) } init(number: Int) { self.number = number } - } diff --git a/exercises/perfect-numbers/PerfectNumbersTest.swift b/exercises/perfect-numbers/PerfectNumbersTest.swift index bb42be95f..9f15c1748 100644 --- a/exercises/perfect-numbers/PerfectNumbersTest.swift +++ b/exercises/perfect-numbers/PerfectNumbersTest.swift @@ -1,34 +1,23 @@ - import XCTest - - class PerfectNumbersTest: XCTestCase { - - func testPerfect() { let numberClassifier = NumberClassifier(number: 6) XCTAssertEqual([.Perfect],[numberClassifier.classification]) } - + func testPerfectAgain() { let numberClassifier = NumberClassifier(number: 28) XCTAssertEqual([.Perfect],[numberClassifier.classification]) - - } - + func testDeficient() { let numberClassifier = NumberClassifier(number: 13) XCTAssertEqual([.Deficient],[numberClassifier.classification]) - } - + func testAbundant() { let numberClassifier = NumberClassifier(number: 12) XCTAssertEqual([.Abundant],[numberClassifier.classification]) - - } - } diff --git a/exercises/phone-number/PhoneNumberExample.swift b/exercises/phone-number/PhoneNumberExample.swift index fffab4a04..ede27db36 100644 --- a/exercises/phone-number/PhoneNumberExample.swift +++ b/exercises/phone-number/PhoneNumberExample.swift @@ -1,20 +1,16 @@ // Foundation not needed - - private extension String { subscript (range: Range) -> String { get { #if swift(>=3.0) let start = startIndex.advanced(by:range.startIndex) let end = start.advanced(by:range.endIndex - range.startIndex) - #else - let start = startIndex.advancedBy(range.startIndex) - let end = start.advancedBy(range.endIndex - range.startIndex) - + let start = startIndex.advancedBy(range.startIndex) + let end = start.advancedBy(range.endIndex - range.startIndex) #endif - + return self[start.. String { let index = self.startIndex.advancedBy(indx) @@ -13,57 +11,39 @@ private extension String{ let end = self.startIndex.advancedBy(intRange.endIndex) return self.substringWithRange(start.. String { - return word.componentsSeparatedByString(" ").map{self.translateWord($0)}.joinWithSeparator(" ") - - + return word.componentsSeparatedByString(" ").map{self.translateWord($0)}.joinWithSeparator(" ") } - + static func translateWord(word:String) -> String{ - - func wordStartsWithPrefixes(word:String, prefixes:[String]) ->Bool{ return 0 < prefixes.filter{word.hasPrefix($0)}.count - } - + func wordStartsWithVowelLike(word:String) ->Bool{ return wordStartsWithPrefixes(word, prefixes: ["xr", "yt", "a", "e","i", "o","u" ]) } - + func wordStartsWithConsonantAndQu(word:String) -> Bool{ let index = word.startIndex.advancedBy(1) return word.substringFromIndex(index).hasPrefix("qu") } - - if wordStartsWithVowelLike(word){return word + "ay"} if wordStartsWithPrefixes(word, prefixes: ["thr", "sch"]){ - return (word.substringFromIndexInt(3) + word.substringWithRangeInt(0..<3) + "ay") } - + return (word.substringFromIndexInt(3) + word.substringWithRangeInt(0..<3) + "ay") } + if wordStartsWithPrefixes(word, prefixes: ["ch", "qu", "th"]){ - return word.substringFromIndexInt(2) + - word.substringWithRangeInt(0..<2) + "ay" } + return word.substringFromIndexInt(2) + + word.substringWithRangeInt(0..<2) + "ay" } if wordStartsWithConsonantAndQu(word){ - return word.substringFromIndexInt(3) + - word.substringWithRangeInt(0..<1) + "quay"} + return word.substringFromIndexInt(3) + + word.substringWithRangeInt(0..<1) + "quay"} return word.substringFromIndexInt(1) + word.substringWithRangeInt(0..<1) + "ay" - } - - - - - - -} \ No newline at end of file +} diff --git a/exercises/pig-latin/PigLatinTest.swift b/exercises/pig-latin/PigLatinTest.swift index e6084be43..890901db0 100644 --- a/exercises/pig-latin/PigLatinTest.swift +++ b/exercises/pig-latin/PigLatinTest.swift @@ -1,69 +1,63 @@ - import XCTest - - class PigLatinTest : XCTestCase { - - func testWordBeginningWithA() { XCTAssertEqual("appleay", PigLatin.translate("apple")) } - + func test_otherWordBeginningE() { XCTAssertEqual("earay", PigLatin.translate("ear")) } - + func testWordBeginningWithP() { XCTAssertEqual("igpay", PigLatin.translate("pig")) } - + func testWordBeginningWithK() { XCTAssertEqual("oalakay", PigLatin.translate("koala")) } - + func testWordBeginningWithCh() { XCTAssertEqual("airchay", PigLatin.translate("chair")) } - + func testWordBeginningWithQu() { XCTAssertEqual("eenquay", PigLatin.translate("queen")) } - + func testWordWithConsonantPrecedingQu() { XCTAssertEqual("aresquay", PigLatin.translate("square")) } - + func testWordBeginningWithTh() { XCTAssertEqual("erapythay", PigLatin.translate("therapy")) } - + func testWordBeginningWithThr() { XCTAssertEqual("ushthray", PigLatin.translate("thrush")) } - + func testWordBeginningWithSch() { XCTAssertEqual("oolschay", PigLatin.translate("school")) } - + func testWordBeginningWithYe() { XCTAssertEqual("ellowyay", PigLatin.translate("yellow")) } - + func testWordBeginningWithYt() { XCTAssertEqual("yttriaay", PigLatin.translate("yttria")) } - + func testWordBeginningWithXe() { XCTAssertEqual("enonxay", PigLatin.translate("xenon")) } - + func testWordBeginningWithXr() { XCTAssertEqual("xrayay", PigLatin.translate("xray")) } - + func testTranslatesPhrase() { XCTAssertEqual("ickquay astfay unray", PigLatin.translate("quick fast run")) } - -} \ No newline at end of file +} diff --git a/exercises/poker/PokerExample.swift b/exercises/poker/PokerExample.swift index 9f4d4fcf1..bfb1fa471 100644 --- a/exercises/poker/PokerExample.swift +++ b/exercises/poker/PokerExample.swift @@ -1,6 +1,4 @@ - private extension String { - func split(input: String)->[String] { return self.componentsSeparatedByString(input) } @@ -14,26 +12,24 @@ private extension String { } } -struct Poker{ - +struct Poker { static func bestHand(hands:[String])->String?{ - + var pokerHandsParsed:[PokerHand] = [] - + for each in hands{ guard let pokerHand = PokerHand(each) else { return nil } pokerHandsParsed.append(pokerHand) } - + guard let topHand = (pokerHandsParsed.sort(>)).first, let indexTop = pokerHandsParsed.indexOf(topHand) else {return nil} - + return hands[indexTop] - } } -enum HandRank{ +enum HandRank { case highCard(PlayingCard) case onePair(Rank,card1:Rank, card2:Rank, card3:Rank ) case twoPair(high:Rank,low:Rank, highCard:PlayingCard) @@ -43,7 +39,7 @@ enum HandRank{ case fullHouse(three:Rank) case fourOfAKind(four:Rank) case straightFlush(Rank,Suit) - + func order()->Int{ switch self { case .highCard(_): return 1 @@ -57,7 +53,7 @@ enum HandRank{ case straightFlush(_,_): return 9 } } - + static func parsePairs(inputHand:PokerHand)->[(rank:Rank,count:Int)]{ let ranks = inputHand.hand.map({$0.rank}) let rankSet = Set(ranks) @@ -69,11 +65,11 @@ enum HandRank{ } let result = toReturn.map({key,value in return (rank:key,count:value)}).sort({ (one, two) in - return one.count == two.count ? one.rank > two.rank : one.count > two.count - }) + return one.count == two.count ? one.rank > two.rank : one.count > two.count + }) return result } - + static func isFlush(inputHand:PokerHand)->(bool:Bool,suit:Suit){ let suits = inputHand.hand.map({$0.suit}) let first = suits[0] @@ -82,7 +78,7 @@ enum HandRank{ } return (true,first) } - + static func isStraight(inputHand:PokerHand)->(bool:Bool, highest:Rank){ let sorted = inputHand.hand.sort({$0.rank < $1.rank}) let first = sorted[0].rank.rawValue @@ -102,12 +98,12 @@ enum HandRank{ let last = sorted[sorted.count - 1].rank return (true,last) } - + init(_ pokerHand:PokerHand){ let pairs = HandRank.parsePairs(pokerHand) let (flush, flushSuit) = HandRank.isFlush(pokerHand) let (straight, straightRank) = HandRank.isStraight(pokerHand) - + //straightFlush if flush && straight { self = .straightFlush(straightRank, flushSuit) @@ -132,7 +128,7 @@ enum HandRank{ let r = (pairs[2]).rank let s = pokerHand.hand[4].suit self = .twoPair(high: (pairs[0]).rank, low: (pairs[1]).rank, - highCard:PlayingCard.init(rank: r, suit: s)) + highCard:PlayingCard.init(rank: r, suit: s)) //onePair } else if pairs[0].count == 2 && pairs.count == 4 { self = .onePair((pairs[0]).rank, card1: (pairs[1]).rank, card2: (pairs[2]).rank, card3: (pairs[3]).rank) @@ -149,37 +145,37 @@ extension HandRank : Equatable, Comparable {} func ==(lhs: HandRank, rhs: HandRank) -> Bool { switch (lhs, rhs) { - //straightFlush(Rank,Suit) + //straightFlush(Rank,Suit) case (HandRank.straightFlush(let lRank, let lSuit),HandRank.straightFlush(let rRank , let rSuit)): return lRank == rRank && lSuit == rSuit - //fourOfAKind(four:Rank) + //fourOfAKind(four:Rank) case (HandRank.fourOfAKind(four: let lFour), HandRank.fourOfAKind(four: let rFour)): return lFour == rFour - //fullHouse(three:Rank) + //fullHouse(three:Rank) case (HandRank.fullHouse(three: let lThree), HandRank.fullHouse(three: let rThree)): return lThree == rThree - //flush(Suit) + //flush(Suit) case (HandRank.flush(let lRank, let lSuit) ,HandRank.flush(let rRank, let rSuit)): return lSuit == rSuit && lRank == rRank - //straight(high:Rank) + //straight(high:Rank) case (HandRank.straight(high: let lRank), HandRank.straight(high: let rRank)): return lRank == rRank - //threeOfAKind(three:Rank) + //threeOfAKind(three:Rank) case (HandRank.threeOfAKind(three: let lRank), HandRank.threeOfAKind(three: let rRank)): return lRank == rRank - //twoPair(high:Rank,low:Rank, highCard:PlayingCard) + //twoPair(high:Rank,low:Rank, highCard:PlayingCard) case (HandRank.twoPair(high: let lHigh, low: let lLow, highCard: let lCard),HandRank.twoPair(high: let rHigh, low: let rLow, highCard: let rCard)): return lHigh == rHigh && lLow == rLow && lCard == rCard - //onePair(Rank) + //onePair(Rank) case (HandRank.onePair(let lPairRank, card1: let lCard1, card2: let lCard2, card3: let lCard3), HandRank.onePair(let rPairRank, card1: let rCard1, card2: let rCard2, card3: let rCard3)): return lPairRank == rPairRank && lCard1 == rCard1 && lCard2 == rCard2 && lCard3 == rCard3 - //highCard(PlayingCard) + //highCard(PlayingCard) case (HandRank.highCard(let lCard), HandRank.highCard(let rCard)): return lCard == rCard default: @@ -191,79 +187,77 @@ func <(lhs: HandRank, rhs: HandRank) -> Bool { switch (lhs, rhs) { case (_, _) where lhs == rhs: return false - - //straightFlush(Rank,Suit) + + //straightFlush(Rank,Suit) case (HandRank.straightFlush(let lRank, let lSuit),HandRank.straightFlush(let rRank , let rSuit)): return lRank == rRank ? lSuit < rSuit : lRank < rRank - - //fourOfAKind(four:Rank) + + //fourOfAKind(four:Rank) case (HandRank.fourOfAKind(four: let lFour), HandRank.fourOfAKind(four: let rFour)): return lFour < rFour - - //fullHouse(three:Rank) + + //fullHouse(three:Rank) case (HandRank.fullHouse(three: let lRank), HandRank.fullHouse(three: let rRank)): return lRank < rRank - - //flush(Suit) + + //flush(Suit) case (HandRank.flush(let lRank,let lSuit),HandRank.flush(let rRank, let rSuit)): return lRank == rRank ? lSuit < rSuit : lRank < rRank - - //straight(high:Rank) + + //straight(high:Rank) case (HandRank.straight(high: let lRank), HandRank.straight(high: let rRank)): return lRank < rRank - - //threeOfAKind(three:Rank) + + //threeOfAKind(three:Rank) case (HandRank.threeOfAKind(three: let lRank), HandRank.threeOfAKind(three: let rRank)): return lRank < rRank - - //twoPair(high:Rank,low:Rank, highCard:PlayingCard) + + //twoPair(high:Rank,low:Rank, highCard:PlayingCard) case (HandRank.twoPair(high: let lHigh, low: let lLow, highCard: let lCard),HandRank.twoPair(high: let rHigh, low: let rLow, highCard: let rCard)): if lHigh == rHigh && lLow == rLow { return lCard < rCard } else { return lHigh < rHigh } - - //onePair(Rank) + + //onePair(Rank) case (HandRank.onePair(let lPairRank, card1: let lCard1, card2: let lCard2, card3: let lCard3), HandRank.onePair(let rPairRank, card1: let rCard1, card2: let rCard2, card3: let rCard3)): return lPairRank == rPairRank ? (lCard1 == rCard1 ? (lCard2 == rCard2 ? lCard3 < rCard3 :lCard2 < rCard2):lCard1 < rCard1):lPairRank < rPairRank - - //highCard(PlayingCard) + + //highCard(PlayingCard) case (HandRank.highCard(let lCard), HandRank.highCard(let rCard)): return lCard < rCard - + default: return lhs.order() < rhs.order() } - } -struct PokerHand{ +struct PokerHand { let hand:[PlayingCard] - + func handRank()->HandRank{ return HandRank(self) } - + init?(_ stringHand:String){ - + var handParsed:[PlayingCard] = [] - + for each in stringHand.split(" "){ guard let card = PlayingCard(each) else {return nil} handParsed.append(card) } - + if handParsed.count == 5 {self.hand = handParsed } else {return nil} } } - extension PokerHand : Equatable, Comparable {} func ==(lhs: PokerHand, rhs: PokerHand) -> Bool{ @@ -274,21 +268,19 @@ func <(lhs: PokerHand, rhs: PokerHand) -> Bool { return lhs.handRank() < rhs.handRank() } - struct PlayingCard { let rank: Rank let suit: Suit - + init(rank: Rank, suit: Suit) { self.rank = rank self.suit = suit } - + init?(_ stringInput:String){ - guard let rank = Rank(stringInput.head()), let suit = Suit(stringInput.tail()) else { return nil} - + self.rank = rank self.suit = suit } @@ -304,12 +296,11 @@ func <(lhs: PlayingCard, rhs: PlayingCard) -> Bool { return lhs.rank == rhs.rank ? lhs.suit < rhs.suit : lhs.rank < rhs.rank } - enum Rank : Int { case Two = 2 case Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King, Ace - + init?(_ rank:String){ var rankInt = 0 switch rank{ @@ -326,9 +317,9 @@ enum Rank : Int { enum Suit: String { case Spades, Hearts, Diamonds, Clubs case None - + init?(_ suit:String){ - + switch suit { case "♡": self = .Hearts case "♢": self = .Diamonds @@ -357,10 +348,10 @@ func <(lhs: Suit, rhs: Suit) -> Bool { case (_, _) where lhs == rhs: return false case (.Spades, _), - (.Hearts, .Diamonds), (.Hearts, .Clubs), - (.Diamonds, .Clubs): + (.Hearts, .Diamonds), (.Hearts, .Clubs), + (.Diamonds, .Clubs): return false default: return true } -} \ No newline at end of file +} diff --git a/exercises/poker/PokerTest.swift b/exercises/poker/PokerTest.swift index fa8d1480e..f8e1ed634 100644 --- a/exercises/poker/PokerTest.swift +++ b/exercises/poker/PokerTest.swift @@ -1,284 +1,279 @@ import XCTest class PokerTest: XCTestCase { - var validTestCases:[(name: String, hands:[String], best:String)] = [] var invalidTestCases:[(name: String, hand:String)] = [] - + func testInvalidCases(){ for each in invalidTestCases{ - XCTAssertNil(PokerHand(each.hand), "\(each.name)") + XCTAssertNil(PokerHand(each.hand), "\(each.name)") } } - + func testAllValid() { for each in validTestCases{ XCTAssertEqual(Poker.bestHand(each.hands), each.best, "\(each.name)") } } - + override func setUp() { super.setUp() - - validTestCases = [ - ( - name: "single hand is always best", - hands: ["3♡ 10♢ 7♧ 8♤ A♢"], - best: "3♡ 10♢ 7♧ 8♤ A♢" - ), - ( - name: "highest card", - hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 2♡ 5♧ 6♢ 10♡"], - best: "3♡ 2♡ 5♧ 6♢ 10♡" - ), - ( - name: "One pair", - hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 3♤ 5♧ 6♢ 9♢"], - best: "3♡ 3♤ 5♧ 6♢ 9♢" - ), - ( - name: "pair beats lower", - hands: ["4♢ 3♤ 4♤ J♤ K♤", "A♡ K♡ J♢ 10♧ 9♡"], - best: "4♢ 3♤ 4♤ J♤ K♤" - ), - ( - name: "best pair", - hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "3♢ 3♡ 5♤ 6♤ 9♡"], - best: "4♡ 2♡ 5♧ 4♢ 10♡" - ), - ( - name: "best pair with same pair and highest cards", - hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♤ 4♧ 5♡ 10♢ 3♡"], - best: "4♤ 4♧ 5♡ 10♢ 3♡" - ), - ( - name: "two pair beats lower", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "2♢ 8♡ 5♢ 2♡ 8♧" - ), - ( - name: "best two pair", - hands: [ - "4♢ J♧ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "4♢ J♧ 4♤ J♤ K♤" - ), - ( - name: "best two pair with equal highest pair", - hands: [ - "4♢ J♧ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "3♢ J♡ 5♢ 3♡ J♢", - ], - best: "4♢ J♧ 4♤ J♤ K♤" - ), - ( - name: "best two pair with equal pairs", - hands: [ - "4♢ J♧ 4♤ J♤ 2♤", - "A♡ K♡ J♢ 10♧ 9♡", - "4♧ J♡ 5♢ 4♡ J♢", - ], - best: "4♧ J♡ 5♢ 4♡ J♢" - ), - ( - name: "full house", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "A♡ K♡ J♢ 10♧ 9♡", - "3♡ 8♡ 3♢ 3♧ 8♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "3♡ 8♡ 3♢ 3♧ 8♧" - ), - ( - name: "best three of a kind", - hands: [ - "4♢ 3♤ 4♤ J♤ 4♡", - "A♡ K♡ J♢ 10♧ 9♡", - "3♢ 8♡ 3♡ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "4♢ 3♤ 4♤ J♤ 4♡" - ), - ( - name: "straight beats lower", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♡ 8♡ 3♢ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "Q♡ K♡ J♢ 10♧ 9♡" - ), - ( - name: "straight includes ace as one", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "2♤ 3♡ A♤ 5♤ 4♤", - "3♢ 8♡ 3♡ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "2♤ 3♡ A♤ 5♤ 4♤" - ), - ( - name: "best straight", - hands: [ - "4♢ 3♤ 4♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "A♢ K♧ 10♢ J♢ Q♢", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "A♢ K♧ 10♢ J♢ Q♢" - ), - ( - name: "flush beats lower", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 8♡ 3♢ 3♧ 9♧", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "4♤ 3♤ 8♤ J♤ K♤" - ), - ( - name: "best flush", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 8♢ A♢ 2♢ 7♢", - "2♢ 8♡ 5♢ 2♡ 8♧", - ], - best: "3♢ 8♢ A♢ 2♢ 7♢" - ), - ( - name: "full house beats lower", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♡ A♡ 3♢ 3♧ A♧", - ], - best: "2♢ 8♡ 8♢ 2♡ 8♧" - ), - ( - name: "best full house", - hands: [ - "4♤ 3♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "5♡ 5♢ A♤ 5♧ A♢", - "3♡ A♡ 3♢ 3♧ A♧", - ], - best: "2♢ 8♡ 8♢ 2♡ 8♧" - ), - ( - name: "four of a kind beats lower", - hands: [ - "4♤ 5♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 3♡ 3♤ 3♧ A♧", - ], - best: "3♢ 3♡ 3♤ 3♧ A♧" - ), - ( - name: "best four of a kind", - hands: [ - "4♤ 5♤ 8♤ J♤ K♤", - "2♢ 2♧ 8♢ 2♡ 2♤", - "Q♡ K♡ J♢ 10♧ 9♡", - "3♢ 3♡ 3♤ 3♧ A♧", - ], - best: "3♢ 3♡ 3♤ 3♧ A♧" - ), - ( - name: "straight flush beats lower", - hands: [ - "4♤ 4♢ 4♡ 4♧ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ 8♡ 10♡ 9♡", - "2♤ 3♤ A♤ 5♤ 4♤", - ], - best: "2♤ 3♤ A♤ 5♤ 4♤" - ), - ( - name: "best straight flush is royal flush", - hands: [ - "4♤ 5♤ 8♤ J♤ K♤", - "2♢ 8♡ 8♢ 2♡ 8♧", - "Q♡ K♡ J♡ 10♡ 9♡", - "Q♢ K♢ J♢ 10♢ A♢", - ], - best: "Q♢ K♢ J♢ 10♢ A♢" - ), - ( - name: "tie for best pair: brake tide by suit", - hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♧ 10♢ 5♤ 2♤ 4♤"], - best: "4♡ 2♡ 5♧ 4♢ 10♡" - ), - ( - name: "tie of three: brake tide by suit", - hands: [ - "A♡ 2♡ 3♡ 4♡ 5♡", - "A♤ 2♤ 3♤ 4♤ 5♤", - "5♧ 4♧ 3♧ 2♧ A♧", - "A♢ 2♢ 6♢ 4♢ 5♢", - ], - best: "A♤ 2♤ 3♤ 4♤ 5♤" - ), - ] - - invalidTestCases = - [ - ( - name: "1 is an invalid card rank", - hand: "1♢ 2♡ 3♡ 4♡ 5♡" - ), - ( - name: "15 is an invalid card rank", - hand: "15♢ 2♡ 3♡ 4♡ 5♡" - ), - ( - name: "too few cards", - hand: "2♡ 3♡ 4♡ 5♡" - ), - ( - name: "too many cards", - hand: "2♡ 3♡ 4♡ 5♡ 6♡ 7♡" - ), - ( - name: "lack of rank", - hand: "11♢ 2♡ ♡ 4♡ 5♡" - ), - ( - name: "lack of suit", - hand: "2♡ 3♡ 4 5♡ 7♡" - ), - ( - name: "H is an invalid suit", - hand: "2♡ 3♡ 4H 5♡ 7♡" - ), - ( - name: "♥ is an invalid suit", - hand: "2♡ 3♡ 4♥ 5♡ 7♡" - ), - ( - name: "lack of spacing", - hand: "2♡ 3♡ 5♡7♡ 8♡" - ), - ( - name: "double suits after rank", - hand: "2♡ 3♡ 5♡♡ 8♡ 9♡" - ), - ] - + + validTestCases = [ + ( + name: "single hand is always best", + hands: ["3♡ 10♢ 7♧ 8♤ A♢"], + best: "3♡ 10♢ 7♧ 8♤ A♢" + ), + ( + name: "highest card", + hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 2♡ 5♧ 6♢ 10♡"], + best: "3♡ 2♡ 5♧ 6♢ 10♡" + ), + ( + name: "One pair", + hands: ["3♢ 2♢ 5♤ 6♤ 9♡", "3♡ 3♤ 5♧ 6♢ 9♢"], + best: "3♡ 3♤ 5♧ 6♢ 9♢" + ), + ( + name: "pair beats lower", + hands: ["4♢ 3♤ 4♤ J♤ K♤", "A♡ K♡ J♢ 10♧ 9♡"], + best: "4♢ 3♤ 4♤ J♤ K♤" + ), + ( + name: "best pair", + hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "3♢ 3♡ 5♤ 6♤ 9♡"], + best: "4♡ 2♡ 5♧ 4♢ 10♡" + ), + ( + name: "best pair with same pair and highest cards", + hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♤ 4♧ 5♡ 10♢ 3♡"], + best: "4♤ 4♧ 5♡ 10♢ 3♡" + ), + ( + name: "two pair beats lower", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "2♢ 8♡ 5♢ 2♡ 8♧" + ), + ( + name: "best two pair", + hands: [ + "4♢ J♧ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "4♢ J♧ 4♤ J♤ K♤" + ), + ( + name: "best two pair with equal highest pair", + hands: [ + "4♢ J♧ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "3♢ J♡ 5♢ 3♡ J♢", + ], + best: "4♢ J♧ 4♤ J♤ K♤" + ), + ( + name: "best two pair with equal pairs", + hands: [ + "4♢ J♧ 4♤ J♤ 2♤", + "A♡ K♡ J♢ 10♧ 9♡", + "4♧ J♡ 5♢ 4♡ J♢", + ], + best: "4♧ J♡ 5♢ 4♡ J♢" + ), + ( + name: "full house", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "A♡ K♡ J♢ 10♧ 9♡", + "3♡ 8♡ 3♢ 3♧ 8♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "3♡ 8♡ 3♢ 3♧ 8♧" + ), + ( + name: "best three of a kind", + hands: [ + "4♢ 3♤ 4♤ J♤ 4♡", + "A♡ K♡ J♢ 10♧ 9♡", + "3♢ 8♡ 3♡ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "4♢ 3♤ 4♤ J♤ 4♡" + ), + ( + name: "straight beats lower", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♡ 8♡ 3♢ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "Q♡ K♡ J♢ 10♧ 9♡" + ), + ( + name: "straight includes ace as one", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "2♤ 3♡ A♤ 5♤ 4♤", + "3♢ 8♡ 3♡ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "2♤ 3♡ A♤ 5♤ 4♤" + ), + ( + name: "best straight", + hands: [ + "4♢ 3♤ 4♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "A♢ K♧ 10♢ J♢ Q♢", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "A♢ K♧ 10♢ J♢ Q♢" + ), + ( + name: "flush beats lower", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 8♡ 3♢ 3♧ 9♧", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "4♤ 3♤ 8♤ J♤ K♤" + ), + ( + name: "best flush", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 8♢ A♢ 2♢ 7♢", + "2♢ 8♡ 5♢ 2♡ 8♧", + ], + best: "3♢ 8♢ A♢ 2♢ 7♢" + ), + ( + name: "full house beats lower", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♡ A♡ 3♢ 3♧ A♧", + ], + best: "2♢ 8♡ 8♢ 2♡ 8♧" + ), + ( + name: "best full house", + hands: [ + "4♤ 3♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "5♡ 5♢ A♤ 5♧ A♢", + "3♡ A♡ 3♢ 3♧ A♧", + ], + best: "2♢ 8♡ 8♢ 2♡ 8♧" + ), + ( + name: "four of a kind beats lower", + hands: [ + "4♤ 5♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 3♡ 3♤ 3♧ A♧", + ], + best: "3♢ 3♡ 3♤ 3♧ A♧" + ), + ( + name: "best four of a kind", + hands: [ + "4♤ 5♤ 8♤ J♤ K♤", + "2♢ 2♧ 8♢ 2♡ 2♤", + "Q♡ K♡ J♢ 10♧ 9♡", + "3♢ 3♡ 3♤ 3♧ A♧", + ], + best: "3♢ 3♡ 3♤ 3♧ A♧" + ), + ( + name: "straight flush beats lower", + hands: [ + "4♤ 4♢ 4♡ 4♧ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ 8♡ 10♡ 9♡", + "2♤ 3♤ A♤ 5♤ 4♤", + ], + best: "2♤ 3♤ A♤ 5♤ 4♤" + ), + ( + name: "best straight flush is royal flush", + hands: [ + "4♤ 5♤ 8♤ J♤ K♤", + "2♢ 8♡ 8♢ 2♡ 8♧", + "Q♡ K♡ J♡ 10♡ 9♡", + "Q♢ K♢ J♢ 10♢ A♢", + ], + best: "Q♢ K♢ J♢ 10♢ A♢" + ), + ( + name: "tie for best pair: brake tide by suit", + hands: ["4♡ 2♡ 5♧ 4♢ 10♡", "4♧ 10♢ 5♤ 2♤ 4♤"], + best: "4♡ 2♡ 5♧ 4♢ 10♡" + ), + ( + name: "tie of three: brake tide by suit", + hands: [ + "A♡ 2♡ 3♡ 4♡ 5♡", + "A♤ 2♤ 3♤ 4♤ 5♤", + "5♧ 4♧ 3♧ 2♧ A♧", + "A♢ 2♢ 6♢ 4♢ 5♢", + ], + best: "A♤ 2♤ 3♤ 4♤ 5♤" + ), + ] + + invalidTestCases = [ + ( + name: "1 is an invalid card rank", + hand: "1♢ 2♡ 3♡ 4♡ 5♡" + ), + ( + name: "15 is an invalid card rank", + hand: "15♢ 2♡ 3♡ 4♡ 5♡" + ), + ( + name: "too few cards", + hand: "2♡ 3♡ 4♡ 5♡" + ), + ( + name: "too many cards", + hand: "2♡ 3♡ 4♡ 5♡ 6♡ 7♡" + ), + ( + name: "lack of rank", + hand: "11♢ 2♡ ♡ 4♡ 5♡" + ), + ( + name: "lack of suit", + hand: "2♡ 3♡ 4 5♡ 7♡" + ), + ( + name: "H is an invalid suit", + hand: "2♡ 3♡ 4H 5♡ 7♡" + ), + ( + name: "♥ is an invalid suit", + hand: "2♡ 3♡ 4♥ 5♡ 7♡" + ), + ( + name: "lack of spacing", + hand: "2♡ 3♡ 5♡7♡ 8♡" + ), + ( + name: "double suits after rank", + hand: "2♡ 3♡ 5♡♡ 8♡ 9♡" + ), + ] } - - } diff --git a/exercises/prime-factors/PrimeFactorsExample.swift b/exercises/prime-factors/PrimeFactorsExample.swift index 5f2c0ea2b..e0da14f07 100644 --- a/exercises/prime-factors/PrimeFactorsExample.swift +++ b/exercises/prime-factors/PrimeFactorsExample.swift @@ -1,21 +1,16 @@ // Foundation not needed - - - struct PrimeFactors{ - - var number:Int64 - + var number: Int64 var toArray = [Int64]() - - private func primesFor( number:Int64)->[Int64]{ + + private func primesFor(number: Int64) -> [Int64] { var number = number var primes = [Int64]() - var divisor:Int64 = 2 - - while (number > 1){ - while (number % divisor == 0){ + var divisor: Int64 = 2 + + while (number > 1) { + while (number % divisor == 0) { primes.append(divisor) number /= divisor } @@ -23,14 +18,9 @@ struct PrimeFactors{ } return primes } - - init(_ value:Int64){ - self.number = value - self.toArray = primesFor(value) - + + init(_ value: Int64){ + self.number = value + self.toArray = primesFor(value) } } - - - - diff --git a/exercises/prime-factors/PrimeFactorsTest.swift b/exercises/prime-factors/PrimeFactorsTest.swift index 7f570c672..ffbd33d35 100644 --- a/exercises/prime-factors/PrimeFactorsTest.swift +++ b/exercises/prime-factors/PrimeFactorsTest.swift @@ -1,55 +1,47 @@ import XCTest - - - class PrimeFactorsTest: XCTestCase { - func test1() { XCTAssertEqual([], PrimeFactors(1).toArray) } - + func test2() { XCTAssertEqual([2] , PrimeFactors(2).toArray) } - + func test3() { XCTAssertEqual([3], PrimeFactors(3).toArray) } - + func test4() { XCTAssertEqual([2, 2], PrimeFactors(4).toArray) } - + func test6() { XCTAssertEqual([2, 3], PrimeFactors(6).toArray) } - + func test8() { XCTAssertEqual([2, 2, 2], PrimeFactors(8).toArray) } - + func test9() { XCTAssertEqual([3, 3], PrimeFactors(9).toArray) } - + func test27() { XCTAssertEqual([3, 3, 3], PrimeFactors(27).toArray) } - + func test625() { XCTAssertEqual([5, 5, 5, 5], PrimeFactors(625).toArray) } - + func test901255() { XCTAssertEqual([5, 17, 23, 461], PrimeFactors(901_255).toArray) } - + func test93819012551() { XCTAssertEqual([11, 9539, 894_119], PrimeFactors(93_819_012_551).toArray) } - - - } - diff --git a/exercises/pythagorean-triplet/PythagoreanTripletExample.swift b/exercises/pythagorean-triplet/PythagoreanTripletExample.swift index f481e23f7..cebf86b6a 100644 --- a/exercises/pythagorean-triplet/PythagoreanTripletExample.swift +++ b/exercises/pythagorean-triplet/PythagoreanTripletExample.swift @@ -1,30 +1,28 @@ import Darwin - - struct Triplet { - var a:Int, b:Int, c:Int = 0 - + init(_ a:Int, _ b:Int, _ c:Int){ self.a = a self.b = b self.c = c } - + var sum:Int{return a + b + c } - + var product:Int{return a * b * c } - + var isPythagorean:Bool{return pow(Double(a), 2) + pow(Double(b), 2) == pow(Double(c), 2)} - + static func Where(minFactor:Int = 1, maxFactor:Int, sum:Int = 0)->[Triplet]{ - + func shouldIncludeTriplet(sum:Int, triplet:Triplet)-> Bool { return triplet.isPythagorean && (sum == 0 || triplet.sum == sum) } - + var triplets = [Triplet]() + for i in minFactor ..< maxFactor - 1 { for j in i + 1 ..< maxFactor { for k in j + 1 ... maxFactor { @@ -35,7 +33,7 @@ struct Triplet { } } } + return triplets; } - } diff --git a/exercises/pythagorean-triplet/PythagoreanTripletTest.swift b/exercises/pythagorean-triplet/PythagoreanTripletTest.swift index 1b88a09e9..ebd49de18 100644 --- a/exercises/pythagorean-triplet/PythagoreanTripletTest.swift +++ b/exercises/pythagorean-triplet/PythagoreanTripletTest.swift @@ -1,44 +1,37 @@ - import XCTest - - - class PythagoreanTripletTest: XCTestCase { func testSum() { XCTAssertEqual(12, Triplet(3, 4, 5).sum) } - + func testProduct() { XCTAssertEqual(60, Triplet(3, 4, 5).product) } - + func testPythagorean() { XCTAssertTrue(Triplet(3, 4, 5).isPythagorean) } - + func testNotPythagorean() { XCTAssertTrue(!Triplet(5, 6, 7).isPythagorean) } - + func testTripletsUpTo10() { let triplets = Triplet.Where(maxFactor: 10) let products = triplets.map{$0.product}.sort(<) XCTAssertEqual([60, 480], products) } - + func testTripletsFrom11UpTo20() { let triplets = Triplet.Where(11, maxFactor: 20) let products = triplets.map{$0.product}.sort(<) XCTAssertEqual([3840], products) } - + func testTripletsWhereSumX() { let triplets = Triplet.Where( maxFactor: 100, sum: 180) let products = triplets.map{$0.product}.sort(<) XCTAssertEqual([118_080, 168_480, 202_500], products) } - - } - diff --git a/exercises/queen-attack/QueenAttackExample.swift b/exercises/queen-attack/QueenAttackExample.swift index 92111dc8e..73d05080b 100644 --- a/exercises/queen-attack/QueenAttackExample.swift +++ b/exercises/queen-attack/QueenAttackExample.swift @@ -1,59 +1,56 @@ // Foundation not needed - - struct Queens { - #if swift(>=3.0) enum InitError: ErrorProtocol { - case SameSpace - case IncorrectNumberOfCoordinates - case InvalidCoordinates - } - #else - enum InitError: ErrorType { case SameSpace case IncorrectNumberOfCoordinates case InvalidCoordinates } + #else + enum InitError: ErrorType { + case SameSpace + case IncorrectNumberOfCoordinates + case InvalidCoordinates + } #endif - - + let white: [Int] let black: [Int] var canAttack: Bool { return onHorizontal || onVertical || onDiagonal } - + private var onHorizontal: Bool { return white[0] == black[0] } + private var onVertical: Bool { return white[1] == black[1] } + private var onDiagonal: Bool { return abs(black[1] - black[0]) == abs(white[1] - white[0]) } - + init(white: [Int] = [0, 3], black: [Int] = [7, 3]) throws { guard white.count == 2 && black.count == 2 else { throw InitError.IncorrectNumberOfCoordinates } - + for number in white + black { guard number >= 0 && number <= 7 else { throw InitError.InvalidCoordinates } } - + guard white != black else { throw InitError.SameSpace } - + self.white = white self.black = black } - } extension Queens: CustomStringConvertible { @@ -64,25 +61,24 @@ extension Queens: CustomStringConvertible { #else let row = [String](count: 8, repeatedValue: "_") var board = [[String]](count: 8, repeatedValue: row) - + #endif - + board[white[0]][white[1]] = "W" board[black[0]][black[1]] = "B" - + var rows = [String]() + #if swift(>=3.0) - for row in board { - rows.append(row.joined(separator: " ")) + rows.append(row.joined(separator: " ")) } return rows.joined(separator: "\n") #else for row in board { - rows.append(row.joinWithSeparator(" ")) + rows.append(row.joinWithSeparator(" ")) } return rows.joinWithSeparator("\n") #endif - } -} \ No newline at end of file +} diff --git a/exercises/queen-attack/QueenAttackTest.swift b/exercises/queen-attack/QueenAttackTest.swift index ad0a538dc..b6fd1f2f5 100644 --- a/exercises/queen-attack/QueenAttackTest.swift +++ b/exercises/queen-attack/QueenAttackTest.swift @@ -1,38 +1,35 @@ import XCTest - - class QueenAttackTest: XCTestCase { - func testDefaultPositions() { let queens = try! Queens() XCTAssertEqual([0, 3], queens.white) XCTAssertEqual([7, 3], queens.black) } - + func testSpecificPlacement() { let queens = try! Queens(white: [3, 7], black: [6, 1]) XCTAssertEqual([3, 7], queens.white) XCTAssertEqual([6, 1], queens.black) } - + func testMultipleBoardsSimultaneously() { let queens1 = try! Queens(white: [3, 7], black: [6, 1]) let queens2 = try! Queens(white: [5, 4], black: [7, 7]) - + XCTAssertEqual([3, 7], queens1.white) XCTAssertEqual([6, 1], queens1.black) XCTAssertEqual([5, 4], queens2.white) XCTAssertEqual([7, 7], queens2.black) } - + func testIncorrectNumberOfCoordinates() { var throwsIncorrectNumberOfCoordinates = false - + defer { XCTAssertTrue(throwsIncorrectNumberOfCoordinates) } - + do { let _ = try Queens(white: [1, 2, 3], black: [4, 5]) } catch Queens.InitError.IncorrectNumberOfCoordinates { @@ -41,14 +38,14 @@ class QueenAttackTest: XCTestCase { return } } - + func testInvalidCoordinates() { var throwsInvalidCoordinates = false - + defer { XCTAssertTrue(throwsInvalidCoordinates) } - + do { let _ = try Queens(white: [-3, 0], black: [2, 481]) } catch Queens.InitError.InvalidCoordinates { @@ -57,14 +54,14 @@ class QueenAttackTest: XCTestCase { return } } - + func testCannotOccupySameSpace() { var throwsSameSpaceError = false - + defer { XCTAssertTrue(throwsSameSpaceError) } - + do { let _ = try Queens(white: [2, 4], black: [2, 4]) } catch Queens.InitError.SameSpace { @@ -73,7 +70,7 @@ class QueenAttackTest: XCTestCase { return } } - + func testStringRepresentation() { let queens = try! Queens(white: [2, 4], black: [6, 6]) let board = "_ _ _ _ _ _ _ _\n" + @@ -99,7 +96,7 @@ class QueenAttackTest: XCTestCase { "_ W _ _ _ _ _ _" XCTAssertEqual(board, queens.description) } - + func testYetAnotherStringRepresentation() { let queens = try! Queens(white: [4, 3], black: [3, 4]) let board = "_ _ _ _ _ _ _ _\n" + @@ -112,39 +109,39 @@ class QueenAttackTest: XCTestCase { "_ _ _ _ _ _ _ _" XCTAssertEqual(board, queens.description) } - + func testCannotAttack() { let queens = try! Queens(white: [2, 3], black: [4, 7]) XCTAssertFalse(queens.canAttack) } - + func testCanAttackOnSameRow() { let queens = try! Queens(white: [2, 4], black: [2, 7]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnSameColumn() { let queens = try! Queens(white: [5, 4], black: [2, 4]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnDiagonal() { let queens = try! Queens(white: [1, 1], black: [6, 6]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnOtherDiagonal() { let queens = try! Queens(white: [0, 6], black: [1, 7]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnYetAnotherDiagonal() { let queens = try! Queens(white: [4, 1], black: [6, 3]) XCTAssertTrue(queens.canAttack) } - + func testCanAttackOnADiagonalSlantedTheOtherWay() { let queens = try! Queens(white: [6, 1], black: [1, 6]) XCTAssertTrue(queens.canAttack) } -} \ No newline at end of file +} diff --git a/exercises/raindrops/RaindropsExample.swift b/exercises/raindrops/RaindropsExample.swift index 9db9d0782..4373f6456 100644 --- a/exercises/raindrops/RaindropsExample.swift +++ b/exercises/raindrops/RaindropsExample.swift @@ -1,12 +1,9 @@ // Foundation not needed - - struct Raindrops { - private var drops:Int var sounds:String = "" - + private func convert(number:Int)->String{ let result = (number % 3, number % 5 , number % 7) switch result{ @@ -20,10 +17,9 @@ struct Raindrops { default:return "\(number)" } } - + init(_ value:Int){ self.drops = value self.sounds = convert(value) } } - diff --git a/exercises/raindrops/RaindropsTest.swift b/exercises/raindrops/RaindropsTest.swift index c2132543e..a912ec464 100644 --- a/exercises/raindrops/RaindropsTest.swift +++ b/exercises/raindrops/RaindropsTest.swift @@ -1,73 +1,67 @@ import XCTest - - - class RaindropsTest: XCTestCase { - func test1() { XCTAssertEqual("1", Raindrops(1).sounds) } - + func test3() { XCTAssertEqual("Pling", Raindrops(3).sounds) } - + func test5() { XCTAssertEqual("Plang", Raindrops(5).sounds) } - + func test7() { XCTAssertEqual("Plong", Raindrops(7).sounds) } - + func test6() { XCTAssertEqual("Pling", Raindrops(6).sounds) } - + func test9() { XCTAssertEqual("Pling", Raindrops(9).sounds) } - + func test10() { XCTAssertEqual("Plang", Raindrops(10).sounds) } - + func test14() { XCTAssertEqual("Plong", Raindrops(14).sounds) } - + func test15() { XCTAssertEqual("PlingPlang", Raindrops(15).sounds) } - + func test21() { XCTAssertEqual("PlingPlong", Raindrops(21).sounds) } - + func test25() { XCTAssertEqual("Plang", Raindrops(25).sounds) } - + func test35() { XCTAssertEqual("PlangPlong", Raindrops(35).sounds) } - + func test49() { XCTAssertEqual("Plong", Raindrops(49).sounds) } - + func test52() { XCTAssertEqual("52", Raindrops(52).sounds) } - + func test105() { XCTAssertEqual("PlingPlangPlong", Raindrops(105).sounds) } - + func test12121() { XCTAssertEqual("12121", Raindrops(12_121).sounds) } - } - diff --git a/exercises/rna-transcription/RnaTranscriptionExample.swift b/exercises/rna-transcription/RnaTranscriptionExample.swift index 2fc845c0b..26021e5b5 100644 --- a/exercises/rna-transcription/RnaTranscriptionExample.swift +++ b/exercises/rna-transcription/RnaTranscriptionExample.swift @@ -1,15 +1,14 @@ // Foundation not needed struct Nucleotide { - var complementOfDNA:String{ return transcribe(dnaToRna) } - + private let value:String - + init(_ nucleotide:String){ self.value = nucleotide } - + private let dnaToRna:[Character:String] = [ "G": "C" , "C": "G" , "T": "A" , "A": "U" ] private func transcribe(dict:[Character : String]) -> String{ diff --git a/exercises/rna-transcription/RnaTranscriptionTest.swift b/exercises/rna-transcription/RnaTranscriptionTest.swift index 46bae0f29..66d104409 100644 --- a/exercises/rna-transcription/RnaTranscriptionTest.swift +++ b/exercises/rna-transcription/RnaTranscriptionTest.swift @@ -1,26 +1,23 @@ - import XCTest class RnaTranscriptionTest: XCTestCase { - func testRnaComplementOfCytosineIsGuanine() { XCTAssertEqual("G", Nucleotide("C").complementOfDNA) } - + func testRnaComplementOfGuanineIsCytosine() { XCTAssertEqual("C", Nucleotide("G").complementOfDNA) } - + func testRnaComplementOfThymineIsAdenine() { XCTAssertEqual("A", Nucleotide("T").complementOfDNA) } - + func testRnaComplementOfAdenineIsUracil() { XCTAssertEqual("U", Nucleotide("A").complementOfDNA) } - + func testRnaComplement() { XCTAssertEqual("UGCACCAGAAUU", Nucleotide("ACGTGGTCTTAA").complementOfDNA) } - } diff --git a/exercises/robot-name/RobotNameExample.swift b/exercises/robot-name/RobotNameExample.swift index 3c321f650..b2e06e58f 100644 --- a/exercises/robot-name/RobotNameExample.swift +++ b/exercises/robot-name/RobotNameExample.swift @@ -1,10 +1,8 @@ import Darwin - - struct Robot { var name: String - + init() { let numberPart = (Int(rand()) % 899) + 100 name = generateRandomLetter() + generateRandomLetter() + "\(numberPart)" diff --git a/exercises/robot-name/RobotNameTest.swift b/exercises/robot-name/RobotNameTest.swift index b61afb6a2..214a53e03 100644 --- a/exercises/robot-name/RobotNameTest.swift +++ b/exercises/robot-name/RobotNameTest.swift @@ -1,9 +1,6 @@ import XCTest - - class RobotNameTest: XCTestCase { - func robotNameIsCorrectlyFormatted(name: String) -> Bool { let robotNameRegex = try? NSRegularExpression(pattern: "\\A\\w{2}\\d{3}\\z", options: NSRegularExpressionOptions.CaseInsensitive) guard let matches = robotNameRegex?.matchesInString(name, options: .WithoutAnchoringBounds, range: NSMakeRange(0, name.characters.count)) else { return false } diff --git a/exercises/robot-simulator/RobotSimulatorExample.swift b/exercises/robot-simulator/RobotSimulatorExample.swift index ea96e727d..d10ab50c7 100644 --- a/exercises/robot-simulator/RobotSimulatorExample.swift +++ b/exercises/robot-simulator/RobotSimulatorExample.swift @@ -1,35 +1,32 @@ // Foundation not needed - - struct SimulatedRobot { - enum Direction { case North case East case South case West - + static let allValues: [Direction] = [.North, .East, .South, .West] } - + enum Instruction: String { case TurnLeft = "L" case TurnRight = "R" case Advance = "A" } - + var bearing: Direction = .North var x: Int = 0 var y: Int = 0 var coordinates: [Int] { return [x, y] } - + mutating func orient(bearing: Direction) { self.bearing = bearing } - + mutating func turnRight() { if let index = Direction.allValues.indexOf(bearing) { var newIndex = index + 1 @@ -39,7 +36,7 @@ struct SimulatedRobot { bearing = Direction.allValues[newIndex] } } - + mutating func turnLeft() { if let index = Direction.allValues.indexOf(bearing) { var newIndex = index - 1 @@ -49,51 +46,49 @@ struct SimulatedRobot { bearing = Direction.allValues[newIndex] } } - + mutating func at(x x: Int, y: Int) { self.x = x self.y = y } - + mutating func advance() { switch bearing { // Note: ++ and -- will be deprecated in Swift 2.2 and removed in Swift 3.0 - // See https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md - case .North: y += 1 - case .East: x += 1 - case .South: y -= 1 - case .West: x -= 1 + // See https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md + case .North: y += 1 + case .East: x += 1 + case .South: y -= 1 + case .West: x -= 1 } } - + func instructions(instructions: String) -> [Instruction] { var result = [Instruction]() - + let characters = instructions.characters.map { String($0) } - + for character in characters { if let instruction = Instruction(rawValue: character) { result.append(instruction) } } - + return result } - + mutating func place(x x: Int, y: Int, direction: Direction) { at(x: x, y: y) orient(direction) } - + mutating func evaluate(commands: String) { for instruction in instructions(commands) { switch instruction { - case .TurnLeft: turnLeft() - case .TurnRight: turnRight() - case .Advance: advance() + case .TurnLeft: turnLeft() + case .TurnRight: turnRight() + case .Advance: advance() } } } - } - diff --git a/exercises/robot-simulator/RobotSimulatorTest.swift b/exercises/robot-simulator/RobotSimulatorTest.swift index cc4e81331..1073a0227 100644 --- a/exercises/robot-simulator/RobotSimulatorTest.swift +++ b/exercises/robot-simulator/RobotSimulatorTest.swift @@ -1,16 +1,13 @@ import XCTest - - class RobotSimulatorTest: XCTestCase { - - var robot = SimulatedRobot() - + var robot = SimulatedRobot() + func testRobotBearingEast() { robot.orient(.East) XCTAssertEqual([.East], [robot.bearing]) } - + func testRobotBearingWest() { robot.orient(.West) XCTAssertEqual([.West], [robot.bearing]) @@ -20,54 +17,54 @@ class RobotSimulatorTest: XCTestCase { robot.orient(.North) XCTAssertEqual([.North], [robot.bearing]) } - + func testRobotBearingSouth() { robot.orient(.South) XCTAssertEqual([.South], [robot.bearing]) } - + func testTurnRightFromNorth() { robot.orient(.North) robot.turnRight() XCTAssertEqual([.East], [robot.bearing]) } - + func testTurnRightFromEast() { robot.orient(.East) robot.turnRight() XCTAssertEqual([.South], [robot.bearing]) } - + func testTurnRightFromSouth() { robot.orient(.South) robot.turnRight() XCTAssertEqual([.West], [robot.bearing]) } - + func testTurnRightFromWest() { robot.orient(.West) robot.turnRight() XCTAssertEqual([.North], [robot.bearing]) } - + func testTurnLeftFromNorth() { robot.orient(.North) robot.turnLeft() XCTAssertEqual([.West], [robot.bearing]) } - + func testTurnLeftFromEast() { robot.orient(.East) robot.turnLeft() XCTAssertEqual([.North], [robot.bearing]) } - + func testTurnLeftFromSouth() { robot.orient(.South) robot.turnLeft() XCTAssertEqual([.East], [robot.bearing]) } - + func testTurnLeftFromWest() { robot.orient(.West) robot.turnLeft() @@ -78,65 +75,65 @@ class RobotSimulatorTest: XCTestCase { robot.at(x: 3, y: 0) XCTAssertEqual([3, 0], robot.coordinates) } - + func testOtherRobotCoordinates() { robot.at(x: -2, y: 5) XCTAssertEqual([-2, 5], robot.coordinates) } - + func testAdvanceWhenFacingNorth() { robot.at(x: 0, y: 0) robot.orient(.North) robot.advance() XCTAssertEqual([0, 1], robot.coordinates) } - + func testAdvanceWhenFacingEast() { robot.at(x: 0, y: 0) robot.orient(.East) robot.advance() XCTAssertEqual([1, 0], robot.coordinates) } - + func testAdvanceWhenFacingSouth() { robot.at(x: 0, y: 0) robot.orient(.South) robot.advance() XCTAssertEqual([0, -1], robot.coordinates) } - + func testAdvanceWhenFacingWest() { robot.at(x: 0, y: 0) robot.orient(.West) robot.advance() XCTAssertEqual([-1, 0], robot.coordinates) } - + func testInstructionForTurningLeft() { XCTAssertEqual([.TurnLeft], robot.instructions("L")) } - + func testInstructionForTurningRight() { XCTAssertEqual([.TurnRight], robot.instructions("R")) } - + func testInstructionForAdvancing() { XCTAssertEqual([.Advance], robot.instructions("A")) } - + func testSeriesOfInstructions() { XCTAssertEqual([.TurnRight, .Advance, .Advance, .TurnLeft], robot.instructions("RAAL")) } - + func testInstructRobot() { var robot = SimulatedRobot() robot.place(x: -2, y: 1, direction: .East) robot.evaluate("RLAALAL") - + XCTAssertEqual([0, 2], robot.coordinates) XCTAssertEqual([.West], [robot.bearing]) } - + func testInstructManyRobots() { var robot1 = SimulatedRobot() var robot2 = SimulatedRobot() @@ -147,15 +144,14 @@ class RobotSimulatorTest: XCTestCase { robot1.evaluate("LAAARALA") robot2.evaluate("RRAAAAALA") robot3.evaluate("LAAARRRALLLL") - + XCTAssertEqual([-4, 1], robot1.coordinates) XCTAssertEqual([.West], [robot1.bearing]) - + XCTAssertEqual([-3, -8], robot2.coordinates) XCTAssertEqual([.South], [robot2.bearing]) - + XCTAssertEqual([11, 5], robot3.coordinates) XCTAssertEqual([.North], [robot3.bearing]) } - } diff --git a/exercises/roman-numerals/RomanNumeralsExample.swift b/exercises/roman-numerals/RomanNumeralsExample.swift index 602423a1c..d31316cf8 100644 --- a/exercises/roman-numerals/RomanNumeralsExample.swift +++ b/exercises/roman-numerals/RomanNumeralsExample.swift @@ -1,19 +1,15 @@ // Foundation not needed - - extension String{ - - init(_ value:RomanNumeral){ + init(_ value: RomanNumeral) { self = value.romanNumeral - } + } } -struct RomanNumeral{ - +struct RomanNumeral { var romanNumeral:String = "" - - private func toRomanNumerals(input:Int) ->String{ + + private func toRomanNumerals(input:Int) -> String { var arabicToRoman = [1000: "M", 900: "CM", 500: "D", 400: "CD", 100: "C", 90: "XC", 50: "L", 40: "XL", 10: "X", 9: "IX", 5: "V", 4: "IV", 1: "I"] var i = input var s = "" @@ -25,12 +21,8 @@ struct RomanNumeral{ } return s } - - init(_ value:Int){ - + + init(_ value:Int) { self.romanNumeral = toRomanNumerals(value) } - - } - diff --git a/exercises/roman-numerals/RomanNumeralsTest.swift b/exercises/roman-numerals/RomanNumeralsTest.swift index 61f7bf5f7..424941106 100644 --- a/exercises/roman-numerals/RomanNumeralsTest.swift +++ b/exercises/roman-numerals/RomanNumeralsTest.swift @@ -1,79 +1,75 @@ import XCTest - - -class RomanNumeralsTest: XCTestCase { - +class RomanNumeralsTest: XCTestCase { func test1() { XCTAssertEqual("I", String(RomanNumeral(1))) } - + func test2() { XCTAssertEqual("II", String(RomanNumeral(2))) } - + func test3() { XCTAssertEqual("III", String(RomanNumeral(3))) } - + func test4() { XCTAssertEqual("IV", String(RomanNumeral(4))) } - + func test5() { XCTAssertEqual("V", String(RomanNumeral(5))) } - + func test6() { XCTAssertEqual("VI", String(RomanNumeral(6))) } - + func test9() { XCTAssertEqual("IX", String(RomanNumeral(9))) } - + func test27() { XCTAssertEqual("XXVII", String(RomanNumeral(27))) } - + func test48() { XCTAssertEqual("XLVIII", String(RomanNumeral(48))) } - + func test59() { XCTAssertEqual("LIX", String(RomanNumeral(59))) } - + func test93() { XCTAssertEqual("XCIII", String(RomanNumeral(93))) } - + func test141() { XCTAssertEqual("CXLI", String(RomanNumeral(141))) } - + func test163() { XCTAssertEqual("CLXIII", String(RomanNumeral(163))) } - + func test402() { XCTAssertEqual("CDII", String(RomanNumeral(402))) } - + func test575() { XCTAssertEqual("DLXXV", String(RomanNumeral(575))) } - + func test911() { XCTAssertEqual("CMXI", String(RomanNumeral(911))) } - + func test1024() { XCTAssertEqual("MXXIV", String(RomanNumeral(1024))) } - + func test3000() { XCTAssertEqual("MMM", String(RomanNumeral(3000))) } - } diff --git a/exercises/saddle-points/SaddlePointsExample.swift b/exercises/saddle-points/SaddlePointsExample.swift index b4f833ef0..74f5f54a6 100644 --- a/exercises/saddle-points/SaddlePointsExample.swift +++ b/exercises/saddle-points/SaddlePointsExample.swift @@ -1,40 +1,37 @@ // Foundation not needed - - struct SaddlePointsMatrix { - let rows: [[Int]] let columns: [[Int]] let saddlePoints: [[Int]] - + init(_ matrix: String) { var rows = [[Int]]() - + let rowItems = matrix.characters.split("\n").map { String($0) } - + for row in rowItems { let rowItems = row.characters.split(" ").map { Int(String($0)) ?? 0 } rows.append(rowItems) } - + self.rows = rows - + var columns = [[Int]]() - + let count = rows[0].count for i in 0..Bool{ + func containsCustom(input: Character) -> Bool { #if swift(>=3.0) return contains(String(input)) #else return containsString(String(input)) #endif } - - func lowercasedCustom()->String{ + + func lowercasedCustom() -> String { #if swift(>=3.0) return lowercased() #else return lowercaseString #endif } - - private func stripCharacters(charsToRemove:String) -> String{ + + private func stripCharacters(charsToRemove: String) -> String { var returnString = "" - self.characters.forEach{ - if !charsToRemove.containsCustom($0){ + self.characters.forEach { + if !charsToRemove.containsCustom($0) { returnString.append($0) - }} + } + } return returnString } - var stripWhiteSpace:String { + + var stripWhiteSpace: String { return stripCharacters(" ") - } - - var IsEmptyOrWhiteSpace:Bool { get { - return self.stripWhiteSpace.isEmpty - }}} + } + var IsEmptyOrWhiteSpace: Bool { + get { + return self.stripWhiteSpace.isEmpty + } + } +} -struct Scrabble{ - +struct Scrabble { static var letterScores = - [ "a": 1 , "e": 1 , "i": 1 , "o": 1 , "u": 1 , "l": 1 , "n": 1 , "r": 1 , "s": 1 , "t": 1 , "d": 2 , "g": 2 , "b": 3 , "c": 3 , "m": 3 , "p": 3 , "f": 4 , "h": 4 , "v": 4 , "w": 4 , "y": 4 , "k": 5 , "j": 8 , "x": 8 , "q": 10 , "z": 10 ] - - - + [ "a": 1 , "e": 1 , "i": 1 , "o": 1 , "u": 1 , "l": 1 , "n": 1 , "r": 1 , "s": 1 , "t": 1 , "d": 2 , "g": 2 , "b": 3 , "c": 3 , "m": 3 , "p": 3 , "f": 4 , "h": 4 , "v": 4 , "w": 4 , "y": 4 , "k": 5 , "j": 8 , "x": 8 , "q": 10 , "z": 10 ] + static func score(input:String) -> Int { if (input.IsEmptyOrWhiteSpace ){ return 0} - + var count:Int = 0 - for each in input.lowercasedCustom().characters{ + for each in input.lowercasedCustom().characters { count += letterScores[String(each)] ?? 0 } return count } - + var word:String = "" - + var score:Int = 0 - + init(_ word:String?) { self.word = word ?? "" self.score = Scrabble.score(word ?? "") - } - -} \ No newline at end of file +} diff --git a/exercises/scrabble-score/ScrabbleScoreTest.swift b/exercises/scrabble-score/ScrabbleScoreTest.swift index cd9e9a6a1..c46920006 100644 --- a/exercises/scrabble-score/ScrabbleScoreTest.swift +++ b/exercises/scrabble-score/ScrabbleScoreTest.swift @@ -1,43 +1,39 @@ import XCTest - - class ScrabbleScoreTest: XCTestCase { - func testEmptyWordScoresZero() { XCTAssertEqual( 0, Scrabble("").score) } - + func testWhitespaceScoresZero() { XCTAssertEqual( 0, Scrabble(" \t\n").score) } - + func testNilScoresZero() { XCTAssertEqual( 0, Scrabble(nil).score) } - + func testScoresVeryShortWord() { XCTAssertEqual( 1, Scrabble("a").score) } - + func testScoresOtherVeryShortWord() { XCTAssertEqual( 4, Scrabble("f").score) } - + func testSimpleWordScoresTheNumberOfLetters() { XCTAssertEqual( 6, Scrabble("street").score) } - + func testComplicatedWordScoresMore() { XCTAssertEqual( 22, Scrabble("quirky").score) } - + func testScoresAreCaseInsensitive() { XCTAssertEqual( 41, Scrabble("OXYPHENBUTAZONE").score) } - + func testConvenientScoring() { XCTAssertEqual( 13, Scrabble.score("alacrity")) } - } diff --git a/exercises/secret-handshake/SecretHandshakeExample.swift b/exercises/secret-handshake/SecretHandshakeExample.swift index e6dcb0361..5ad63b94b 100644 --- a/exercises/secret-handshake/SecretHandshakeExample.swift +++ b/exercises/secret-handshake/SecretHandshakeExample.swift @@ -1,20 +1,17 @@ // Foundation not needed - - struct SecretHandshake{ - var commandValue:Int var commandValues = [1: "wink" , 2: "double blink", 4: "close your eyes" , 8: "jump"] - + init(_ commandValue:Int){ self.commandValue = commandValue } - + var shouldReverse:Bool {return (commandValue & 16) != 0} - + var commands:[String] {return commandsFunc()} - + private func commandsFunc()->[String] { var commands = [String]() for key in Array(commandValues.keys).sort( < ){ @@ -22,7 +19,7 @@ struct SecretHandshake{ commands.append(commandValues[key]!) } } - + if shouldReverse{ return Array(commands.reverse()) } @@ -30,4 +27,4 @@ struct SecretHandshake{ return commands } } -} \ No newline at end of file +} diff --git a/exercises/secret-handshake/SecretHandshakeTests.swift b/exercises/secret-handshake/SecretHandshakeTests.swift index 430ca08b1..d80212806 100644 --- a/exercises/secret-handshake/SecretHandshakeTests.swift +++ b/exercises/secret-handshake/SecretHandshakeTests.swift @@ -1,49 +1,44 @@ - import XCTest - - class SecretHandshakeTests: XCTestCase { - func testHandshake1ToWink() { let handshake = SecretHandshake(1) XCTAssertEqual(["wink"], handshake.commands) } - + func testHandshake10ToDoubleBlink() { let handshake = SecretHandshake(2) XCTAssertEqual(["double blink"], handshake.commands) } - + func testHandshake100ToCloseYourEyes() { let handshake = SecretHandshake(4) XCTAssertEqual(["close your eyes"], handshake.commands) } - + func testHandshake1000ToJump() { let handshake = SecretHandshake(8) XCTAssertEqual(["jump"], handshake.commands) } - + func testHandshake11ToWinkAndDoubleBlink() { let handshake = SecretHandshake(3) XCTAssertEqual(["wink", "double blink"], handshake.commands) } - + func testHandshake10011ToDoubleBlinkAndWink() { let handshake = SecretHandshake(19) XCTAssertEqual(["double blink", "wink"], handshake.commands) } - + func testHandshake11111ToDoubleBlinkAndWink() { let handshake = SecretHandshake(31) let expected = ["jump", "close your eyes", "double blink", "wink"] XCTAssertEqual(expected, handshake.commands) } - + func testNonValidHandshake() { let handshake = SecretHandshake(0) XCTAssertEqual([], handshake.commands) } - -} \ No newline at end of file +} diff --git a/exercises/series/SeriesExample.swift b/exercises/series/SeriesExample.swift index 37b9f2b06..e77f9e261 100644 --- a/exercises/series/SeriesExample.swift +++ b/exercises/series/SeriesExample.swift @@ -1,26 +1,23 @@ // Foundation not needed - - struct Series { - var numberString = "" - + init(_ numString:String){ self.numberString = numString } - + func slices(chunkSize:Int)->[[Int]]{ var numberStringArray = Array(numberString.characters).map{Int("\($0)") ?? 0} let count = numberStringArray.count var start = 0 var end = chunkSize var tempArrayReturn = [[Int]]() - + #if swift(>=3.0) - let enumarated = (0..<(count)).enumerated() + let enumarated = (0..<(count)).enumerated() #else - let enumarated = (0..<(count)).enumerate() + let enumarated = (0..<(count)).enumerate() #endif for (_, _) in enumarated { if end < count+1 { @@ -32,6 +29,4 @@ struct Series { } return tempArrayReturn } - - -} \ No newline at end of file +} diff --git a/exercises/series/SeriesTest.swift b/exercises/series/SeriesTest.swift index 203525e41..1035dfb68 100644 --- a/exercises/series/SeriesTest.swift +++ b/exercises/series/SeriesTest.swift @@ -1,81 +1,76 @@ import XCTest - - - class SeriesTest: XCTestCase { - func testSimpleSlicesOfOne() { let series = Series("01234") XCTAssertEqual([[0], [1], [2], [3], [4]], series.slices(1)) } - + func testSimpleSlicesOfOneAgain() { let series = Series("92834") XCTAssertEqual([[9], [2], [8], [3], [4]], series.slices(1)) } - + func testSimpleSlicesOfTwo() { let series = Series("01234") XCTAssertEqual([[0, 1], [1, 2], [2, 3], [3, 4]], series.slices(2)) } - + func testOtherSlicesOfTwo() { let series = Series("98273463") let expected = [[9, 8], [8, 2], [2, 7], [7, 3], [3, 4], [4, 6], [6, 3]] XCTAssertEqual(expected, series.slices(2)) } - + func testSimpleSlicesOfTwoAgain() { let series = Series("37103") XCTAssertEqual([[3, 7], [7, 1], [1, 0], [0, 3]], series.slices(2)) } - + func testSimpleSlicesOfThree() { let series = Series("01234") XCTAssertEqual([[0, 1, 2], [1, 2, 3], [2, 3, 4]], series.slices(3)) } - + func testSimpleSlicesOfThreeAgain() { let series = Series("31001") XCTAssertEqual([[3, 1, 0], [1, 0, 0], [0, 0, 1]], series.slices(3)) } - + func testOtherSlicesOfThree() { let series = Series("982347") let expected = [[9, 8, 2], [8, 2, 3], [2, 3, 4], [3, 4, 7]] XCTAssertEqual(expected, series.slices(3)) } - + func testSimpleSlicesOfFour() { let series = Series("01234") XCTAssertEqual([[0, 1, 2, 3], [1, 2, 3, 4]], series.slices(4)) } - + func testSimpleSlicesOfFourAgain() { let series = Series("91274") XCTAssertEqual([[9, 1, 2, 7], [1, 2, 7, 4]], series.slices(4)) } - + func testSimpleSlicesOfFive() { let series = Series("01234") XCTAssertEqual([[0, 1, 2, 3, 4]], series.slices(5)) } - + func testSimpleSlicesOfFiveAgain() { let series = Series("81228") XCTAssertEqual([[8, 1, 2, 2, 8]], series.slices(5)) } - + func testSimpleSliceThatBlowsUp() { let series = Series("01234") XCTAssertEqual([],series.slices(6)) } - + func testMoreComplicatedSliceThatBlowsUp() { let sliceString = "01032987583" let series = Series(sliceString) XCTAssertEqual([], series.slices(12)) } - -} \ No newline at end of file +} diff --git a/exercises/sieve/SieveExample.swift b/exercises/sieve/SieveExample.swift index 585fda614..7562c7546 100644 --- a/exercises/sieve/SieveExample.swift +++ b/exercises/sieve/SieveExample.swift @@ -1,27 +1,24 @@ // Foundation not needed - - struct Sieve { var value:Int = 0 init(_ num:Int){ self.value = num } - + var primes:[Int]{return primesFunc(self.value ) } - + func primesFunc(limit:Int) -> [Int]{ - if limit < 2 { return []} else{ - let tempArray = Array(2...limit) + let tempArray = Array(2...limit) return tempArray.filter{Sieve.onlyDivisorSelf($0)} } } - - static func onlyDivisorSelf( number:Int)->Bool{ + + static func onlyDivisorSelf( number:Int)->Bool{ var number = number - + var primes = [Int]() var divisor:Int = 2 while (number > 1){ @@ -33,13 +30,4 @@ struct Sieve { } if primes.count == 1 {return true} else {return false} } - - - - - - - - - -} \ No newline at end of file +} diff --git a/exercises/sieve/SieveTest.swift b/exercises/sieve/SieveTest.swift index 5b1584678..3e3a1a936 100644 --- a/exercises/sieve/SieveTest.swift +++ b/exercises/sieve/SieveTest.swift @@ -1,15 +1,11 @@ - import XCTest - - class SieveTest: XCTestCase { - func testAFewPrimes() { let expected = [2, 3, 5, 7] XCTAssertEqual(expected, Sieve(10).primes) } - + func testPrimes() { let expected = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, @@ -29,5 +25,4 @@ class SieveTest: XCTestCase { ] XCTAssertEqual(expected, Sieve(1000).primes) } - } diff --git a/exercises/simple-cipher/SimpleCipherExample.swift b/exercises/simple-cipher/SimpleCipherExample.swift index c97007afa..a1a745319 100644 --- a/exercises/simple-cipher/SimpleCipherExample.swift +++ b/exercises/simple-cipher/SimpleCipherExample.swift @@ -1,21 +1,17 @@ import Darwin - - func arc4random_uniform(input:Int)->Int{ let temp = UInt32(input) return Int(arc4random_uniform(temp)) } - public struct Cipher { private let abc = "abcdefghijklmnopqrstuvwxyz" private var alphabet:[Character] { return Array(abc.characters) } private(set) var key:String = "" private var keyArray:[Character] { return Array(key.characters) } - - + private func randomKeySet()->String{ var tempKey = "" for _ in (0..<100).enumerate(){ @@ -23,18 +19,16 @@ public struct Cipher } return tempKey } - init(){ key = randomKeySet() } - - + init?(key:String) { if isLowerCaseAlfabet(key){ self.key = key - + if key.isEmpty { return nil } @@ -42,12 +36,11 @@ public struct Cipher //self.key = randomKeySet() // Alternative non Optional faiulure } } - - - func isLowerCaseAlfabet(inkey:String)-> Bool{ + + func isLowerCaseAlfabet(inkey:String)-> Bool{ var valid = true inkey.characters.forEach{ - + if "abcdefghijklmnopqrstuvwxyz".containsString(String($0)) == false { valid = false } @@ -55,56 +48,50 @@ public struct Cipher return valid } - func encode(plaintext:String) ->String { let plainTextArray = Array(plaintext.characters) - + func encodeCharacter(plaintext:String, idx:Int)->Character { //let plainTextArray = Array(plaintext) // hack for subscript support for Strings var alphabetIdx:Int = - (alphabet.indexOf(plainTextArray[idx]) ?? 0) + - (alphabet.indexOf(keyArray[idx]) ?? 0) + (alphabet.indexOf(plainTextArray[idx]) ?? 0) + + (alphabet.indexOf(keyArray[idx]) ?? 0) if alphabetIdx >= alphabet.count { alphabetIdx -= alphabet.count } return alphabet[alphabetIdx] } - + var ciphertext = "" for i in 0 ..< min(plainTextArray.count, keyArray.count) { ciphertext.append(encodeCharacter(plaintext, idx: i)) } return ciphertext } - - - + func decode(ciphertext:String)->String { let cipherTextArray = Array(ciphertext.characters) - + func decodeCharacter(ciphertext:String, idx:Int)-> Character { //let cipherTextArray = Array(ciphertext) // no native subscript for String var alphabetIdx:Int = - (alphabet.indexOf(cipherTextArray[idx]) ?? 0) - - (alphabet.indexOf(keyArray[idx]) ?? 0) + (alphabet.indexOf(cipherTextArray[idx]) ?? 0) - + (alphabet.indexOf(keyArray[idx]) ?? 0) if alphabetIdx < 0{ alphabetIdx += alphabet.count } return alphabet[alphabetIdx] } - - + var plaintext = "" - + for i in 0 ..< cipherTextArray.count { plaintext.append(decodeCharacter(ciphertext, idx: i)) } return plaintext } - - -} \ No newline at end of file +} diff --git a/exercises/simple-cipher/SimpleCipherTest.swift b/exercises/simple-cipher/SimpleCipherTest.swift index 562c28290..8165c29a5 100644 --- a/exercises/simple-cipher/SimpleCipherTest.swift +++ b/exercises/simple-cipher/SimpleCipherTest.swift @@ -1,10 +1,6 @@ - import XCTest - - class SimpleCipherTest: XCTestCase { - func testCipherEncode() { let cipher = Cipher() let plaintext = "aaaaaaaaaa" @@ -25,7 +21,7 @@ class SimpleCipherTest: XCTestCase { XCTAssertEqual(plaintext, cipher.decode(cipher.encode(plaintext))) } -// MARK: TestIncorrectKey + // MARK: TestIncorrectKey func testCipherWithCapsKey() { XCTAssertNil(Cipher(key: "ABCDEF")) @@ -39,7 +35,7 @@ class SimpleCipherTest: XCTestCase { XCTAssertNil(Cipher(key: "")) } -// MARK: TestSubstitution + // MARK: TestSubstitution let cipherSubstitution = Cipher(key: "abcdefghij") ?? Cipher() @@ -76,7 +72,7 @@ class SimpleCipherTest: XCTestCase { XCTAssertEqual(ciphertext, cipherSubstitution.encode(plaintext)) } -// MARK: TestPseudoShift + // MARK: TestPseudoShift let cipherPseudo = Cipher(key: "dddddddddd") ?? Cipher() @@ -96,5 +92,4 @@ class SimpleCipherTest: XCTestCase { let plaintext = "abcdefghij" XCTAssertEqual(plaintext, cipherPseudo.decode(cipherPseudo.encode(plaintext))) } - } diff --git a/exercises/simple-linked-list/SimpleLinkedListExample.swift b/exercises/simple-linked-list/SimpleLinkedListExample.swift index 39a8de3ce..454b56d6a 100644 --- a/exercises/simple-linked-list/SimpleLinkedListExample.swift +++ b/exercises/simple-linked-list/SimpleLinkedListExample.swift @@ -1,14 +1,12 @@ // Foundation not needed - - private extension Array{ func reversedCustom()->Array{ #if swift(>=3.0) - return reversed() + return reversed() #else - return reverse() + return reverse() #endif } } @@ -16,21 +14,20 @@ private extension Array{ class Element { var value: T? = nil var next: Element? = nil - + init() { } - + init(_ value: T, _ next:Element?) { self.value = value self.next = next } - - + func toArray () ->[T] { return toA(self) } - + private var countArray:Array = [] - + private func toA(input:Element, _ tempArray:Array = []) ->[T]{ if tempArray.isEmpty && input.value != nil { countArray.append(input.value!) @@ -41,9 +38,7 @@ class Element { } return countArray } - - - + class func fromArray(input:[T]) ->Element { var tempElement = Element() for each in Array(input.reversedCustom()){ @@ -51,12 +46,8 @@ class Element { } return tempElement } - - - + func reverseElements() -> Element { return Element.fromArray(Array(toArray().reversedCustom())) } - - -} \ No newline at end of file +} diff --git a/exercises/simple-linked-list/SimpleLinkedListTest.swift b/exercises/simple-linked-list/SimpleLinkedListTest.swift index d661698aa..cd168cb19 100644 --- a/exercises/simple-linked-list/SimpleLinkedListTest.swift +++ b/exercises/simple-linked-list/SimpleLinkedListTest.swift @@ -1,12 +1,8 @@ - import XCTest - - // Use Optionals and Generic Classes class SimpleLinkedListTest: XCTestCase { - func testConstructorA() { let one = Element(1, nil) let two = Element(2, one) @@ -14,7 +10,7 @@ class SimpleLinkedListTest: XCTestCase { XCTAssertNil(one.next) XCTAssertEqual(2, two.value!) } - + func testConstructorB() { let one = Element(1, nil) let two = Element(2, one) @@ -22,7 +18,7 @@ class SimpleLinkedListTest: XCTestCase { let result2 = two.next?.value XCTAssertEqual(result!, result2!) } - + func testToA() { let elementNil = Element() let elementOne = Element(1, nil) @@ -33,15 +29,15 @@ class SimpleLinkedListTest: XCTestCase { XCTAssertEqual([2, 1] , elementTwo.toArray() ) XCTAssertEqual([3, 2, 1] , elementThree.toArray()) } - + func testReverseOne() { let one = Element(1, nil) let oneR = one.reverseElements() XCTAssertEqual(1, oneR.value!) XCTAssertNil(oneR.next?.value) - + } - + func testReverseTwo() { let one = Element(1, nil) let two = Element(2, one) @@ -50,36 +46,35 @@ class SimpleLinkedListTest: XCTestCase { let expect = twoR.next?.value XCTAssertEqual(2, expect!) } - + func testFromAOne() { - + XCTAssertNil(Element.fromArray([]).value) let oneA = Element.fromArray([1]) XCTAssertEqual(1, oneA.value!) XCTAssertNil(oneA.next?.value) - + } - + func testFromATwo() { - + let twoA = Element.fromArray([2, 1]) XCTAssertEqual(2, twoA.value!) let expected = twoA.next?.value XCTAssertEqual(1, expected! ) XCTAssertNil(twoA.next?.next?.value) } - + func testFromATen() { - + let oneToTen = Element.fromArray(Array(1...10)) let expected10 = oneToTen.next?.next?.next?.next?.next?.next?.next?.next?.next?.value XCTAssertEqual(10, expected10! ) } - + func testRoundtrip() { XCTAssertEqual([1], Element.fromArray([1]).toArray() ) XCTAssertEqual([2, 1], Element.fromArray([2, 1]).toArray() ) XCTAssertEqual(Array(1...10), Element.fromArray(Array(1...10)).toArray()) } - -} \ No newline at end of file +} diff --git a/exercises/space-age/SpaceAgeExample.swift b/exercises/space-age/SpaceAgeExample.swift index 1c418006b..79d77ebe8 100644 --- a/exercises/space-age/SpaceAgeExample.swift +++ b/exercises/space-age/SpaceAgeExample.swift @@ -1,11 +1,8 @@ import Darwin - - struct SpaceAge{ - var seconds:Float = 0 - + var onMercury:Float { get { return round((seconds / 7_600_530.24)*100)/100}} var onVenus:Float { get { return round((seconds / 19_413_907.2)*100)/100}} var onEarth:Float { get { return round((seconds / 31_558_149.76)*100)/100}} @@ -14,13 +11,8 @@ struct SpaceAge{ var onSaturn:Float { get { return round((seconds / 929_596_608.0)*100)/100}} var onUranus:Float { get { return round((seconds / 2_661_041_808.0)*100)/100}} var onNeptune:Float { get { return round((seconds / 5_200_418_592.0)*100)/100}} - - + init(_ input:Float){ - self.seconds = input - } - } - diff --git a/exercises/space-age/SpaceAgeTest.swift b/exercises/space-age/SpaceAgeTest.swift index 1a2c38b32..b00d69081 100644 --- a/exercises/space-age/SpaceAgeTest.swift +++ b/exercises/space-age/SpaceAgeTest.swift @@ -1,60 +1,55 @@ - import XCTest - - class SpaceAgeTest: XCTestCase { - func testAgeInSeconds() { let age = SpaceAge(1_000_000) XCTAssertTrue(1_000_000 == age.seconds) } - + func testAgeInEarthYears() { let age = SpaceAge(1_000_000_000) XCTAssertTrue(31.69 == age.onEarth) } - + func testAgeInMercuryYears() { let age = SpaceAge(2_134_835_688) XCTAssertTrue(67.65 == age.onEarth) XCTAssertTrue(280.88 == age.onMercury) } - + func testAgeInVenusYears() { let age = SpaceAge(189_839_836) XCTAssertTrue(6.02 == age.onEarth) XCTAssertTrue(9.78 == age.onVenus) } - + func testAgeOnMars() { let age = SpaceAge(2_329_871_239) XCTAssertTrue(73.83 == age.onEarth) XCTAssertTrue(39.25 == age.onMars) } - + func testAgeOnJupiter() { let age = SpaceAge(901_876_382) XCTAssertTrue(28.58 == age.onEarth) XCTAssertTrue(2.41 == age.onJupiter) } - + func testAgeOnSaturn() { let age = SpaceAge(3_000_000_000) XCTAssertTrue(95.06 == age.onEarth) XCTAssertTrue(3.23 == age.onSaturn) } - + func testAgeOnUranus() { let age = SpaceAge(3_210_123_456) XCTAssertTrue(101.72 == age.onEarth) XCTAssertTrue(1.21 == age.onUranus) } - + func testAgeOnNeptune() { let age = SpaceAge(8_210_123_456) XCTAssertTrue(260.16 == age.onEarth) XCTAssertTrue(1.58 == age.onNeptune) } - -} \ No newline at end of file +} diff --git a/exercises/strain/StrainExample.swift b/exercises/strain/StrainExample.swift index b8b27bf1c..580ba34ce 100644 --- a/exercises/strain/StrainExample.swift +++ b/exercises/strain/StrainExample.swift @@ -1,19 +1,17 @@ // Foundation not needed - - extension Array{ - + func keep(compare compare:Bool = true, inputFunc:(Element) -> Bool )->Array { var array2Return:Array = [] for each in self{ if inputFunc(each) == compare{ array2Return.append(each)} - } + } return array2Return } - + func discard(inputFunc:(Element) -> Bool)->Array{ return keep(compare: false, inputFunc: inputFunc) } -} \ No newline at end of file +} diff --git a/exercises/strain/StrainTest.swift b/exercises/strain/StrainTest.swift index 5f455f236..6cb020c8b 100644 --- a/exercises/strain/StrainTest.swift +++ b/exercises/strain/StrainTest.swift @@ -1,32 +1,28 @@ import XCTest - - class StrainTest: XCTestCase { - func testEmptyKeep() { - XCTAssertTrue ([].keep{each -> Bool in each < 10}.isEmpty) } - + func testKeepEverything() { XCTAssertEqual([1, 2, 3], [1, 2, 3].keep{each -> Bool in each < 10}) } - + func testKeepFirstAndLast() { XCTAssertEqual([1, 3], [1, 2, 3].keep{ each -> Bool in (each % 2 != 0)}) } - + func testKeepNeitherFirstNorLast() { XCTAssertEqual([2, 4], [1, 2, 3, 4, 5].keep{ each -> Bool in (each % 2 == 0) }) } - + func testKeepStrings() { let words = ["apple", "zebra", "banana", "zombies", "cherimoya", "zealot"] let result = words.keep{each -> Bool in (each as String).hasPrefix("z") ?? false} XCTAssertEqual(["zebra", "zombies", "zealot"], result) } - + func testKeepArrays () { let rows = [ [1, 2, 3], @@ -40,29 +36,29 @@ class StrainTest: XCTestCase { let result = rows.keep{ each -> Bool in (each as [Int]).contains(5)} XCTAssertEqual([[5, 5, 5], [5, 1, 2], [1, 5, 2], [1, 2, 5]], result) } - + func testEmptyDiscard() { XCTAssertEqual([], [].discard {each -> Bool in each < 10}) } - + func testDiscardNothing() { XCTAssertEqual([1, 2, 3], [1, 2, 3].discard {each -> Bool in each > 10}) } - + func testDiscardFirstAndLast() { XCTAssertEqual([2], [1, 2, 3].discard {each -> Bool in (each % 2 != 0)}) } - + func testDiscardNeitherFirstNorLast() { XCTAssertEqual([1, 3, 5], [1, 2, 3, 4, 5].discard{ each -> Bool in (each % 2 == 0)}) } - + func testDiscardStrings() { let words = ["apple", "zebra", "banana", "zombies", "cherimoya", "zealot"] let result = words.discard{each -> Bool in (each as String).hasPrefix("z") ?? false} XCTAssertEqual(["apple", "banana", "cherimoya"], result) } - + func testDiscardArrays () { let rows = [ [1, 2, 3], @@ -76,6 +72,4 @@ class StrainTest: XCTestCase { let result = rows.discard { each -> Bool in (each as [Int]).contains(5)} XCTAssertEqual([[1, 2, 3], [2, 1, 2], [2, 2, 1]], result) } - } - diff --git a/exercises/sum-of-multiples/SumOfMultiplesExample.swift b/exercises/sum-of-multiples/SumOfMultiplesExample.swift index 08d1d8ffe..c2bbd9729 100644 --- a/exercises/sum-of-multiples/SumOfMultiplesExample.swift +++ b/exercises/sum-of-multiples/SumOfMultiplesExample.swift @@ -1,16 +1,15 @@ // Foundation not needed struct SumOfMultiples { - static func toLimit(limit: Int, inMultiples: [Int]) -> Int { var multiples = Set(inMultiples) - + if let indexOfZero = multiples.indexOf(0) { multiples.removeAtIndex(indexOfZero) } - + var itemToReturn = 0 - + for each in 1.. String{ let removeSpaces = trimCharacters(" ", sourceText: self) if removeSpaces.hasSuffix("\n"){ return String(removeSpaces.characters.dropLast()) } return removeSpaces - } - + func trimCharacters(charToTrim:Character, sourceText:String) -> String{ var editCharacterView = sourceText.characters var editString = String(editCharacterView) - + let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim - + if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } - + if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } @@ -39,21 +35,21 @@ struct Tournament case WIN case ERR } - + struct TeamResult { var Losses:Int = 0 var Draws:Int = 0 var Wins:Int = 0 - + var Played:Int { return Losses + Draws + Wins } - + var Score:Int { return Wins * 3 + Draws } - + mutating func addOutcome( outcome:Outcome )-> Void { switch outcome { @@ -68,67 +64,65 @@ struct Tournament } } } - + private var teams = Dictionary() - - + private mutating func addResult(team1 team1:String, team2:String, outcome:Outcome) -> Void { // Invert outcome for the second team. let outcome2:Outcome = (outcome == Outcome.WIN) ? Outcome.LOSS : (outcome == Outcome.LOSS) ? Outcome.WIN : Outcome.DRAW - - + + addTeamOutcome(team1, outcome) addTeamOutcome(team2, outcome2) } - + private var teamResult = TeamResult() - + private mutating func addTeamOutcome(team:String, _ outcome:Outcome) -> Void { if teams[team] != nil { teamResult = teams[team]! teamResult.addOutcome(outcome) teams[team] = teamResult - + } else { teamResult = TeamResult() teamResult.addOutcome(outcome) teams[team] = teamResult } } - + private mutating func writeResults()-> String { - + func formarter (Team:String, MP:String, W:String, D:String, L:String, P:String)->String{ - + func wsChars(text:String, spacing:Int = 31)->String{ return Repeat(count:abs(spacing - Array(text.characters).count) , repeatedValue: " ").joinWithSeparator("") } - + func spacing(text:String, columnWith:Int = 4)->String{ let textCount = Array(text.characters).count let space = Int(round(Double(textCount) / Double(columnWith))) - + return wsChars(text, spacing: columnWith - space - textCount) + text + wsChars(text, spacing: space ) } - + let text = "\(Team)" + wsChars(Team) + "|" + spacing(MP) + "|" + spacing(W) + "|" + spacing(D) + "|" + spacing(L) + "|" + spacing(P) - + return text.trimWhiteSpace() + "\n" - + } - + var textOutput:String = "" - + let header = formarter("Team", MP: "MP", W: "W", D: "D", L: "L", P: "P") - + textOutput += header - - + func sortKeysByValue()->[String] { var sortByValue = [(String, Int)]() @@ -141,43 +135,43 @@ struct Tournament for each in sortByValue{ sortedKeys.append(each.0) } - + return sortedKeys } - + for team in sortKeysByValue(){ - + let result = teams[team]! - + let MP = result.Played let W = result.Wins let D = result.Draws let L = result.Losses let P = result.Score - - + + let line = formarter(team, - MP: "\(MP)", - W: "\(W)", - D: "\(D)", - L: "\(L)", - P: "\(P)") - + MP: "\(MP)", + W: "\(W)", + D: "\(D)", + L: "\(L)", + P: "\(P)") + textOutput += line } return textOutput.trimWhiteSpace() } - + func tally(inStream:String) -> String { // Create New Tournament var tournament = Tournament() - + var outcome:Outcome = Outcome.ERR - + // alternative to .componentsSeparatedByString let textArrayLines = inStream.characters.split {$0 == "\n"}.map { String($0) } - + for line in textArrayLines { let parts = line.trimWhiteSpace().componentsSeparatedByString(";") @@ -194,7 +188,7 @@ struct Tournament default: outcome = Outcome.ERR } - + if outcome != Outcome.ERR { tournament.addResult(team1: parts[0], team2: parts[1], outcome: outcome) @@ -204,13 +198,4 @@ struct Tournament return tournament.writeResults() } - - - } - - - - - - diff --git a/exercises/tournament/TournamentTest.swift b/exercises/tournament/TournamentTest.swift index 21f58cde1..2c1a103b4 100644 --- a/exercises/tournament/TournamentTest.swift +++ b/exercises/tournament/TournamentTest.swift @@ -1,20 +1,16 @@ import XCTest - - - class TournamentTest:XCTestCase { - let input1 = - "Allegoric Alaskians;Blithering Badgers;win\n" + + "Allegoric Alaskians;Blithering Badgers;win\n" + "Devastating Donkeys;Courageous Californians;draw\n" + "Devastating Donkeys;Allegoric Alaskians;win\n" + "Courageous Californians;Blithering Badgers;loss\n" + "Blithering Badgers;Devastating Donkeys;loss\n" + - "Allegoric Alaskians;Courageous Californians;win" - + "Allegoric Alaskians;Courageous Californians;win" + let input2 = - "Allegoric Alaskians;Blithering Badgers;win\n" + + "Allegoric Alaskians;Blithering Badgers;win\n" + "Devastating Donkeys_Courageous Californians;draw\n" + "Devastating Donkeys;Allegoric Alaskians;win\n" + "\n" + @@ -23,38 +19,35 @@ class TournamentTest:XCTestCase { "Blithering Badgers;Devastating Donkeys;loss\n" + "# Yackity yackity yack\n" + "Allegoric Alaskians;Courageous Californians;win\n" + - "Devastating Donkeys;Courageous Californians;draw" - + "Devastating Donkeys;Courageous Californians;draw" + let input3 = - "Allegoric Alaskians;Blithering Badgers;win\n" + + "Allegoric Alaskians;Blithering Badgers;win\n" + "Devastating Donkeys;Allegoric Alaskians;win\n" + "Courageous Californians;Blithering Badgers;loss\n" + - "Allegoric Alaskians;Courageous Californians;win" - - + "Allegoric Alaskians;Courageous Californians;win" + let expected1 = "Team | MP | W | D | L | P\n" + "Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" + "Allegoric Alaskians | 3 | 2 | 0 | 1 | 6\n" + "Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" + "Courageous Californians | 3 | 0 | 1 | 2 | 1" - + let expected2 = "Team | MP | W | D | L | P\n" + "Devastating Donkeys | 3 | 2 | 1 | 0 | 7\n" + "Allegoric Alaskians | 3 | 2 | 0 | 1 | 6\n" + "Blithering Badgers | 3 | 1 | 0 | 2 | 3\n" + "Courageous Californians | 3 | 0 | 1 | 2 | 1" - + let expected3 = "Team | MP | W | D | L | P\n" + "Allegoric Alaskians | 3 | 2 | 0 | 1 | 6\n" + "Blithering Badgers | 2 | 1 | 0 | 1 | 3\n" + "Devastating Donkeys | 1 | 1 | 0 | 0 | 3\n" + "Courageous Californians | 2 | 0 | 0 | 2 | 0" - - func testGoodInput() { let tournament = Tournament() XCTAssertEqual(tournament.tally(input1), expected1) @@ -64,10 +57,9 @@ class TournamentTest:XCTestCase { let tournament = Tournament() XCTAssertEqual(tournament.tally(input2), expected2) } - + func testinCompleteCompetition() { let tournament = Tournament() XCTAssertEqual(tournament.tally(input3), expected3) } - } diff --git a/exercises/triangle/TriangleExample.swift b/exercises/triangle/TriangleExample.swift index 8bffb81b0..bcd978212 100644 --- a/exercises/triangle/TriangleExample.swift +++ b/exercises/triangle/TriangleExample.swift @@ -1,60 +1,53 @@ // Foundation not needed - - let triangleKind = (Equilateral:"Equilateral",Isosceles:"Isosceles",Scalene:"Scalene",ErrorKind:"ErrorKind") - struct Triangle { - var a:Double = 0 var b:Double = 0 var c:Double = 0 - + var kind:String { get { return self.Kind() }} - + init(_ a:Double, _ b:Double, _ c:Double){ (self.a,self.b,self.c) = (a,b,c) - + } - + func uniqueSides() -> Int{ var tempSet = Set() for each in [a,b,c]{ - tempSet.insert(each) + tempSet.insert(each) } - + return tempSet.count } - - + func allSidesAreZero() -> Bool{ return a == 0 && b == 0 && c == 0 } - + func hasImpossibleSides() -> Bool{ return a < 0 || b < 0 || c < 0 } - + func violatesTriangleInequality() -> Bool{ return a + b < c || a + c < b || b + c < a } - + func Kind()->String{ - if (allSidesAreZero() || hasImpossibleSides() || violatesTriangleInequality()) { return triangleKind.ErrorKind } - + let unique = uniqueSides() - + if (unique == 1){ return triangleKind.Equilateral} - + if (unique == 2){ return triangleKind.Isosceles} - + return triangleKind.Scalene } - -} \ No newline at end of file +} diff --git a/exercises/triangle/TriangleTest.swift b/exercises/triangle/TriangleTest.swift index 17a41e57e..7226c7cba 100644 --- a/exercises/triangle/TriangleTest.swift +++ b/exercises/triangle/TriangleTest.swift @@ -1,71 +1,61 @@ import XCTest - - - class TriangleTest: XCTestCase { - let triangleKind = (Equilateral:"Equilateral",Isosceles:"Isosceles",Scalene:"Scalene",ErrorKind:"ErrorKind") - - + func testEquilateralTrianglesHaveEqualSides() { XCTAssertEqual(triangleKind.Equilateral, Triangle(2, 2, 2).kind) } - + func testLargerEquilateralTrianglesAlsoHaveEqualSides() { XCTAssertEqual(triangleKind.Equilateral, Triangle(10, 10, 10).kind) } - + func testIsoscelesTrianglesHaveLastTwoSidesEqual() { XCTAssertEqual(triangleKind.Isosceles, Triangle(3, 4, 4).kind) } - + func testIsoscelesTrianglesHaveFirstAndLastSidesEqual() { XCTAssertEqual(triangleKind.Isosceles, Triangle(4, 3, 4).kind) } - + func testIsoscelesTrianglesHaveTwoFirstSidesEqual() { XCTAssertEqual(triangleKind.Isosceles, Triangle(4, 4, 3).kind) } - + func testIsoscelesTrianglesHaveInFactExactlyTwoSidesEqual() { XCTAssertEqual(triangleKind.Isosceles, Triangle(10, 10, 2).kind) } - + func testScaleneTrianglesHaveNoEqualSides() { XCTAssertEqual(triangleKind.Scalene, Triangle(3, 4, 5).kind) } - + func testScaleneTrianglesHaveNoEqualSidesAtALargerScaleToo() { XCTAssertEqual(triangleKind.Scalene, Triangle(10, 11, 12).kind) } - + func testScaleneTrianglesHaveNoEqualSidesInDescendingOrderEither() { XCTAssertEqual(triangleKind.Scalene, Triangle(5, 4, 2).kind) } - + func testVerySmallTrianglesAreLegal() { XCTAssertEqual(triangleKind.Scalene, Triangle(0.4, 0.6, 0.3).kind) } - + func testTrianglesWithNoSizeAreIllegal() { XCTAssertEqual(triangleKind.ErrorKind, Triangle(0, 0, 0).kind) } - + func testTrianglesWithNegativeSidesAreIllegal() { XCTAssertEqual(triangleKind.ErrorKind, Triangle(3, 4, -5).kind) } - + func testTrianglesViolatingTriangleInequalityAreIllegal() { XCTAssertEqual(triangleKind.ErrorKind, Triangle(1, 1, 3).kind) } - - - + func testTrianglesViolatingTriangleInequalityAreIllegal3() { XCTAssertEqual(triangleKind.ErrorKind, Triangle(7, 3, 2).kind) } - - } - diff --git a/exercises/trinary/TrinaryExample.swift b/exercises/trinary/TrinaryExample.swift index e1214e6e5..5150b269d 100644 --- a/exercises/trinary/TrinaryExample.swift +++ b/exercises/trinary/TrinaryExample.swift @@ -1,46 +1,41 @@ import Darwin - - extension Int{ init(_ value:Trinary){ self = value.toDecimal } } - struct Trinary { - private var stringValue = "" - private var toDecimal:Int = 0 - private func isValidTrinary() -> Bool{ + private var stringValue = "" + private var toDecimal:Int = 0 + + private func isValidTrinary() -> Bool{ return (Int(stringValue) ?? -1) > -1 ? true : false } - + private func tri2int(input:String)->Int{ #if swift(>=3.0) - let orderedInput = Array(input.characters.reversed()) - let enumarated = orderedInput.enumerated() + let orderedInput = Array(input.characters.reversed()) + let enumarated = orderedInput.enumerated() #else - let orderedInput = Array(input.characters.reverse()) - let enumarated = orderedInput.enumerate() + let orderedInput = Array(input.characters.reverse()) + let enumarated = orderedInput.enumerate() #endif var tempInt:Int = 0 for (inx,each) in enumarated{ let tempCharInt = Int("\(each)") ?? 0 let tempTriPower = Int(pow(Double(3),Double(inx))) - tempInt += tempTriPower * tempCharInt + tempInt += tempTriPower * tempCharInt } return tempInt } - - + init( _ sv:String){ self.stringValue = sv - + if isValidTrinary() { self.toDecimal = tri2int(sv) } - } - -} \ No newline at end of file +} diff --git a/exercises/trinary/TrinaryTest.swift b/exercises/trinary/TrinaryTest.swift index 668316c0b..806f9e3a4 100644 --- a/exercises/trinary/TrinaryTest.swift +++ b/exercises/trinary/TrinaryTest.swift @@ -1,46 +1,39 @@ import XCTest - - - class TrinaryTest: XCTestCase { - func testTrinary1IsDecimal1() { XCTAssertEqual(1, Int(Trinary("1"))) } - + func testTrinary2IsDecimal2() { XCTAssertEqual(2, Int(Trinary("2"))) } - + func testTrinary10IsDecimal3() { XCTAssertEqual(3, Int(Trinary("10"))) } - + func testTrinary11IsDecimal4() { XCTAssertEqual(4, Int(Trinary("11"))) } - + func testTrinary100IsDecimal9() { XCTAssertEqual(9, Int(Trinary("100"))) } - + func testTrinary112IsDecimal14() { XCTAssertEqual(14, Int(Trinary("112"))) } - + func testTrinary222Is26() { XCTAssertEqual(26, Int(Trinary("222"))) } - + func testTrinary1122000120Is32091() { XCTAssertEqual(32091, Int(Trinary("1122000120"))) } - + func testInvalidTrinaryIsDecimal0() { XCTAssertEqual(0, Int(Trinary("carrot"))) } - - - } - +} diff --git a/exercises/twelve-days/TwelveDaysExample.swift b/exercises/twelve-days/TwelveDaysExample.swift index ef9a9a5d4..10e78d4e2 100644 --- a/exercises/twelve-days/TwelveDaysExample.swift +++ b/exercises/twelve-days/TwelveDaysExample.swift @@ -1,24 +1,21 @@ // Foundation not needed - - struct TwelveDaysSong { - static func sing() -> String{ return verses(1,12) } - + static func verses(start:Int, _ end:Int) ->String{ var string2return = "" for each in start...end{ string2return += verse(each) + "\n" } - + return string2return } + static func verse(number:Int) ->String{ - switch(number) - { + switch(number) { case 1: return "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n" case 2: @@ -47,5 +44,4 @@ struct TwelveDaysSong { return "" } } - -} \ No newline at end of file +} diff --git a/exercises/twelve-days/TwelveDaysTest.swift b/exercises/twelve-days/TwelveDaysTest.swift index 33cd0caef..eea4703e1 100644 --- a/exercises/twelve-days/TwelveDaysTest.swift +++ b/exercises/twelve-days/TwelveDaysTest.swift @@ -1,83 +1,78 @@ import XCTest - - - class TwelveDaysTest: XCTestCase { - - func testVerse1() { let expected = "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(1) XCTAssertEqual(expected, result) } - + func testVerse2() { let expected = "On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(2) XCTAssertEqual(expected, result) } - + func testVerse3() { let expected = "On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(3) XCTAssertEqual(expected, result) } - + func testVerse4() { let expected = "On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(4) XCTAssertEqual(expected, result) } - + func testVerse5() { let expected = "On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(5) XCTAssertEqual(expected, result) } - + func testVerse6() { let expected = "On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(6) XCTAssertEqual(expected, result) } - + func testVerse7() { let expected = "On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(7) XCTAssertEqual(expected, result) } - + func testVerse8() { let expected = "On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(8) XCTAssertEqual(expected, result) } - + func testVerse9() { let expected = "On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(9) XCTAssertEqual(expected, result) } - + func testVerse10() { let expected = "On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(10) XCTAssertEqual(expected, result) } - + func testVerse11() { let expected = "On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(11) XCTAssertEqual(expected, result) } - + func testVerse12() { let expected = "On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.\n" let result = TwelveDaysSong.verse(12) XCTAssertEqual(expected, result) } - + func testMultipleVerses() { let expected = ( "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree.\n\n" + @@ -86,13 +81,8 @@ class TwelveDaysTest: XCTestCase { let result = TwelveDaysSong.verses(1, 3) XCTAssertEqual(expected, result) } - + func testTheWholeSong() { - XCTAssertEqual(TwelveDaysSong.verses(1, 12), TwelveDaysSong.sing()) - } - - - } diff --git a/exercises/word-count/WordCountExample.swift b/exercises/word-count/WordCountExample.swift index 058fa4fe4..e0cfd820d 100644 --- a/exercises/word-count/WordCountExample.swift +++ b/exercises/word-count/WordCountExample.swift @@ -1,14 +1,11 @@ // Foundation not needed - - struct WordCount { - func splitStringToArray(inString:String) -> [String]{ - + return inString.characters.split(isSeparator: { splitAt($0) }).map{String($0)} } - + func splitAt(characterToCompare:Character, charToSplitAt:String = " !&$%^&,:")-> Bool{ for each in charToSplitAt.characters{ if each == characterToCompare{ @@ -17,27 +14,25 @@ struct WordCount { } return false } - + let words: String - + init(words: String) { self.words = words } - + func count() -> [String: Int] { var dict = [String:Int]() let cleanArray = splitStringToArray(words) - + cleanArray.forEach { string in if !string.isEmpty { if let count = dict[string.lowercaseString] { dict[string.lowercaseString] = count + 1 } else { dict[string.lowercaseString] = 1 } - } - } - return dict + } } + return dict + } } - - diff --git a/exercises/word-count/WordCountTest.swift b/exercises/word-count/WordCountTest.swift index 5208b4fa4..fe93987bc 100644 --- a/exercises/word-count/WordCountTest.swift +++ b/exercises/word-count/WordCountTest.swift @@ -1,56 +1,51 @@ import XCTest - - - class WordCountTest: XCTestCase { - func testCountOneWord() { let words = WordCount(words: "word") let expected = ["word": 1] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testCountOneOfEeach() { let words = WordCount(words: "one of each") let expected = ["one" : 1, "of" : 1, "each" : 1 ] let result = words.count(); - + XCTAssertEqual(expected, result) } - + func testCountMultipleOccurrences() { let words = WordCount(words: "one fish two fish red fish blue fish") let expected = ["one" : 1, "fish" : 4, "two" : 1, "red" : 1, "blue" : 1 ] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testIgnorePunctation() { let words = WordCount(words: "car : carpet as java : javascript!!&$%^&") let expected = ["car" : 1, "carpet" : 1, "as" : 1, "java" : 1, "javascript" : 1 ] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testIncludeNumbers() { let words = WordCount(words: "testing, 1, 2 testing") let expected = [ "testing" : 2, "1" : 1, "2" : 1 ] let result = words.count() - + XCTAssertEqual(expected, result) } - + func testNormalizeCase() { let words = WordCount(words:"go Go GO") let expected = [ "go" : 3] let result = words.count() - + XCTAssertEqual(expected, result) } - } diff --git a/exercises/wordy/WordyExample.swift b/exercises/wordy/WordyExample.swift index 7017f5f81..6eb500da8 100644 --- a/exercises/wordy/WordyExample.swift +++ b/exercises/wordy/WordyExample.swift @@ -1,9 +1,6 @@ // Foundation not needed - - private extension String { - func trimWhiteSpace()-> String{ let removeSpaces = trimCharacters(" ", sourceText: self) if removeSpaces.hasSuffix("\n"){ @@ -11,109 +8,106 @@ private extension String { } return removeSpaces } - + func trimCharacters(charToTrim:Character, sourceText:String) -> String{ var editCharacterView = sourceText.characters var editString = String(editCharacterView) - + let trimFirst = sourceText.characters.first == charToTrim let trimLast = sourceText.characters.last == charToTrim - + if trimFirst { editCharacterView = editCharacterView.dropFirst() } if trimLast { editCharacterView = editCharacterView.dropLast() } - + if trimFirst || trimLast == true { editString = trimCharacters(charToTrim, sourceText: String(editCharacterView)) } return editString } - + func replacingOccurrencesCustom(of:String, with: String) -> String { #if swift(>=3.0) - return replacingOccurrences(of: of, with: with) + return replacingOccurrences(of: of, with: with) #else - return stringByReplacingOccurrencesOfString(of, withString: with) + return stringByReplacingOccurrencesOfString(of, withString: with) #endif } - + func componentsSeparatedByStringCustom(input:String)->Array { #if swift(>=3.0) - return componentsSeparated(by: input) + return componentsSeparated(by: input) #else - return componentsSeparatedByString(input) + return componentsSeparatedByString(input) #endif } - } - #if swift(>=3.0) enum calculateError:ErrorProtocol{ - case error + case error } #else enum calculateError:ErrorType{ - case error + case error } #endif struct WordProblem { var textIn = "" - + init(_ text:String){ self.textIn = text } - + private let operans = ["plus" : "+", - "minus" : "-", - "multiplied by" : "*", - "divided by" : "/"] - + "minus" : "-", + "multiplied by" : "*", + "divided by" : "/"] + private let funcs = ["+":{(a:Int, b:Int) -> Int in return a + b}, - "-":{(a:Int, b:Int) -> Int in return a - b}, - "*":{(a:Int, b:Int) -> Int in return a * b}, - "/":{(a:Int, b:Int) -> Int in return a / b}] - - + "-":{(a:Int, b:Int) -> Int in return a - b}, + "*":{(a:Int, b:Int) -> Int in return a * b}, + "/":{(a:Int, b:Int) -> Int in return a / b}] + + func answer() throws -> Int{ guard let toReturn = calculate(textIn) else { throw calculateError.error } return toReturn } - + func calculate(textIn:String) ->Int?{ let calcStack = replaceText(textIn).componentsSeparatedByStringCustom(" ") - + if calcStack.count == 3 { let a = Int(calcStack[0]) let operA = funcs[calcStack[1]] let b = Int(calcStack[2]) - + if a != nil || operA != nil || b == nil { return operA!(a!, b!) } } - + if calcStack.count == 5 { let a = Int(calcStack[0]) let operA = funcs[calcStack[1]] let b = Int(calcStack[2]) let operB = funcs[calcStack[3]] let c = Int(calcStack[4]) - + if a != nil || operA != nil || b == nil || operB != nil || c != nil { - - let left = operA!(a!, b!) - return operB!(left, c!) } + + let left = operA!(a!, b!) + return operB!(left, c!) } } return nil } - - + private func replaceText( textInp:String)-> String{ var textInp = textInp for key in Array(operans.keys){ @@ -121,10 +115,10 @@ struct WordProblem { let toReplaceValue = operans[key]! textInp = textInp.replacingOccurrencesCustom(toBeReplaced, with: toReplaceValue) } - + func checkCharInSet(input:Character)->Bool{ #if swift(>=3.0) - let temp = " 0987654321+-*/".characters.index(of: input) + let temp = " 0987654321+-*/".characters.index(of: input) #else let temp = " 0987654321+-*/".characters.indexOf(input) #endif @@ -133,16 +127,14 @@ struct WordProblem { } else { return true} } - + var newTextIn = Array(textInp.characters) newTextIn = newTextIn.filter(checkCharInSet) let newTextInString:[String] = newTextIn.map{String($0)} #if swift(>=3.0) - return newTextInString.joined(separator: "").trimWhiteSpace() + return newTextInString.joined(separator: "").trimWhiteSpace() #else - return newTextInString.joinWithSeparator("").trimWhiteSpace() + return newTextInString.joinWithSeparator("").trimWhiteSpace() #endif } - - } \ No newline at end of file diff --git a/exercises/wordy/WordyTest.swift b/exercises/wordy/WordyTest.swift index 271b880c8..8cd50f7a5 100644 --- a/exercises/wordy/WordyTest.swift +++ b/exercises/wordy/WordyTest.swift @@ -1,74 +1,76 @@ import XCTest - - // Use error handeling class WordyTest: XCTestCase { - + func testAdd1() { XCTAssertEqual(2, try? WordProblem("What is 1 plus 1?").answer()) } - + func testAdd2() { XCTAssertEqual(55, try? WordProblem("What is 53 plus 2?").answer()) } - + func testAddNegativeNumbers() { XCTAssertEqual(-11, try? WordProblem("What is -1 plus -10?").answer()) } - + func testAddMoreDigits() { XCTAssertEqual(45_801, try? WordProblem("What is 123 plus 45678?").answer()) } - + func testSubtract() { XCTAssertEqual(16, try? WordProblem("What is 4 minus -12?").answer()) } - + func testMultiply() { - XCTAssertEqual(-75, try? WordProblem("What is -3 multiplied by 25?").answer()) } - + XCTAssertEqual(-75, try? WordProblem("What is -3 multiplied by 25?").answer()) + } + func testDivide() { - XCTAssertEqual(-11, try? WordProblem("What is 33 divided by -3?").answer()) } - + XCTAssertEqual(-11, try? WordProblem("What is 33 divided by -3?").answer()) + } + func testAddTwice() { let question = "What is 1 plus 1 plus 1?" XCTAssertEqual(3, try? WordProblem(question).answer()) } - + func testAddThenSubtract() { let question = "What is 1 plus 5 minus -2?" XCTAssertEqual(8, try? WordProblem(question).answer()) } - + func testSubtractTwice() { let question = "What is 20 minus 4 minus 13?" XCTAssertEqual(3, try? WordProblem(question).answer()) } - + func testSubtractThenAdd() { let question = "What is 17 minus 6 plus 3?" XCTAssertEqual(14, try? WordProblem(question).answer()) } - + func testMultiplyTwice() { let question = "What is 2 multiplied by -2 multiplied by 3?" - XCTAssertEqual(-12, try? WordProblem(question).answer()) } - + XCTAssertEqual(-12, try? WordProblem(question).answer()) + } + func testAddThenMultiply() { let question = "What is -3 plus 7 multiplied by -2?" - XCTAssertEqual(-8, try? WordProblem(question).answer()) } - + XCTAssertEqual(-8, try? WordProblem(question).answer()) + } + func testDivideTwice() { let question = "What is -12 divided by 2 divided by -3?" XCTAssertEqual(2, try? WordProblem(question).answer()) } - + func testTooAdvanced() { XCTAssertNil(try? WordProblem("What is 53 cubed?").answer()) } - + func testIrrelevant() { - XCTAssertNil(try? WordProblem("Who is the president of the United States?").answer()) } - + XCTAssertNil(try? WordProblem("Who is the president of the United States?").answer()) + } } diff --git a/xcodeProject/xSwift.xcodeproj/project.pbxproj b/xcodeProject/xSwift.xcodeproj/project.pbxproj index d542fb499..db09f4322 100755 --- a/xcodeProject/xSwift.xcodeproj/project.pbxproj +++ b/xcodeProject/xSwift.xcodeproj/project.pbxproj @@ -863,8 +863,8 @@ 1EAF95DF1C90C587009DDCB6 /* dominoes */ = { isa = PBXGroup; children = ( - 1EAF95E01C90C587009DDCB6 /* DominoesTest.swift */, 1E4CC79E1C90D48300C8BBEB /* DominoesExample.swift */, + 1EAF95E01C90C587009DDCB6 /* DominoesTest.swift */, ); path = dominoes; sourceTree = "";