Skip to content

Solución reto #50 en Swift #295

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 152 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
152 commits
Select commit Hold shift + click to select a range
47e2a72
Jaimefere's solution (7 s)
Dec 29, 2021
56891fe
Jaimefere's solution in separated playground page
Jan 4, 2022
8bcf066
Merge remote-tracking branch 'refs/remotes/original/main'
Jan 4, 2022
f91005a
Solución Reto #1
Jan 10, 2022
526e435
Merge remote-tracking branch 'refs/remotes/original/main'
Jan 11, 2022
ce9342b
Solución #1 y enunciado #2
Jan 11, 2022
2a1ba15
Jaimefere's solution #2 challenge
Jan 11, 2022
9408827
Return false when words have equal lengths and they use different let…
Jan 11, 2022
0c8ac9b
Without sorting
Jan 12, 2022
c9aa492
Merge remote-tracking branch 'refs/remotes/original/main'
Jan 20, 2022
d31d5f3
Rename #2 Jaimefere's solution
Jan 20, 2022
49f188e
#3 Jaimefere's solution
Jan 20, 2022
49781ac
Jaimefere's #3 solution in separated file
Jan 26, 2022
63894bc
Merge remote-tracking branch 'refs/remotes/original/main'
Jan 26, 2022
7059ae4
Jaimefere's #4 solution
Jan 26, 2022
e931a47
Jaimefere's #4 solution, only one constructor
Jan 27, 2022
010a7b3
Move #4 Jaimefere's solution to a distinct page
Feb 4, 2022
719d9b1
Merge remote-tracking branch 'refs/remotes/original/main'
Feb 4, 2022
1cd348c
#5 Jaimefere's solution
Feb 7, 2022
cc2c78e
Move #5 Jaimefere's solution to a distinct page
Feb 8, 2022
a6cf6a1
Merge remote-tracking branch 'refs/remotes/original/main'
Feb 8, 2022
e8a1bd1
#6 Jaimefere's solution
Feb 8, 2022
fdb5948
Move #6 Jaimefere's solution to another page
Feb 20, 2022
99305da
Merge remote-tracking branch 'refs/remotes/original/main'
Feb 20, 2022
548b03b
#7 Jaimefere's solution
Feb 20, 2022
531c929
Move #7 Jaimefere's solution to another page
Feb 26, 2022
974c183
Merge remote-tracking branch 'refs/remotes/original/main'
Feb 26, 2022
a1a1e13
#8 Jaimefere's solution
Feb 26, 2022
46282cc
Move #8 Jaimefere's solution to another page
Mar 6, 2022
37e5101
Merge remote-tracking branch 'refs/remotes/original/main'
Mar 6, 2022
7e7d16a
#9 Jaimefere's solution
Mar 6, 2022
d553391
Move #9 Jaimefere's solution to another page
Mar 14, 2022
2d891ea
Merge remote-tracking branch 'refs/remotes/original/main'
Mar 14, 2022
995c11a
#10 Jaimefere's solution
Mar 14, 2022
47f7063
Move #10 Jaimefere's solution to another page
Mar 21, 2022
6f8972d
Merge remote-tracking branch 'refs/remotes/original/main'
Mar 21, 2022
94369e7
#11 Jaimefere's solution
Mar 21, 2022
e96cba0
Move #11 Jaimefere's solution to another page
Mar 28, 2022
cda4473
Merge remote-tracking branch 'refs/remotes/original/main'
Mar 28, 2022
e4c6be9
#12 Jaimefere's solution
Mar 28, 2022
e2c4ece
Move #12 jaimefere's solution to another page
Apr 3, 2022
a8853ab
Merge remote-tracking branch 'refs/remotes/original/main'
Apr 3, 2022
493d8e4
#13 Jaimefere's refactored solution
Apr 3, 2022
c251c3a
Move #13 jaimefere's solution to another page
Apr 10, 2022
9909fb6
Merge remote-tracking branch 'refs/remotes/original/main'
Apr 10, 2022
9c6a1f1
#14 Jaimefere's solution
Apr 10, 2022
29083c7
Move #14 jaimefere's solution to another page
Apr 17, 2022
fc67113
Merge remote-tracking branch 'refs/remotes/original/main'
Apr 17, 2022
4000f58
#15 Jaimefere's solution
Apr 18, 2022
7fad1f3
Move #15 jaimefere's solution to another page
Apr 19, 2022
2295003
Merge remote-tracking branch 'refs/remotes/original/main'
Apr 19, 2022
a5bf2ae
#16 Jaimefere's solution
Apr 24, 2022
428038f
Move Jaimefere's solution #16 to another page
May 3, 2022
3d0de6a
Merge remote-tracking branch 'refs/remotes/original/main'
May 3, 2022
08d4f19
Move Jaimefere's solution #17 to another page
May 3, 2022
f290b5f
Jaimefere's solution #18
May 9, 2022
03c6b07
Move Jaimefere's solution #18 to another page
May 10, 2022
3ba0e56
Merge remote-tracking branch 'refs/remotes/original/main'
May 10, 2022
bfc77ba
Jaimefere's solution #19
May 16, 2022
932c0e6
Move Jaimefere's solution #19 to another page
May 22, 2022
4e5a0e0
Merge remote-tracking branch 'refs/remotes/original/main'
May 22, 2022
78bd6c2
Jaimefere's solution #20
May 22, 2022
20e1d12
Move Jaimefere's solution #20 to another page
May 29, 2022
b68403b
Merge remote-tracking branch 'refs/remotes/original/main'
May 29, 2022
6493f73
Jaimefere's solution #21
Jun 1, 2022
ece3a01
Move Jaimefere's solution #21 to another page
Jun 6, 2022
3f9d7f4
Merge remote-tracking branch 'refs/remotes/original/main'
Jun 6, 2022
291fcfe
Jaimefere's solution #22
Jun 7, 2022
45e31a5
Move Jaimefere's solution #22 to another page
Jun 13, 2022
604a273
Merge remote-tracking branch 'refs/remotes/original/main'
Jun 13, 2022
a1e15b7
Jaimefere's solution #23
Jun 13, 2022
3bcfe3e
Move Jaimefere's solution #23 to another page
Jun 14, 2022
fd76a17
Merge remote-tracking branch 'refs/remotes/original/main'
Jun 14, 2022
5e1efa1
Jaimefere's solution #24
Jun 19, 2022
df25020
Move Jaimefere's solution #24 to another page
Jun 24, 2022
cbd4bbe
Merge remote-tracking branch 'refs/remotes/original/main'
Jun 24, 2022
70412ed
Jaimefere's solution #25
Jun 24, 2022
444d2df
Move Jaimefere's solution #25 to another page
Jul 3, 2022
570ff0f
Merge remote-tracking branch 'refs/remotes/original/main'
Jul 3, 2022
5061e91
Jaimefere's solution #26
Jul 5, 2022
bd86c61
Move Jaimefere's solution #26 to another page
Jul 9, 2022
180a631
Merge remote-tracking branch 'refs/remotes/original/main'
Jul 9, 2022
ed4eae5
Jaimefere's solution #27
Jul 9, 2022
abaf7d4
Move Jaimefere's solution #27 to another page
Jul 18, 2022
1d43bcf
Merge remote-tracking branch 'refs/remotes/original/main'
Jul 18, 2022
e7ac9b4
Jaimefere's solution #28
Jul 18, 2022
0390be7
Move Jaimefere's solution #28 to another page
Jul 24, 2022
6ac32c9
Merge remote-tracking branch 'refs/remotes/original/main'
Jul 24, 2022
7ce0b35
Jaimefere's solution #29
Jul 26, 2022
a59c675
Move Jaimefere's solution #29 to another page
Jul 31, 2022
87b69fa
Merge remote-tracking branch 'refs/remotes/original/main'
Jul 31, 2022
a16d7ef
Jaimefere's solution #30
Jul 31, 2022
c040ad0
Move Jaimefere's solution #30 to another page
Aug 7, 2022
ba3fe4d
Merge remote-tracking branch 'refs/remotes/original/main'
Aug 7, 2022
7dee983
Jaimefere's solution #31
Aug 7, 2022
ff868a7
Move Jaimere's solution #31 to another page
Aug 15, 2022
32afa35
Merge remote-tracking branch 'refs/remotes/original/main'
Aug 15, 2022
9cf62ca
Jaimefere's solution #32
Aug 15, 2022
174912b
Move Jaimere's solution #32 to another page
Aug 20, 2022
582d341
Merge remote-tracking branch 'refs/remotes/original/main'
Aug 20, 2022
2635f56
Jaimefere's solution #33
Aug 22, 2022
27a9c0d
Move Jaimefere's solution #33 to another page
Aug 28, 2022
a6dfe62
Merge remote-tracking branch 'refs/remotes/original/main'
Aug 28, 2022
4fa933a
Jaimefere's solution #34
Aug 28, 2022
aeee9c5
Move Jaimefere's solution #34 to another page
Sep 5, 2022
4d78b7f
Merge remote-tracking branch 'refs/remotes/original/main'
Sep 5, 2022
b080955
Jaimefere's solution #35
Sep 5, 2022
ccdef34
Move Jaimefere's solution #35 to another page
Sep 14, 2022
0e92e33
Merge remote-tracking branch 'refs/remotes/original/main'
Sep 14, 2022
d242c05
Jaimefere's solution #36
Sep 14, 2022
a55cd59
Move Jaimefere's solution #36 to another page
Sep 18, 2022
c938249
Merge remote-tracking branch 'refs/remotes/original/main'
Sep 18, 2022
0c4fdd1
Jaimefere's solution #37
Sep 18, 2022
2389c95
Move Jaimefere's solution #37 to another package
Sep 25, 2022
9c0e1c0
Merge remote-tracking branch 'refs/remotes/original/main'
Sep 25, 2022
64a5a36
Jaimefere's solution #38
Sep 25, 2022
9db74de
Move Jaimefere's solution #38 to another package
Oct 1, 2022
b74dc0c
Merge remote-tracking branch 'refs/remotes/original/main'
Oct 1, 2022
0b63581
Jaimefere's solution #39
Oct 1, 2022
5f5244e
Move Jaimefere's solution #39 to another page
Oct 10, 2022
59f0fda
Merge remote-tracking branch 'refs/remotes/original/main'
Oct 10, 2022
ba78be0
Move Jaimefere's solution #40 to another page
Oct 17, 2022
2bcc065
Merge remote-tracking branch 'refs/remotes/original/main'
Oct 17, 2022
e57e49e
Jaimefere's solution #41
Oct 17, 2022
c6d7a01
Move Jaimefere's solution #41 to another page
Oct 24, 2022
02c4662
Merge remote-tracking branch 'refs/remotes/original/main'
Oct 24, 2022
514ff58
Jaimefere's solution #42
Oct 24, 2022
4eec4b1
Move Jaimefere's solution #42 to another page
Nov 2, 2022
6ef9d4a
Merge remote-tracking branch 'refs/remotes/original/main'
Nov 2, 2022
86d2053
Jaimefer's solution #43 in different page
Nov 3, 2022
693c288
Jaimefere's solution #44
Nov 6, 2022
ec2ec37
Move Jaimefere's solution #44 to another page
Nov 14, 2022
3367bd2
Move Jaimefere's solution #44 to another page
Nov 14, 2022
867c0ce
Jaimefere's solution #45
Nov 14, 2022
9a538c5
Merge remote-tracking branch 'refs/remotes/origin/main'
Nov 14, 2022
2800d55
Move Jaimefere's solution #45 to another page
Nov 20, 2022
a453dc6
Merge remote-tracking branch 'refs/remotes/original/main'
Nov 20, 2022
9ab004e
Jaimefere's solution #46
Nov 20, 2022
fe64129
Move Jaimefere's solution #46 to another page
Nov 27, 2022
75509c8
Merge remote-tracking branch 'refs/remotes/original/main'
Nov 27, 2022
1c59475
Jaimefere's solution #47
Nov 27, 2022
e28f64a
Move Jaimefere's solution #47 to another page
Dec 4, 2022
58fd990
Merge remote-tracking branch 'refs/remotes/original/main'
Dec 4, 2022
7b1e7a9
Jaimefere's solution #48
Dec 5, 2022
0c811a7
Move Jaimefere's solution #48 to another page
Dec 6, 2022
513ee87
Merge remote-tracking branch 'refs/remotes/original/main'
Dec 6, 2022
f788652
First ten challenges solved by ChatGPT
Dec 12, 2022
f0736f5
ChatGPT's solution #49
Dec 12, 2022
e4fb7ee
Solved challenges from #11 to #16 by ChatGPT
Dec 19, 2022
a814d12
Move ChatGPT's solution #49 to another package
Dec 19, 2022
a28574c
Merge remote-tracking branch 'refs/remotes/original/main'
Dec 19, 2022
0b9275f
Move Jaimefere's solution #50 to other page
Dec 20, 2022
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
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ Tienes toda la información extendida sobre los retos de programación semanales
* **#47** - 21/11/22 - [`VOCAL MÁS COMÚN`](https://github.com/mouredev/Weekly-Challenge-2022-Swift/blob/main/WeeklyChallenge2022.playground/Pages/Challenge47.xcplaygroundpage/Contents.swift)
* **#48** - 28/11/22 - [`EL CALENDARIO DE ADEVIENTO 2022`](https://github.com/mouredev/Weekly-Challenge-2022-Swift/blob/main/WeeklyChallenge2022.playground/Pages/Challenge48.xcplaygroundpage/Contents.swift)
* **#49** - 05/12/22 - [`EL DETECTOR DE HANDLES`](https://github.com/mouredev/Weekly-Challenge-2022-Swift/blob/main/WeeklyChallenge2022.playground/Pages/Challenge49.xcplaygroundpage/Contents.swift)
* **#50** - 12/12/22 - [`LA ENCRIPTACIÓN DE KARACA`](https://github.com/mouredev/Weekly-Challenge-2022-Swift/blob/main/WeeklyChallenge2022.playground/Pages/Challenge50.xcplaygroundpage/Contents.swift)
* **#51** - 19/12/22 - `Publicación nuevo reto...`
* **#50** - 12/12/22 - `Publicación nuevo reto...`

<a href="https://youtu.be/ydH_B5KuqGs"><img src="http://i3.ytimg.com/vi/ydH_B5KuqGs/maxresdefault.jpg" style="height: 50%; width:50%;"/></a>

Expand Down Expand Up @@ -161,4 +160,4 @@ Soy ingeniero de software desde hace más de 12 años. Desde hace 4 años combin

### En mi perfil de GitHub tienes más información

[![Web](https://img.shields.io/badge/GitHub-MoureDev-14a1f0?style=for-the-badge&logo=github&logoColor=white&labelColor=101010)](https://github.com/mouredev)
[![Web](https://img.shields.io/badge/GitHub-MoureDev-14a1f0?style=for-the-badge&logo=github&logoColor=white&labelColor=101010)](https://github.com/mouredev)
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Foundation

/*
* Reto #4
* ÁREA DE UN POLÍGONO
* Fecha publicación enunciado: 24/01/22
* Fecha publicación resolución: 31/01/22
* Dificultad: FÁCIL
*
* Enunciado: Crea UNA ÚNICA FUNCIÓN (importante que sólo sea una) que sea capaz de calcular y retornar el área de un polígono.
* - La función recibirá por parámetro sólo UN polígono a la vez.
* - Los polígonos soportados serán Triángulo, Cuadrado y Rectángulo.
* - Imprime el cálculo del área de un polígono de cada tipo.
*
* Información adicional:
* - Usa el canal de nuestro discord (https://mouredev.com/discord) "🔁reto-semanal" para preguntas, dudas o prestar ayuda la acomunidad.
* - Puedes hacer un Fork del repo y una Pull Request al repo original para que veamos tu solución aportada.
* - Revisaré el ejercicio en directo desde Twitch el lunes siguiente al de su publicación.
* - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación.
*
*/

struct Polygon {
private var hasFourVertices: Bool
private var sideA: Double
private var sideB: Double
private var sideC: Double

init(hasFourVertices:Bool, sideA: Double, sideB: Double = 0.0, sideC: Double = 0.0) {
self.hasFourVertices = hasFourVertices
self.sideA = sideA
self.sideB = (sideB == 0.0) ? sideA : sideB
self.sideC = (sideC == 0.0) ? self.sideB : sideC
}

func getArea() -> Double {
if(hasFourVertices) {
return sideA * sideB
} else {
let semiperimeter = (sideA + sideB + sideC) / 2.0
return sqrt(semiperimeter * (semiperimeter - sideA) * (semiperimeter - sideB) * (semiperimeter - sideC))
}
}
}

print(Polygon.init(hasFourVertices: true, sideA: 4).getArea())
print(Polygon.init(hasFourVertices: true, sideA: 7, sideB: 4).getArea())
print(Polygon.init(hasFourVertices: false, sideA: 3, sideB: 4, sideC: 5).getArea())
print(Polygon.init(hasFourVertices: false, sideA: 3, sideB: 4).getArea()) // isosceles
print(Polygon.init(hasFourVertices: false, sideA: 3).getArea()) // equilateral
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Foundation

/*
* Reto #0
* EL FAMOSO "FIZZ BUZZ"
* Fecha publicación enunciado: 27/12/21
* Fecha publicación resolución: 03/01/22
* Dificultad: FÁCIL
*
* Enunciado: Escribe un programa que muestre por consola (con un print) los números de 1 a 100 (ambos incluidos y con un salto de línea entre cada impresión), sustituyendo los siguientes:
* - Múltiplos de 3 por la palabra "fizz".
* - Múltiplos de 5 por la palabra "buzz".
* - Múltiplos de 3 y de 5 a la vez por la palabra "fizzbuzz".
*
* Información adicional:
* - Usa el canal de nuestro discord (https://mouredev.com/discord) "🗓reto-semanal" para preguntas, dudas o prestar ayuda la acomunidad.
* - Puedes hacer un Fork del repo y una Pull Request al repo original para que veamos tu solución aportada.
* - Revisaré el ejercicio en directo desde Twitch el lunes siguiente al de su publicación.
* - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación.
*
*/
//let startTime = NSDate()
(1...100).forEach { num in
if(num % 5 == 0) {
print("\(num % 3 == 0 ? "fizz" : "")buzz")
} else if(num % 3 == 0) {
print("fizz")
} else {
print(num)
}
}
//print("execution time: \(NSDate().timeIntervalSince(startTime as Date) * 1000) ms")
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Foundation

/*
* Reto #0
* EL FAMOSO "FIZZ BUZZ"
* Fecha publicación enunciado: 27/12/21
* Fecha publicación resolución: 03/01/22
* Dificultad: FÁCIL
*
* Enunciado: Escribe un programa en Swift que muestre por consola (con un print) los números de 1 a 100 (ambos incluidos y con un salto de línea entre cada impresión), sustituyendo los siguientes:
* - Múltiplos de 3 por la palabra "fizz".
* - Múltiplos de 5 por la palabra "buzz".
* - Múltiplos de 3 y de 5 a la vez por la palabra "fizzbuzz".
*
* Resuelto: Sí
" Iteracciones: 1
* Explicación: El código utiliza un bucle for para recorrer los números del 1 al 100. Para cada número, se comprueba si es múltiplo de 3 y de 5, de 3 o de 5, y se imprime el número sustituido por la palabra correspondiente, o bien se imprime el número sin modificar si no es múltiplo de ninguno de los dos números.
*
*/

for number in 1...100 {
if number % 3 == 0 && number % 5 == 0 {
// El número es múltiplo de 3 y de 5
print("fizzbuzz")
} else if number % 3 == 0 {
// El número es múltiplo de 3
print("fizz")
} else if number % 5 == 0 {
// El número es múltiplo de 5
print("buzz")
} else {
// El número no es múltiplo ni de 3 ni de 5
print(number)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Foundation

/*
* Reto #1
* ¿ES UN ANAGRAMA?
* Fecha publicación enunciado: 03/01/22
* Fecha publicación resolución: 10/01/22
* Dificultad: MEDIA
*
* Enunciado: Escribe una función que reciba dos palabras (String) y retorne verdadero o falso (Bool) según sean o no anagramas.
* Un Anagrama consiste en formar una palabra reordenando TODAS las letras de otra palabra inicial.
* NO hace falta comprobar que ambas palabras existan.
* Dos palabras exactamente iguales no son anagrama.
*
* Información adicional:
* - Usa el canal de nuestro discord (https://mouredev.com/discord) "🔁reto-semanal" para preguntas, dudas o prestar ayuda la acomunidad.
* - Puedes hacer un Fork del repo y una Pull Request al repo original para que veamos tu solución aportada.
* - Revisaré el ejercicio en directo desde Twitch el lunes siguiente al de su publicación.
* - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación.
*
*/

func areAnagrams(wordA: String, wordB: String) -> Bool {
return wordA.count == wordB.count && (wordA.lowercased().enumerated().filter { (index, c) in
String(c) == String(Array(wordB)[index]).lowercased() || // que cumpla que TODAS las letras están en otra posición (reordenadas)
wordA.split(separator: c).count != wordB.split(separator: c).count
}.isEmpty)
}

print(areAnagrams(wordA: "Roma", wordB: ""))
print(areAnagrams(wordA: "Roma", wordB: "Roma"))
print(areAnagrams(wordA: "Roma", wordB: "romana"))
print(areAnagrams(wordA: "Roma", wordB: "Peru"))
print(areAnagrams(wordA: "Roma", wordB: "ramo"))
print(areAnagrams(wordA: "Roma", wordB: "mora"))
print(areAnagrams(wordA: "Roma", wordB: "moar"))
print(areAnagrams(wordA: "Roma", wordB: "amor"))
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import Foundation

/*
* Reto #1
* ¿ES UN ANAGRAMA?
* Fecha publicación enunciado: 03/01/22
* Fecha publicación resolución: 10/01/22
* Dificultad: MEDIA
*
* Enunciado: Escribe una función en Swift que reciba dos palabras (String) y retorne verdadero o falso (Bool) según sean o no anagramas.
* - Un Anagrama consiste en formar una palabra reordenando TODAS las letras de otra palabra inicial.
* - NO hace falta comprobar que ambas palabras existan.
* - Dos palabras exactamente iguales no son anagrama.
*
* Resuelto: No, en los casos en los que debe devolver falso a veces devuelve true.
* Explicación: Para resolver este problema, podríamos utilizar un diccionario para contar la cantidad de ocurrencias de cada letra en cada palabra. Luego, comparar los dos diccionarios para ver si son iguales. Si lo son, entonces las palabras son anagramas.
* Nota: no exige poner el nombre de los parámetros de la función. Utiliza tabulación de 2 espacios.
*
*/

func esAnagrama(_ palabra1: String, _ palabra2: String) -> Bool {
// Primero, convertimos las palabras a minúsculas
let palabra1 = palabra1.lowercased()
let palabra2 = palabra2.lowercased()

// Creamos un diccionario vacío para contar las ocurrencias de cada letra
var contador1 = [Character: Int]()
var contador2 = [Character: Int]()

// Recorremos las dos palabras y contamos las ocurrencias de cada letra
for letra in palabra1 {
contador1[letra, default: 0] += 1
}
for letra in palabra2 {
contador2[letra, default: 0] += 1
}

// Comparamos los diccionarios para ver si son iguales
return contador1 == contador2
}

// ChatGPT
// Debería devolver verdadero
esAnagrama("casa", "acas")
// Debería devolver falso
esAnagrama("casa", "casa")
esAnagrama("casa", "saca")
esAnagrama("casa", "baso")

// Brais
print(esAnagrama("amor", "roma"))

// Jaime
print(esAnagrama("Roma", ""))
print(esAnagrama("Roma", "Roma"))
print(esAnagrama("Roma", "romana"))
print(esAnagrama("Roma", "Peru"))
print(esAnagrama("Roma", "ramo"))
print(esAnagrama("Roma", "mora"))
print(esAnagrama("Roma", "moar"))
print(esAnagrama("Roma", "amor"))



Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Foundation

/*
* Reto #10
* EXPRESIONES EQUILIBRADAS
* Fecha publicación enunciado: 07/03/22
* Fecha publicación resolución: 14/03/22
* Dificultad: MEDIA
*
* Enunciado: Crea un programa que comprueba si los paréntesis, llaves y corchetes de una expresión están equilibrados.
* - Equilibrado significa que estos delimitadores se abren y cieran en orden y de forma correcta.
* - Paréntesis, llaves y corchetes son igual de prioritarios. No hay uno más importante que otro.
* - Expresión balanceada: { [ a * ( c + d ) ] - 5 }
* - Expresión no balanceada: { a * ( c + d ) ] - 5 }
*
* Información adicional:
* - Usa el canal de nuestro discord (https://mouredev.com/discord) "🔁reto-semanal" para preguntas, dudas o prestar ayuda a la comunidad.
* - Puedes hacer un Fork del repo y una Pull Request al repo original para que veamos tu solución aportada.
* - Revisaré el ejercicio en directo desde Twitch el lunes siguiente al de su publicación.
* - Subiré una posible solución al ejercicio el lunes siguiente al de su publicación.
*
*/

func isBalanced(expression: String) -> Bool {
let openBrackets = ["{","(","["]
let closeBrackets = ["}",")","]"]
let onlyBrackets = expression.filter{ openBrackets.contains(String($0)) || closeBrackets.contains(String($0)) }

if(onlyBrackets.count == 2) {
return (onlyBrackets == "{}" || onlyBrackets == "()" || onlyBrackets == "[]")
} else {
let firstCloseBracketIndex = onlyBrackets.firstIndex(where: { closeBrackets.contains(String($0)) } )
if(firstCloseBracketIndex == nil || onlyBrackets[...firstCloseBracketIndex!].count < 2) {
return false
} else {
let currentCouple = String(onlyBrackets[onlyBrackets.index(firstCloseBracketIndex!, offsetBy: -1)..<onlyBrackets.index(firstCloseBracketIndex!, offsetBy: 1)])
let prevExpression = String(onlyBrackets[..<onlyBrackets.index(firstCloseBracketIndex!, offsetBy: -1)])
let restExpression = String(onlyBrackets[onlyBrackets.index(firstCloseBracketIndex!, offsetBy: 1)..<onlyBrackets.endIndex])
return isBalanced(expression: currentCouple) && isBalanced(expression: "\(prevExpression)\(restExpression)")
}
}
}

let balancedExpressions = ["{ [ a * ( c + d ) ] - 5 }", "[()]{}{[()()]()}", "{[{}{}]}[()]", "{{}{}}", "[]{}()"]
balancedExpressions.forEach { exp in
print("\(exp) \(!isBalanced(expression: exp) ? "NO " : "")está balanceada")
}
print()
let notBalancedExpressions = ["{ a * ( c + d ) ] - 5 }", "[(])", "{()}[)", "{(})", "{"]
notBalancedExpressions.forEach { exp in
print("\(exp) \(!isBalanced(expression: exp) ? "NO " : "")está balanceada")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import Foundation

/*
* Reto #10
* EXPRESIONES EQUILIBRADAS
* Fecha publicación enunciado: 07/03/22
* Fecha publicación resolución: 14/03/22
* Dificultad: MEDIA
*
* Enunciado: Crea un programa en Swift que comprueba si los paréntesis, llaves y corchetes de una expresión están equilibrados.
* - Equilibrado significa que estos delimitadores se abren y cieran en orden y de forma correcta.
* - Paréntesis, llaves y corchetes son igual de prioritarios. No hay uno más importante que otro.
* - Expresión balanceada: { [ a * ( c + d ) ] - 5 }
* - Expresión no balanceada: { a * ( c + d ) ] - 5 }
*
* Resuelto: Sí
" Iteracciones: 1
* Explicación: Para resolver este problema, podemos utilizar una pila, un tipo de dato que nos permite agregar elementos en un orden determinado y recuperarlos en orden inverso.
Para comprobar si los delimitadores de una expresión están equilibrados, podemos iterar sobre cada carácter de la expresión y hacer lo siguiente:
Si el carácter es un delimitador de apertura, lo agregamos a la pila.
Si el carácter es un delimitador de cierre, verificamos si el último elemento de la pila es el delimitador de apertura correspondiente. Si lo es, eliminamos el elemento de la pila. Si no lo es, la expresión no está equilibrada.
Al finalizar la iteración, si la pila está vacía, significa que todos los delimitadores de apertura y cierre se encuentran en pares y en orden correcto, por lo que la expresión está equilibrada. Si la pila no está vacía, significa que hay delimitadores de apertura que no tienen su correspondiente delimitador de cierre, por lo que la expresión no está equilibrada.
*
*/

// Crea un diccionario de caracteres para los delimitadores abiertos y cerrados
let delimiters = ["{": "}", "[": "]", "(": ")"]

// Función para verificar si la expresión es equilibrada
func isBalanced(_ expression: String) -> Bool {
// Crea una pila para guardar los delimitadores abiertos
var stack = [String]()

// Itera sobre cada caracter en la expresión
for character in expression {
// Si el caracter es un delimitador abierto, agrégalo a la pila
if delimiters.keys.contains(String(character)) {
stack.append(String(character))
}
// Si el caracter es un delimitador cerrado, comprueba si se corresponde con el último delimitador abierto en la pila
else if delimiters.values.contains(String(character)) {
// Si la pila está vacía o el último delimitador abierto no se corresponde con el delimitador cerrado, la expresión no es equilibrada
if stack.isEmpty || delimiters[stack.last!] != String(character) {
return false
}
// Si el delimitador cerrado se corresponde con el último delimitador abierto en la pila, elimina el delimitador abierto de la pila
stack.removeLast()
}
}

// Si la pila está vacía al final de la iteración, significa que todos los delimitadores abiertos fueron cerrados en orden y de forma correcta, por lo que la expresión es equilibrada
return stack.isEmpty
}

// Ejemplos de expresiones equilibradas
print(isBalanced("{ [ a * ( c + d ) ] - 5 }"))
print(isBalanced("[ 1 + 2 ] + { 3 - 4 }"))

// Brais cases
print(isBalanced("{a + b [c] * (2x2)}}}}")) // false
print(isBalanced("{ [ a * ( c + d ) ] - 5 }")) // true
print(isBalanced("{ a * ( c + d ) ] - 5 }")) // false
print(isBalanced("{a^4 + (((ax4)}")) // false
print(isBalanced("{ ] a * ( c + d ) + ( 2 - 3 )[ - 5 }")) // false
print(isBalanced("{{{{{{(}}}}}}")) // false
print(isBalanced("(a")) // false

// Jaime cases
print(isBalanced("{ [ a * ( c + d ) ] - 5 }")) // true
print(isBalanced("[()]{}{[()()]()}")) // true
print(isBalanced("{[{}{}]}[()]")) // true
print(isBalanced("{{}{}}")) // true
print(isBalanced("[]{}()")) // true
print(isBalanced("a+2")) // true
print(isBalanced("{ a * ( c + d ) ] - 5 }")) // false
print(isBalanced("{()}[)")) // false
print(isBalanced("[(])")) // false
print(isBalanced("{(})")) // false
print(isBalanced("{")) // false

Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func isBalanced(expression: String) -> Bool {
}
}
}
}

return stack.isEmpty
}
Loading