diff --git a/WeeklyChallenge2022.playground/Pages/Challenge0.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge0.xcplaygroundpage/Contents.swift index c0d2703..00b371f 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge0.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge0.xcplaygroundpage/Contents.swift @@ -19,9 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -for index in 1...100 { - let divisibleByThree = index % 3 == 0 - let divisibleByFive = index % 5 == 0 - print("\((divisibleByThree && divisibleByFive) ? "fizzbuzz" : (divisibleByThree ? "fizz" : (divisibleByFive ? "buzz" : index.description)))") -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge1.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge1.xcplaygroundpage/Contents.swift index d123250..b1e25cc 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge1.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge1.xcplaygroundpage/Contents.swift @@ -19,9 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func isAnagram(wordOne: String, wordTwo: String) -> Bool { - return wordOne.lowercased() == wordTwo.lowercased() ? false : wordOne.lowercased().sorted().elementsEqual(wordTwo.lowercased().sorted()) -} - -print(isAnagram(wordOne: "amor", wordTwo: "roma")) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge10.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge10.xcplaygroundpage/Contents.swift index cebcb04..6e970bc 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge10.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge10.xcplaygroundpage/Contents.swift @@ -20,33 +20,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -print(isBalanced(expression: "{a + b [c] * (2x2)}}}}")) -print(isBalanced(expression: "{ [ a * ( c + d ) ] - 5 }")) -print(isBalanced(expression: "{ a * ( c + d ) ] - 5 }")) -print(isBalanced(expression: "{a^4 + (((ax4)}")) -print(isBalanced(expression: "{ ] a * ( c + d ) + ( 2 - 3 )[ - 5 }")) -print(isBalanced(expression: "{{{{{{(}}}}}}")) -print(isBalanced(expression: "(a")) - -func isBalanced(expression: String) -> Bool { - - let symbols = ["{":"}", "[":"]", "(":")"] - var stack = [String]() - - for character in expression { - - let symbol = character.description - let containsKey = symbols.keys.contains(symbol) - - if containsKey || symbols.values.contains(symbol) { - if containsKey { - stack.append(symbol) - } else if stack.isEmpty || symbol != symbols[stack.popLast() ?? ""] { - return false - } - } - } - - return stack.isEmpty -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge11.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge11.xcplaygroundpage/Contents.swift index cca1c7e..52e6ced 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge11.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge11.xcplaygroundpage/Contents.swift @@ -18,34 +18,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func printNonCommon(str1: String, str2: String) { - print("out1: \(findNonCommon(str1: str1, str2: str2))") - print("out2: \(findNonCommon(str1: str2, str2: str1))") -} - -func findNonCommon(str1: String, str2: String) -> String { - - var out = "" - - str1.lowercased().forEach { - if (!str2.lowercased().contains($0)) { - out += $0.description - } - } - - return out -} - -func printNonCommonWithFilter(str1: String, str2: String) { - print("out1: \(str1.lowercased().filter { !str2.lowercased().contains($0) })") - print("out2: \(str2.lowercased().filter { !str1.lowercased().contains($0) })") -} - -printNonCommon(str1: "brais", str2: "moure") -printNonCommon(str1: "Me gusta Objective-C", str2: "Me gusta Swift") -printNonCommon(str1: "Usa el canal de nuestro discord (https://mouredev.com/discord) \"🔁reto-semanal\" para preguntas, dudas o prestar ayuda a la comunidad.", - str2: "Puedes hacer un Fork del repo y una Pull Request al repo original para que veamos tu solución aportada.") - -// Otra solución utilizando funciones de orden superior -printNonCommonWithFilter(str1: "Usa el canal de nuestro discord (https://mouredev.com/discord) \"🔁reto-semanal\" para preguntas, dudas o prestar ayuda a la comunidad.", str2: "Puedes hacer un Fork del repo y una Pull Request al repo original para que veamos tu solución aportada.") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge12.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge12.xcplaygroundpage/Contents.swift index 4c30548..40fb2e7 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge12.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge12.xcplaygroundpage/Contents.swift @@ -19,23 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func isPalindrome(text: String) -> Bool { - - let normalizedText = NSMutableString(string: text.lowercased().folding(options: .diacriticInsensitive, locale: .current)).toRegex(pattern: "[^a-z0-9]", replacement: "") - return normalizedText.description == String(normalizedText.description.reversed()) -} - -extension NSMutableString { - - func toRegex(pattern: String, replacement: String) -> NSMutableString { - let regex = try! NSRegularExpression(pattern: pattern, options: []) - regex.replaceMatches(in: self, options: [], range: NSMakeRange(0, self.length), withTemplate: replacement) - return self - } - -} - -print(isPalindrome(text: "Ana lleva al oso la avellana.")) -print(isPalindrome(text: "Adivina ya te opina, ya ni miles origina, ya ni cetro me domina, ya ni monarcas, a repaso ni mulato carreta, acaso nicotina, ya ni cita vecino, anima cocina, pedazo gallina, cedazo terso nos retoza de canilla goza, de pánico camina, ónice vaticina, ya ni tocino saca, a terracota luminosa pera, sacra nómina y ánimo de mortecina, ya ni giros elimina, ya ni poeta, ya ni vida")) -print(isPalindrome(text: "¿Qué os ha parecido el reto?")) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge13.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge13.xcplaygroundpage/Contents.swift index b90b647..2226e09 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge13.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge13.xcplaygroundpage/Contents.swift @@ -16,13 +16,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func factorial(n: Int) -> Int? { - return n < 0 ? nil : n <= 1 ? 1 : n * (factorial(n: n - 1)!) -} - -print(factorial(n: 0) ?? "No tiene factorial") -print(factorial(n: 7) ?? "No tiene factorial") -print(factorial(n: 10) ?? "No tiene factorial") -print(factorial(n: 1) ?? "No tiene factorial") -print(factorial(n: -1) ?? "No tiene factorial") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge14.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge14.xcplaygroundpage/Contents.swift index c14a3ca..e0e1bac 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge14.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge14.xcplaygroundpage/Contents.swift @@ -17,24 +17,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func isArmstrong(number: Int) -> Bool { - - if number < 0 { - return false - } - - var sum = 0 - let powValue = Double(number.description.count) - - number.description.forEach { character in - sum += Int(pow(Double(character.description) ?? 0, powValue)) - } - - return number == sum -} - -print(isArmstrong(number: 371)) -print(isArmstrong(number: -371)) -print(isArmstrong(number: 372)) -print(isArmstrong(number: 0)) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge15.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge15.xcplaygroundpage/Contents.swift index 9e07a89..0c2f020 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge15.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge15.xcplaygroundpage/Contents.swift @@ -20,40 +20,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -enum DaysBetweenError: Error { - case dateFormat -} - -func daysBetween(firstDate: String, secondDate: String) throws -> Int { - - let formatter = DateFormatter() - formatter.dateFormat = "dd/MM/yyyy" - - let regex = try! NSRegularExpression(pattern: "^([0-9]){2}[/]([0-9]){2}[/]([0-9]){4}$", options: []) - - if regex.firstMatch(in: firstDate, range: NSMakeRange(0, firstDate.count)) != nil, - regex.firstMatch(in: secondDate, range: NSMakeRange(0, secondDate.count)) != nil, - let firstParsedDate = formatter.date(from: firstDate), - let secondParsedDate = formatter.date(from: secondDate), - let days = Calendar.current.dateComponents([.day], from: firstParsedDate, to: secondParsedDate).day { - - return abs(days) - } - - throw DaysBetweenError.dateFormat -} - -func printDaysBetween(firstDate: String, secondDate: String) { - do { - print(try daysBetween(firstDate: firstDate, secondDate: firstDate)) - } catch DaysBetweenError.dateFormat { - print("Error en el formato de alguna fecha") - } catch { - print("Error en el parse de alguna fecha") - } -} - -printDaysBetween(firstDate: "18/05/2022", secondDate: "29/05/2022") -printDaysBetween(firstDate: "mouredev", secondDate: "29/04/2022") -printDaysBetween(firstDate: "18/5/2022", secondDate: "29/04/2022") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge16.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge16.xcplaygroundpage/Contents.swift index 14acef1..910a0c0 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge16.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge16.xcplaygroundpage/Contents.swift @@ -18,26 +18,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func capitalize(text: String) -> String { - - var capitalizedText = text - - let clearText = NSMutableString(string: text) - let regex = try! NSRegularExpression(pattern: "[^A-zÀ-ú]", options: []) - regex.replaceMatches(in: clearText, options: [], range: NSMakeRange(0, clearText.length), withTemplate: " ") - - clearText.components(separatedBy: " ").forEach { word in - - let firstChar = word.prefix(1).description.uppercased() - let otherChars = word.dropFirst() - - capitalizedText = capitalizedText.replacingOccurrences(of: word, with: "\(firstChar)\(otherChars)") - } - - return capitalizedText -} - -print(capitalize(text: "¿hola qué tal estás?")) -print(capitalize(text: "¿hola qué tal estás?")) -print(capitalize(text: "El niño ñoño")) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge17.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge17.xcplaygroundpage/Contents.swift index 94a4349..7de66b9 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge17.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge17.xcplaygroundpage/Contents.swift @@ -27,46 +27,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -enum AthleteState: String { - case run = "_" - case jump = "|" -} - -func checkRace(athlete: [AthleteState], track: String) -> Bool { - - let totalActions = athlete.count > track.count ? athlete.count : track.count - let minActions = athlete.count > track.count ? track.count : athlete.count - - let trackSegments = Array(track) - - var athleteTrack = "" - - for index in (0..= minActions { - athleteTrack += "?" - } else { - let segment = trackSegments[index] - let state = athlete[index] - switch state { - case .run: - athleteTrack += segment.description == state.rawValue ? state.rawValue : "/" - case .jump: - athleteTrack += segment.description == state.rawValue ? state.rawValue : "x" - } - } - } - - print(athleteTrack) - - return track == athleteTrack -} - -print(checkRace(athlete: [.run, .jump, .run, .jump, .run], track: "_|_|_")) -print(checkRace(athlete: [.run, .run, .run, .jump, .run], track: "_|_|_")) -print(checkRace(athlete: [.run, .run, .jump, .jump, .run], track: "_|_|_")) -print(checkRace(athlete: [.run, .run, .jump, .jump, .run], track: "_|_|_|_")) -print(checkRace(athlete: [.run, .jump, .run, .jump], track: "_|_|_")) -print(checkRace(athlete: [.run, .jump, .run, .jump, .run, .jump, .run], track: "_|_|_")) -print(checkRace(athlete: [.jump, .jump, .jump, .jump, .jump], track: "|||||")) -print(checkRace(athlete: [.jump, .jump, .jump, .jump, .jump], track: "||?||")) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge18.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge18.xcplaygroundpage/Contents.swift index e0877ff..5673d50 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge18.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge18.xcplaygroundpage/Contents.swift @@ -21,85 +21,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -enum TicTacToeValue { - case X, O, empty -} - -enum TicTacToeResult { - case X, O, draw, null -} - -func checkTicTacToe(board: [[TicTacToeValue]]) -> TicTacToeResult { - - // Null - - if board.count != 3 { - return .null - } - - var xCount = 0 - var oCount = 0 - - var flatBoard: [TicTacToeValue] = [] - for row in board { - flatBoard.append(contentsOf: row) - - if row.count != 3 { - return .null - } - - for col in row { - if col == .X { - xCount += 1 - } else if col == .O { - oCount += 1 - } - } - } - - if abs(xCount - oCount) > 1 { - return .null - } - - // Win or Draw - - let winCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] - - var result = TicTacToeResult.draw - - for winCombination in winCombinations { - - if flatBoard[winCombination[0]] != .empty - && flatBoard[winCombination[0]] == flatBoard[winCombination[1]] - && flatBoard[winCombination[0]] == flatBoard[winCombination[2]] { - - let winner = flatBoard[winCombination[0]] - - if result != .draw - && (result == .O ? TicTacToeValue.O : TicTacToeValue.X) != winner { - return .null - } - - result = winner == .X ? .X : .O - } - } - - return result -} - -print(checkTicTacToe(board: [[.X, .O, .X], - [.O, .X, .O], - [.O, .O, .X]])) - -print(checkTicTacToe(board: [[.empty, .O, .X], - [.empty, .X, .O], - [.empty, .O, .X]])) - -print(checkTicTacToe(board: [[.O, .O, .O], - [.O, .X, .X], - [.O, .X, .X]])) - -print(checkTicTacToe(board: [[.X, .O, .X], - [.X, .X, .O], - [.X, .X, .X]])) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge19.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge19.xcplaygroundpage/Contents.swift index ce5f7de..0ef88e4 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge19.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge19.xcplaygroundpage/Contents.swift @@ -16,17 +16,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func timeToMillis(days: Int, hours: Int, minutes: Int, seconds: Int) -> Int { - - let daysInMillis = days * 24 * 60 * 60 * 1000 - let hoursInMillis = hours * 60 * 60 * 1000 - let minutesInMillis = minutes * 60 * 1000 - let secondsToMillis = seconds * 1000 - - return daysInMillis + hoursInMillis + minutesInMillis + secondsToMillis -} - -print(timeToMillis(days: 0, hours: 0, minutes: 0, seconds: 10)) -print(timeToMillis(days: 2, hours: 5, minutes: -45, seconds: 10)) -print(timeToMillis(days: 2000000000, hours: 5, minutes: 45, seconds: 10)) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge2.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge2.xcplaygroundpage/Contents.swift index 34a1893..2100b39 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge2.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge2.xcplaygroundpage/Contents.swift @@ -18,14 +18,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -var n0 = 0 -var n1 = 1 - -(1...50).forEach { _ in - print(n0) - - let fib = n0 + n1 - n0 = n1 - n1 = fib -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge20.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge20.xcplaygroundpage/Contents.swift index 5e15f25..cb20925 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge20.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge20.xcplaygroundpage/Contents.swift @@ -18,18 +18,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func asyncSum(numberOne: Int, numberTwo: Int, seconds: Int, result: @escaping (Int) -> Void) { - - DispatchQueue.global().asyncAfter(deadline: .now() + Double(seconds), execute: { - result(numberOne + numberTwo) - }) -} - -asyncSum(numberOne: 5, numberTwo: 2, seconds: 10) { result in - print(result) -} - -asyncSum(numberOne: 1, numberTwo: 3, seconds: 5) { result in - print(result) -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge21.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge21.xcplaygroundpage/Contents.swift index 1bde3db..0fe140e 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge21.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge21.xcplaygroundpage/Contents.swift @@ -22,52 +22,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func calculate(filePath: String, fileType: String) -> String { - - var fileError = false - var result: Double? - var lastOperator: String? - - if let path = Bundle.main.path(forResource: filePath, ofType: fileType) { - do { - let content = try String(contentsOfFile: path, encoding: .utf8).components(separatedBy: "\n") - - for line in content { - if let number = Double(line) { - - if result == nil { - result = number - } else { - switch lastOperator { - case "+": - result! += number - case "-": - result! -= number - case "*": - result! *= number - case "/": - result! /= number - default: - fileError = true - break - } - lastOperator = nil - } - - } else if lastOperator == nil { - lastOperator = line - } else { - fileError = true - break - } - } - } catch { - fileError = true - } - } - - return fileError || lastOperator != nil ? "No se han podido resolver las operaciones" : result!.description -} - -print(calculate(filePath: "Challenge21", fileType: "txt")) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge22.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge22.xcplaygroundpage/Contents.swift index 6f0ae9a..e7a01c8 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge22.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge22.xcplaygroundpage/Contents.swift @@ -19,38 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func calculateSet(first: [Int], second: [Int], common: Bool) -> [Int] { - - var commonResult: [Int] = [] - - for firstValue in first { - if !commonResult.contains(firstValue) { - for secondValue in second { - if firstValue == secondValue && !commonResult.contains(firstValue) { - commonResult.append(firstValue) - break - } - } - } - } - - if common { - return commonResult - } else { - var nonCommonResult: [Int] = [] - nonCommonResult.append(contentsOf: first) - nonCommonResult.append(contentsOf: second) - - commonResult.forEach { commonValue in - nonCommonResult.removeAll { nonCommonValue in - return commonValue == nonCommonValue - } - } - - return nonCommonResult - } -} - -print(calculateSet(first: [1, 2, 3, 3, 4], second: [2, 2, 3, 3, 3, 4, 6], common: true)) -print(calculateSet(first: [1, 2, 3, 3, 4], second: [2, 2, 3, 3, 3, 4, 6], common: false)) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge23.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge23.xcplaygroundpage/Contents.swift index 42a6c4a..34573c3 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge23.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge23.xcplaygroundpage/Contents.swift @@ -17,29 +17,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func mcd(firstNumber: Int, secondNumber: Int) -> Int { - - var a = firstNumber - var b = secondNumber - - while a != 0 && b != 0 { - let temp = b - b = a % b - a = temp - } - - return a + b -} - -func mcm(firstNumber: Int, secondNumber: Int) -> Int { - return (firstNumber * secondNumber) / mcd(firstNumber: firstNumber, secondNumber: secondNumber) -} - -func mcdRecursive(firstNumber: Int, secondNumber: Int) -> Int { - return (firstNumber == 0 || secondNumber == 0) ? (firstNumber + secondNumber) : mcdRecursive(firstNumber: secondNumber, secondNumber: firstNumber % secondNumber) -} - -print(mcd(firstNumber: 56, secondNumber: 180)) -print(mcdRecursive(firstNumber: 56, secondNumber: 180)) -print(mcm(firstNumber: 56, secondNumber: 180)) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge24.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge24.xcplaygroundpage/Contents.swift index 02785b4..a23c5f6 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge24.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge24.xcplaygroundpage/Contents.swift @@ -17,67 +17,3 @@ import Foundation * */ -// 1 - -print("**** 1 ****") - -for index in (1...100) { - print(index) -} - -// 2 - -print("**** 2 ****") - -(1...100).forEach { index in - print(index) -} - -// 3 - -print("**** 3 ****") - -var whileIndex = 1 - -while whileIndex <= 100 { - print(whileIndex) - whileIndex += 1 -} - -// 4 - -print("**** 4 ****") - -whileIndex = 1 - -repeat { - print(whileIndex) - whileIndex += 1 -} while whileIndex <= 100 - -// 5 - -print("**** 5 ****") - -func print100(index: Int) { - if index <= 100 { - print(index) - print100(index: index + 1) - } -} - -print100(index: 1) - -// 6 - -print("**** 6 ****") - -print((1...100).filter { _ -> Bool in - return true -}) - -// 7 - -print("**** 7 ****") - -print((1...100).map { $0 }) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge25.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge25.xcplaygroundpage/Contents.swift index 1056771..241e16f 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge25.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge25.xcplaygroundpage/Contents.swift @@ -20,37 +20,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -enum Move { - case rock, scissors, paper -} - -func rockScissorsPaper(games: [(Move, Move)]) -> String { - - var playerOneGames = 0 - var playerTwoGames = 0 - - games.forEach { playerOneMove, playerTwoMove in - - if (playerOneMove != playerTwoMove) { - - if playerOneMove == .rock && playerTwoMove == .scissors - || playerOneMove == .scissors && playerTwoMove == .paper - || playerOneMove == .paper && playerTwoMove == .rock { - - playerOneGames += 1 - } else { - playerTwoGames += 1 - } - } - } - - return playerOneGames == playerTwoGames ? "Tie" : playerOneGames > playerTwoGames ? "Player 1" : "Player 2" -} - -print(rockScissorsPaper(games: [(.rock, .rock)])) -print(rockScissorsPaper(games: [(.rock, .scissors)])) -print(rockScissorsPaper(games: [(.paper, .scissors)])) -print(rockScissorsPaper(games: [(.rock, .rock), (.scissors, .scissors), (.paper, .paper)])) -print(rockScissorsPaper(games: [(.rock, .scissors), (.scissors, .paper), (.scissors, .rock)])) -print(rockScissorsPaper(games: [(.rock, .paper), (.scissors, .rock), (.paper, .scissors)])) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge26.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge26.xcplaygroundpage/Contents.swift index ac5465c..e84c42a 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge26.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge26.xcplaygroundpage/Contents.swift @@ -18,40 +18,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -enum PolygonType { - case square, triangle, diamond -} - -func drawPolygon(size: Int, type: PolygonType) { - - if size < 2 { - print("El tamaño debe ser mayor a 1") - } - - var totalSize = size - if type == .diamond { - totalSize *= 2 - } - - for value in 1...totalSize { - switch type { - case .square: - print(String(repeating: "* ", count: totalSize)) - case .triangle: - print(String(repeating: "* ", count: value)) - case .diamond: - if value <= size { - print(String(repeating: "* ", count: value)) - } else { - print("\(String(repeating: " ", count: value - size))\(String(repeating: "* ", count: totalSize - value))") - } - } - } - - print("") -} - -drawPolygon(size: 10, type: .square) -drawPolygon(size: 15, type: .triangle) -drawPolygon(size: 12, type: .diamond) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge27.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge27.xcplaygroundpage/Contents.swift index 6a334d9..1fe22fb 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge27.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge27.xcplaygroundpage/Contents.swift @@ -18,10 +18,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func areOrthogonal(vectorOne: (first: Int, second: Int), vectorTwo: (first: Int, second: Int)) -> Bool { - return vectorOne.first * vectorTwo.first + vectorOne.second * vectorTwo.second == 0 -} - -print(areOrthogonal(vectorOne: (first: 1, second: 2), vectorTwo: (first: 2, second: 1))) -print(areOrthogonal(vectorOne: (first: 2, second: 1), vectorTwo: (first: -1, second: 2))) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge28.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge28.xcplaygroundpage/Contents.swift index 92320eb..2c79c88 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge28.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge28.xcplaygroundpage/Contents.swift @@ -22,62 +22,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -enum Money: Int, CaseIterable { - - case five = 5 - case ten = 10 - case fifty = 50 - case oneHundred = 100 - case twoHundred = 200 - -} - -func buy(code: Int, money: [Money]) -> (name: String, money: [Money]) { - - let products = [1: (name: "Agua", money: 50), - 2: (name: "Coca-Cola", money: 100), - 4: (name: "Cerveza", money: 155), - 5: (name: "Pizza", money: 200), - 10: (name: "Donut", money: 75)] - - if let product = products[code] { - - let totalMoney = money.map{ $0.rawValue }.reduce(0, +) - - if totalMoney < product.money { - return ("El producto con código [\(code)] tiene un coste \(product.money). Has introducido \(totalMoney).", money) - } - - let pendingMoney = totalMoney - product.money - - return (product.name, returnMoney(pendingMoney: pendingMoney)) - } - - return ("El producto con código [\(code)] no existe.", money) -} - -func returnMoney(pendingMoney: Int, money: [Money] = []) -> [Money] { - - if pendingMoney == 0 { - return money - } - - var newPendingMoney = pendingMoney - var newMoney = money - - for coin in Money.allCases.reversed() { - if coin.rawValue <= pendingMoney { - newPendingMoney -= coin.rawValue - newMoney.append(coin) - break - } - } - - return returnMoney(pendingMoney: newPendingMoney, money: newMoney) -} - -print(buy(code: 1, money: [.five, .five, .ten, .ten, .ten, .five])) -print(buy(code: 3, money: [.five, .five, .ten, .ten, .ten, .five])) -print(buy(code: 1, money: [.five, .five, .ten, .ten, .ten, .five, .fifty])) -print(buy(code: 5, money: [.twoHundred])) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge29.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge29.xcplaygroundpage/Contents.swift index 1409553..0f1ef52 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge29.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge29.xcplaygroundpage/Contents.swift @@ -19,31 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func sort(numbers: [Int], asc: Bool) -> [Int] { - - var sortedNumbers: [Int] = [] - - for number in numbers { - - var added = false - - for (index, sortedNumber) in sortedNumbers.enumerated() { - - if asc ? number < sortedNumber : number > sortedNumber { - sortedNumbers.insert(number, at: index) - added = true - break - } - } - - if !added { - sortedNumbers.append(number) - } - } - - return sortedNumbers -} - -print(sort(numbers: [4, 6, 1, 8, 2], asc: true)) // 1, 2, 4, 6, 8 -print(sort(numbers: [4, 6, 1, 8, 2], asc: false)) // 8, 6, 4, 2, 1 diff --git a/WeeklyChallenge2022.playground/Pages/Challenge3.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge3.xcplaygroundpage/Contents.swift index 054e0b3..8a92d78 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge3.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge3.xcplaygroundpage/Contents.swift @@ -17,24 +17,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func isPrime(number: Int) -> Bool { - - if number < 2 { - return false - } - - for i in 2 ..< number { - if number % i == 0 { - return false - } - } - - return true -} - -(1...100).forEach { number in - if isPrime(number: number) { - print(number) - } -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge30.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge30.xcplaygroundpage/Contents.swift index 67b4d40..f7655da 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge30.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge30.xcplaygroundpage/Contents.swift @@ -25,28 +25,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func drawFrame(text: String) { - - let words = text.components(separatedBy: " ") - var maxLength = 0 - words.forEach { word in - if word.count > maxLength { - maxLength = word.count - } - } - - print(String(repeating: "*", count: maxLength + 4)) - - words.forEach { word in - if !word.isEmpty { - print("* \(word)\(String(repeating: " ", count: maxLength - word.count)) *") - } - } - - print(String(repeating: "*", count: maxLength + 4)) -} - -drawFrame(text: "¿Qué te parece el reto?") -drawFrame(text: "¿Qué te parece el reto?") -drawFrame(text: "¿Cuántos retos de código de la comunidad has resuelto?") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge31.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge31.xcplaygroundpage/Contents.swift index 10110f6..e268b35 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge31.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge31.xcplaygroundpage/Contents.swift @@ -17,22 +17,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func thirtyLeapYears(year: Int) { - - var currentYear = year + 1 - var yearCount = 0 - - while yearCount < 30 { - - if currentYear % 4 == 0 && (currentYear % 100 != 0 || currentYear % 400 == 0) { - print(currentYear) - yearCount += 1 - } - - currentYear += 1 - } -} - -thirtyLeapYears(year: 1999) -thirtyLeapYears(year: -500) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge32.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge32.xcplaygroundpage/Contents.swift index c1a2650..ba89447 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge32.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge32.xcplaygroundpage/Contents.swift @@ -14,35 +14,3 @@ import Foundation * - Tienes toda la información sobre los retos semanales en https://retosdeprogramacion.com/semanales2022. * */ - -func findSecondGreater(numbers: [Int]) -> Int? { - - var sortedNumbers: [Int] = [] - - for number in numbers { - - var found = false - - for (index, sortedNumber) in sortedNumbers.enumerated() { - - if number >= sortedNumber { - if number != sortedNumber { - sortedNumbers.insert(number, at: index) - } - found = true - break - } - } - - if !found { - sortedNumbers.append(number) - } - } - - return sortedNumbers.count >= 2 ? sortedNumbers[1] : nil -} - -print(findSecondGreater(numbers: [4, 6, 1, 8, 2]) ?? "No se ha encontrado un valor") -print(findSecondGreater(numbers: [4, 6, 8, 8, 6]) ?? "No se ha encontrado un valor") -print(findSecondGreater(numbers: [4, 4]) ?? "No se ha encontrado un valor") -print(findSecondGreater(numbers: []) ?? "No se ha encontrado un valor") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge33.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge33.xcplaygroundpage/Contents.swift index d7469fe..4b470c9 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge33.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge33.xcplaygroundpage/Contents.swift @@ -21,27 +21,3 @@ import Foundation * - Tienes toda la información sobre los retos semanales en https://retosdeprogramacion.com/semanales2022. * */ - -private func chineseZodiac(year: Int) -> String { - - let elements = ["madera", "fuego", "tierra", "metal", "agua"] - let animals = ["rata", "buey", "tigre", "conejo", "dragón", "serpiente", "caballo", "oveja", "mono", "gallo", "perro", "cerdo"] - - if year < 604 { - return "El ciclo sexagenario comenzó en el año 604." - } - - let sexagenaryYear = (year - 4) % 60 - let element = elements[(sexagenaryYear % 10) / 2] - let animal = animals[sexagenaryYear % 12] - - return "\(year): \(element) \(animal)" -} - -print(chineseZodiac(year: 1924)) -print(chineseZodiac(year: 1946)) -print(chineseZodiac(year: 1984)) -print(chineseZodiac(year:604)) -print(chineseZodiac(year:603)) -print(chineseZodiac(year: 1987)) -print(chineseZodiac(year: 2022)) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge34.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge34.xcplaygroundpage/Contents.swift index 3896b30..93dcaea 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge34.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge34.xcplaygroundpage/Contents.swift @@ -15,59 +15,3 @@ import Foundation * - Tienes toda la información sobre los retos semanales en https://retosdeprogramacion.com/semanales2022. * */ - -enum LostNumbers: Error { - case numbersError - - var description: String { - switch self { - case .numbersError: - return "El listado no puede poseer repetidos ni estar desordenado, y debe tener mínimo 2 valores." - } - } -} - -func lostNumbers(numbers: [Int]) throws -> [Int] { - - // Errors - if numbers.count < 2 { - throw LostNumbers.numbersError - } - - let first = numbers.first! - let last = numbers.last! - let asc = first < last - - var prev: Int? - try numbers.forEach { number in - if let prev = prev { - if asc ? number <= prev : number >= prev { - throw LostNumbers.numbersError - } - } - prev = number - } - - // Lost - var lost: [Int] = [] - - ((asc ? first : last)...(asc ? last : first)).forEach { number in - if !numbers.contains(number) { - lost.append(number) - } - } - - return lost -} - -do { - print(try lostNumbers(numbers: [1, 3, 5])) - print(try lostNumbers(numbers: [5, 3, 1])) - print(try lostNumbers(numbers: [5, 1])) - print(try lostNumbers(numbers: [-5, 1])) - //print(try lostNumbers(numbers: [1, 3, 3, 5])) - //print(try lostNumbers(numbers: [5, 7, 1])) - print(try lostNumbers(numbers: [10, 7, 7, 1])) -} catch LostNumbers.numbersError { - print(LostNumbers.numbersError.description) -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge35.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge35.xcplaygroundpage/Contents.swift index 202128b..37237c7 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge35.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge35.xcplaygroundpage/Contents.swift @@ -25,48 +25,49 @@ import Foundation * */ -enum PokemonType: String { - case water = "Agua" - case fire = "Fuego" - case grass = "Planta" - case electric = "Eléctrico" -} -struct PokemonChart { - let effective: PokemonType - let notEffective: PokemonType +enum TipoPokemon { + case agua + case fuego + case planta + case electrico } -func battle(attacker: PokemonType, defender: PokemonType, attack: Int, defense: Int) -> Double? { +struct PokemonRanking { + let efectivo: TipoPokemon + let noEfectivo: TipoPokemon +} - if attack <= 0 || attack > 100 || defense <= 0 || defense > 100 { +func batalla(atacante: TipoPokemon, defensor: TipoPokemon, ataque: Int, defensa: Int) -> Double? { + + if ataque <= 0 || ataque > 100 || defensa <= 0 || defensa > 100 { print("El ataque o la defensa contiene un valor incorrecto") return nil } - - let typeChart: [PokemonType:PokemonChart] = [ - .water:PokemonChart(effective: .fire, notEffective: .grass), - .fire:PokemonChart(effective: .grass, notEffective: .water), - .grass:PokemonChart(effective: .water, notEffective: .fire), - .electric:PokemonChart(effective: .water, notEffective: .grass)] - - - var effectivity = 1.0 - if attacker == defender || typeChart[attacker]!.notEffective == defender { - effectivity = 0.5 + + let ranking: [TipoPokemon : PokemonRanking] = [ + TipoPokemon.agua : PokemonRanking(efectivo: .fuego, noEfectivo: .planta), + TipoPokemon.fuego : PokemonRanking(efectivo: .planta, noEfectivo: .agua), + TipoPokemon.planta : PokemonRanking(efectivo: .agua, noEfectivo: .fuego), + TipoPokemon.electrico : PokemonRanking(efectivo: .agua, noEfectivo: .planta), + ] + + var efectividad = 1.0 + if atacante == defensor || ranking[atacante]?.noEfectivo == defensor { + efectividad = 0.5 print("No es muy efectivo") - } else if typeChart[attacker]!.effective == defender { - effectivity = 2.0 - print("Es súper efectivo") + } else if ranking[atacante]?.efectivo == defensor { + efectividad = 2.0 + print("Es super efectivo") } else { print("Es neutro") } - - return 50 * Double(attack) / Double(defense) * effectivity + + return 50 * Double(ataque) / Double(defensa) * efectividad + } -print(battle(attacker: .water, defender: .fire, attack: 50, defense: 30) ?? "Error") -print(battle(attacker: .water, defender: .fire, attack: 101, defense: -10) ?? "Error") -print(battle(attacker: .fire, defender: .water, attack: 50, defense: 30) ?? "Error") -print(battle(attacker: .fire, defender: .fire, attack: 50, defense: 30) ?? "Error") -print(battle(attacker: .grass, defender: .electric, attack: 30, defense: 50) ?? "Error") +print((batalla(atacante: .agua, defensor: .fuego, ataque: 50, defensa: 30)) ?? "Error") +print((batalla(atacante: .fuego, defensor: .agua, ataque: 50, defensa: 30)) ?? "Error") +print((batalla(atacante: .planta, defensor: .electrico, ataque: 50, defensa: 30)) ?? "Error") +print((batalla(atacante: .electrico, defensor: .planta, ataque: 50, defensa: 30)) ?? "Error") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge36.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge36.xcplaygroundpage/Contents.swift index 9208f6a..82b03be 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge36.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge36.xcplaygroundpage/Contents.swift @@ -27,77 +27,63 @@ import Foundation * */ -enum KindArmy { - - case harfoot, southener, dwarf, numenorean, elf - - var bravery: Int { + +enum Bondadosas: Int { + case Pelosos + case SureñosBuenos + case Enanos + case Numenoreanos + case Elfos + var puntos: Int { switch self { - case .harfoot: - return 1 - case .southener: - return 2 - case .dwarf: - return 3 - case .numenorean: - return 4 - case .elf: - return 5 + case .Pelosos: return 1 + case .SureñosBuenos: return 2 + case .Enanos: return 3 + case .Numenoreanos: return 4 + case .Elfos: return 5 } } } -enum EvilArmy { - - case southener, orc, goblin, warg, troll - - var bravery: Int { +enum Malvadas { + case SureñosMalos + case Orcos + case Goblins + case Huargos + case Trolls + var puntos: Int { switch self { - case .southener, .orc, .goblin: - return 2 - case .warg: - return 3 - case .troll: - return 5 + case .SureñosMalos: return 2 + case .Orcos: return 2 + case .Goblins: return 2 + case .Huargos: return 3 + case .Trolls: return 5 } } } -func battleForTheMiddleEarth(kindArmy: [(KindArmy, Int)], evilArmy: [(EvilArmy, Int)]) { - - var kindArmyPoints = 0 - var evilArmyPoints = 0 - kindArmy.forEach { army, size in - kindArmyPoints += army.bravery * size +func batalla(buenos: [Bondadosas:Int], malos: [Malvadas:Int]){ + + var puntosBuenos = 0 + var puntosMalos = 0 + + for (tipo, soldados) in buenos { + puntosBuenos += tipo.puntos * soldados } - evilArmy.forEach { army, size in - evilArmyPoints += army.bravery * size + for (tipo, soldados) in malos { + puntosMalos += tipo.puntos * soldados } - - if kindArmyPoints > evilArmyPoints { - print("Gana el bien") - } else if evilArmyPoints > kindArmyPoints { - print("Gana el mal") + + print("Puntos buenos-> \(puntosBuenos) - Puntos malos-> \(puntosMalos)") + if puntosBuenos > puntosMalos { + print("Ganan los buenos") + } else if puntosBuenos < puntosMalos { + print("Ganan los malos") } else { - print("Empate") + print("Empatan") } - } - -battleForTheMiddleEarth( - kindArmy: [(.elf, 1)], - evilArmy: [(.troll, 1)]) - -battleForTheMiddleEarth( - kindArmy: [(.elf, 1), (.harfoot, 1)], - evilArmy: [(.troll, 1)]) - -battleForTheMiddleEarth( - kindArmy: [(.elf, 1), (.harfoot, 1)], - evilArmy: [(.troll, 1), (.orc, 1)]) -battleForTheMiddleEarth( - kindArmy: [(.elf, 56), (.harfoot, 80), (.dwarf, 5)], - evilArmy: [(.troll, 17), (.orc, 51), (.warg, 10), (.southener, 2)]) +batalla(buenos:[Bondadosas.Elfos:2, Bondadosas.Enanos:25], malos:[Malvadas.Orcos:2, Malvadas.SureñosMalos:55]) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge37.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge37.xcplaygroundpage/Contents.swift index 57ec390..7f99c7f 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge37.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge37.xcplaygroundpage/Contents.swift @@ -21,3 +21,135 @@ import Foundation * https://retosdeprogramacion.com/semanales2022. * */ + +enum Zeldas { + //https://en.wikipedia.org/wiki/List_of_The_Legend_of_Zelda_media + + case TheLegendOfZelda + case TheAventureOfLink + case ALinkToThePast + case LinksAwakening + case OcarinaOfTime + case MajorasMask + case OracleOfSeasons + case OracleOfAges + case ALinkToThePast_FourSword + case TheWindMaker + case FourSwordAdventures + case TheMinishCap + case TwilightPrincess + case PhantomHourglass + case SpiritTracks + case SkywardSword + case ALinkBetweenWorlds + case TriForceHeroes + case BreathOfTheWild + case TearsOfTheKingdom + + var name: String { + switch self { + case .TheLegendOfZelda: + return "The Legend of Zelda" + case .TheAventureOfLink: + return "Zelda II: The Adventure of Link" + case .ALinkToThePast: + return "The Legend of Zelda: A Link to the Past" + case .LinksAwakening: + return "The Legend of Zelda: Link's Awakening" + case .OcarinaOfTime: + return "The Legend of Zelda: Ocarina of Time" + case .MajorasMask: + return "Zelda: Majora's Mask" + case .OracleOfSeasons: + return "The Legend of Zelda: Oracle of Seasons" + case .OracleOfAges: + return "The Legend of Zelda: Oracle of Ages" + case .ALinkToThePast_FourSword: + return "The Legend of Zelda: A Link to the Past & Four Swords" + case .TheWindMaker: + return "The Legend of Zelda: The Wind Waker" + case .FourSwordAdventures: + return "The Legend of Zelda: Four Swords Adventures" + case .TheMinishCap: + return "The Legend of Zelda: The Minish Cap" + case .TwilightPrincess: + return "The Legend of Zelda: Twilight Princess" + case .PhantomHourglass: + return "The Legend of Zelda: Phantom Hourglass" + case .SpiritTracks: + return "The Legend of Zelda: Spirit Tracks" + case .SkywardSword: + return "The Legend of Zelda: Skyward Sword" + case .ALinkBetweenWorlds: + return "The Legend of Zelda: A Link Between Worlds" + case .TriForceHeroes: + return "The Legend of Zelda: Tri Force Heroes" + case .BreathOfTheWild: + return "The Legend of Zelda: Breath of the Wild" + case .TearsOfTheKingdom: + return "The Legend of Zelda: Tears of the Kingdom" + } + } + + var release: String { + switch self { + case .TheLegendOfZelda: + return "15/11/1987" + case .TheAventureOfLink: + return "26/09/1988" + case .ALinkToThePast: + return "24/09/1992" + case .LinksAwakening: + return "24/09/1993" + case .OcarinaOfTime: + return "11/12/1998" + case .MajorasMask: + return "17/11/2000" + case .OracleOfSeasons: + return "05/10/2001" + case .OracleOfAges: + return "05/10/2001" + case .ALinkToThePast_FourSword: + return "28/03/2003" + case .TheWindMaker: + return "02/05/2003" + case .FourSwordAdventures: + return "07/04/2005" + case .TheMinishCap: + return "07/04/2005" + case .TwilightPrincess: + return "08/12/2006" + case .PhantomHourglass: + return "19/11/2007" + case .SpiritTracks: + return "11/12/2009" + case .SkywardSword: + return "18/11/2011" + case .ALinkBetweenWorlds: + return "22/11/2013" + case .TriForceHeroes: + return "23/11/2015" + case .BreathOfTheWild: + return "03/03/2017" + case .TearsOfTheKingdom: + return "12/05/2023" + } + } +} + +func daysBetween(startGame: Zeldas, endGame: Zeldas) { + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = "mm/dd/YYYY" + dateFormatter.locale = Locale(identifier: "es_ES") + dateFormatter.dateStyle = .short + + var result = Calendar.current.dateComponents( + [.day,.year], + from: dateFormatter.date(from: startGame.release) ?? Date(), + to: dateFormatter.date(from: endGame.release) ?? Date() + ) + + print("Han pasado \(result.year!.magnitude) años y \(result.day!.magnitude) días entre los juegos \(startGame.name) y \(endGame.name)") +} + +daysBetween(startGame: Zeldas.OcarinaOfTime, endGame: Zeldas.ALinkToThePast) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge4.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge4.xcplaygroundpage/Contents.swift index f3b4837..a53a7bb 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge4.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge4.xcplaygroundpage/Contents.swift @@ -19,57 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -area(polygon: Triangle(base: 10.0, height: 5.0)) -area(polygon: Rectangle(length: 5.0, width: 7.0)) -area(polygon: Square(side: 4.0)) - -protocol Polygon { - - func area() -> Double - func printArea() -} - -struct Triangle: Polygon { - - let base, height: Double - - func area() -> Double { - return (base * height) / 2 - } - - func printArea() { - print("El área del triángulo es \(area())") - } -} - -struct Rectangle: Polygon { - - let length, width: Double - - func area() -> Double { - return length * width - } - - func printArea() { - print("El área del rectángulo es \(area())") - } -} - -struct Square: Polygon { - - let side: Double - - func area() -> Double { - return side * side - } - - func printArea() { - print("El área del cuadrado es \(area())") - } -} - -func area(polygon: Polygon) -> Double { - polygon.printArea() - return polygon.area() -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge5.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge5.xcplaygroundpage/Contents.swift index ae3cf7a..6fb4561 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge5.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge5.xcplaygroundpage/Contents.swift @@ -18,34 +18,3 @@ import UIKit * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func rationalAspectRatio(aspectRatio: Double) -> (num: Int, den: Int) { - let precision = 1.0E-6 - var x = aspectRatio - var a = x.rounded(.down) - var (h1, k1, h, k) = (1, 0, Int(a), 1) - - while x - a > precision * Double(k) * Double(k) { - x = 1.0 / (x - a) - a = x.rounded(.down) - (h1, k1, h, k) = (h, k, h1 + Int(a) * h, k1 + Int(a) * k) - } - return (h, k) -} - -var aspectRationStr: String? - -if let url = URL(string: "https://raw.githubusercontent.com/mouredev/mouredev/master/mouredev_github_profile.png"), let data = try? Data(contentsOf: url) { - - let imagen = UIImage(data: data) - if let height = imagen?.size.height, let width = imagen?.size.width { - let aspectRatio = rationalAspectRatio(aspectRatio: height / width) - aspectRationStr = "\(aspectRatio.den):\(aspectRatio.num)" - } -} - -if let ratio = aspectRationStr { - print("El aspect ratio es \(ratio)") -} else { - print("No se ha podido calcular el aspect ratio") -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge6.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge6.xcplaygroundpage/Contents.swift index 06b9b7e..e99910a 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge6.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge6.xcplaygroundpage/Contents.swift @@ -17,29 +17,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -print(reverse(text: "Hola mundo")) -print(recursiveReverse(text: "Hola mundo")) - -func reverse(text: String) -> String { - let textCount = text.count - 1 - var reversedText = "" - let textArray = Array(text) - for index in 0...textCount { - reversedText += "\(textArray[textCount - index])" - } - return reversedText -} - -// Sin un bucle, mediante una función recursiva -func recursiveReverse(text: String, index: Int = 0, reversedText: String = "") -> String { - let textCount = text.count - 1 - var newReversedText = reversedText - let textArray = Array(text) - newReversedText += "\(textArray[textCount - index])" - if index < textCount { - let newIndex = index + 1 - newReversedText = recursiveReverse(text: text, index:newIndex, reversedText: newReversedText) - } - return newReversedText -} diff --git a/WeeklyChallenge2022.playground/Pages/Challenge7.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge7.xcplaygroundpage/Contents.swift index 57cfb0e..0aa737a 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge7.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge7.xcplaygroundpage/Contents.swift @@ -19,28 +19,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func countWords(text: String) { - - let mutableString = NSMutableString(string: text.lowercased()) - - let regex = try! NSRegularExpression(pattern: "[^a-z0-9]", options: []) - regex.replaceMatches(in: mutableString, options: [], range: NSMakeRange(0, mutableString.length), withTemplate: " ") - - var words: [String:Int] = [:] - - String(mutableString).split(separator: " ").forEach { word in - let key = String(word) - if words[key] != nil { - words[key]! += 1 - } else { - words[key] = 1 - } - } - - words.forEach { key, value in - print("\(key) se ha repetido \(value) \(value == 1 ? "vez" : "veces")") - } -} - -countWords(text: "Hola, mi nombre es brais. Mi nombre completo es Brais Moure (MoureDev).") diff --git a/WeeklyChallenge2022.playground/Pages/Challenge8.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge8.xcplaygroundpage/Contents.swift index 389cf09..7916755 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge8.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge8.xcplaygroundpage/Contents.swift @@ -16,22 +16,3 @@ import Foundation * - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación. * */ - -func decimalToBinary(_ decimal: Int) -> String { - - var number = decimal - var binary = "" - - while number != 0 { - - let reminder = number % 2 - number /= 2 - - binary = "\(reminder)\(binary)" - } - - return binary.isEmpty ? "0" : binary -} - -print(decimalToBinary(387)) -print(decimalToBinary(0)) diff --git a/WeeklyChallenge2022.playground/Pages/Challenge9.xcplaygroundpage/Contents.swift b/WeeklyChallenge2022.playground/Pages/Challenge9.xcplaygroundpage/Contents.swift index adca7a6..a467edb 100644 --- a/WeeklyChallenge2022.playground/Pages/Challenge9.xcplaygroundpage/Contents.swift +++ b/WeeklyChallenge2022.playground/Pages/Challenge9.xcplaygroundpage/Contents.swift @@ -20,74 +20,3 @@ import Foundation * */ -func decoder(input: String) -> String { - - var decodedInput = "" - - let naturalDict = ["A":".—", "N":"—.", "0":"—————", - "B":"—...", "Ñ":"——.——", "1":".————", - "C":"—.—.", "O":"———", "2":"..———", - "CH":"————", "P":".——.", "3":"...——", - "D":"—..", "Q":"——.—", "4":"....—", - "E":".", "R":".—.", "5":".....", - "F":"..—.", "S":"...", "6":"—....", - "G":"——.", "T":"—", "7":"——...", - "H":"....", "U":"..—", "8":"———..", - "I":"..", "V":"...—", "9":"————.", - "J":".———", "W":".——", ".":".—.—.—", - "K":"—.—", "X":"—..—", ",":"——..——", - "L":".—..", "Y":"—.——", "?":"..——..", - "M":"——", "Z":"——..", "\"":".—..—.", "/":"—..—."] - - var morseDict: [String: String] = [:] - naturalDict.forEach { key, value in - morseDict[value] = key - } - - if input.rangeOfCharacter(from: CharacterSet.letters) != nil || input.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil { - - // Natural - - var index = 0 - var ch = false - - input.uppercased().forEach { character in - if !ch && character != " " { - let nextIndex = index + 1 - if character == "C" && nextIndex < input.count && Array(input.uppercased())[nextIndex] == "H" { - decodedInput += naturalDict["CH"] ?? "" - ch = true - } else { - decodedInput += naturalDict[character.description] ?? "" - } - - decodedInput += " " - } else { - if (!ch) { - decodedInput += " " - } - ch = false - } - - index += 1 - } - - } else if (input.contains(".") || input.contains("—")) { - - // Morse - - input.components(separatedBy: " ").forEach { word in - word.components(separatedBy: " ").forEach { symbols in - decodedInput += morseDict[symbols] ?? "" - } - decodedInput += " " - } - } - - return decodedInput -} - -let naturalText = "Chocapic. Es una marca de cereales?" -let morseText = decoder(input: naturalText) -print(morseText) -print(decoder(input: morseText))