Skip to content

Solución Reto #37 Swift #262

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)))")
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Original file line number Diff line number Diff line change
Expand Up @@ -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?"))
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Original file line number Diff line number Diff line change
Expand Up @@ -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..<totalActions) {
if index >= 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: "||?||"))
Original file line number Diff line number Diff line change
Expand Up @@ -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]]))
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Loading