jueves, 19 de octubre de 2017

Ejercicios Swift



Este post contiene distintos ejercicios en lenguaje Swift con String y Enteros, los ejercicios son retos planteados en el Master avanzado en desarrollo iOS y Swift de Udemy. Al final se encuentra un Quiz de 4 preguntas relacionadas.

1) Identificar letras repetidas en un string


import UIKit

// "hola" --> True
// "casa" --> False
// "cAsa" --> True

func reto1 (str: String) -> Bool {
    var letras_usadas = [Character] ()
    for letra in str.characters {
        if letras_usadas.contains(letra) {
            return false
        }
        letras_usadas.append(letra)
    }
    return true
}

assert(reto1(str: "hola") == true, "El reto 1 tiene un error")

assert(reto1(str: "casa") == true, "El reto 1 tiene un error")

2) Palindromos

import UIKit

// string de entrada
// boolean de salida

// ala --> se lee igual de izquierda a derecha que de derecha a izquierda

func palindromo (str: String) -> Bool {
    let string_original = Array(str.characters)
    let string_invertido = Array(str.characters.reversed())
    return string_original == string_invertido
}

assert(palindromo(str: "ala") == true, "el reto 2 tiene un error")

assert(palindromo(str: "casa") == false, "el reto 2 tiene un error")


3) Dos String con los mismos caracteres

import UIKit

// 2 strings de entrada
// 1 boolean de salida

//func reto3 (str1: String, str2: String) -> Bool {
//    if str1.characters.count == str2.characters.count {
//        let array1 = Array(str1.characters)
//        var array2 = Array(str2.characters)
//        for letra in array1 {
//            if array2.contains(letra) {
//                let indice = array2.index(of: letra)
//                array2.remove(at: indice!)
//            } else { // el array2 no contiene la letra del array1
//                return false
//            }
//        }
//        return true
//    }
//    return false
//}

func reto3 (str1: String, str2: String) -> Bool {
    let array1 = Array(str1.characters)
    let array2 = Array(str2.characters)
    return array1.count == array2.count && array1.sorted() == array2.sorted()
    
}

assert(reto3(str1: "saco", str2: "cosa") == true, "el reto 3 tiene un error")
assert(reto3(str1: "hola", str2: "hola") == true, "el reto 3 tiene un error")
assert(reto3(str1: "casa", str2: "camion") == false, "el reto 3 tiene un error")
assert(reto3(str1: "abc", str2: "cba") == true, "el reto 3 tiene un error")
assert(reto3(str1: "abca", str2: "cba") == false, "el reto 3 tiene un error")
assert(reto3(str1: "a", str2: "aa") == false, "el reto 3 tiene un error")


4) Un String dentro de otro String

import UIKit

// RETO 4: ¿Un string contiene a otro?
// 2 strings de entrada
// 1 boolean de salida

// str1: "Camion" str2 = "yo tengo un camion" --> str2 contiene str1 -> true
// str1: "yo tengo un camion", str2: "tengo" --> str1 contiene el str2 -> true

func reto4 (str1: String, str2: String) -> Bool {
    return str1.uppercased().contains(str2.uppercased()) || str2.uppercased().contains(str1.uppercased())
}

assert(reto4(str1: "Camion", str2: "yo tengo un camion") == true, "el reto 4 tiene un error")
assert(reto4(str1: "En verano voy a ir a la piscina con mis amigos", str2: "ir a la piscina") == true, "el reto 4 tiene un error")


5) Contar letras diferentes en un String

import UIKit

// Contar los caracteres de un string

func longitud (str: String) -> Int {
    var numero = 0;
    for _ in str.characters {
        numero += 1
    }
    return numero
}

assert(longitud(str: "mariposa") == 8, "longitud tiene un error")

assert(longitud(str: "") == 0, "longitud tiene un error")


6) Elimina letras duplicadas de un String

import UIKit

// eliminar las letras que se repiten en un string de forma que no queden repetidas

// "hello" -> "helo"
// "carro" -> "caro"
// "casa" -> "cas"
// "television" -> "telvison"

func eliminarRepetidas (str: String) -> String {
    var noRepetidas = [Character]()
    for letra in str.characters {
        if !noRepetidas.contains(letra) {
            noRepetidas.append(letra)
        }
    }
    return String(noRepetidas)
}

assert(eliminarRepetidas(str: "hello") == "helo", "el reto 6 esta mal")
assert(eliminarRepetidas(str: "carro") == "caro", "el reto 6 esta mal")
assert(eliminarRepetidas(str: "casa") == "cas", "el reto 6 esta mal")

assert(eliminarRepetidas(str: "television") == "telvison", "el reto 6 esta mal")


7) Elimina espacios de más en un String

import UIKit

// "El   perro   come    pienso" -> "El perro come pienso"

func reto7(str: String) -> String {
    var resultado = [Character]()
    var anteriorEsEspacio = false
    let espacio = Array(" ".characters).first
    
    for letra in str.characters {
        if letra == espacio {
            if anteriorEsEspacio == false {
                resultado.append(letra)
            }
            anteriorEsEspacio = true
        } else {
            anteriorEsEspacio = false
            resultado.append(letra)
        }
    }
    return String(resultado)
}

assert(reto7(str: "El perro   come     pienso") == "El perro come pienso", "El reto 7 tiene un error")


8) String rotados

import UIKit

// 2 strings de entrada
// 1 boolean

// "abcd" "dabc" -> true
// "abcd" "bcda" --> true
// "abcd" "abcd" --> true
// "abcd" "abdc" -> false

func reto8 (str1: String, str2: String) -> Bool {
    if (str1.characters.count != str2.characters.count) {
        return false
    } else {
        let a1 = Array(str1.characters)
        var a2 = Array(str2.characters)
    
        for _ in a2 {
            if a1 == a2 {
                return true
            } else {
                a2.append(a2.removeFirst())
            }
        }
        return false
    }
}

assert(reto8(str1: "abcd", str2: "dabc") == true, "el reto 8 tiene un error")
assert(reto8(str1: "abcd", str2: "bcda") == true, "el reto 8 tiene un error")
assert(reto8(str1: "abcd", str2: "abcd") == true, "el reto 8 tiene un error")
assert(reto8(str1: "abcd", str2: "abdc") == false, "el reto 8 tiene un error")


9) Los pangramas

import UIKit

// Tienen que estar todas las letras del alfabeto en el string
// a b c d e f g h i j k l m n ñ o p q r s t u v w x y z = 27

func reto9 (str: String) -> Bool {
    let entrada = Set(str.lowercased().characters)
    let alfabeto = entrada.filter( {$0 >= "a" && $0 <= "z"} )
    return alfabeto.count == 27
}

assert(reto9(str: "abcdefghijklmnñopqrstuvwxyz") == true, "error")
assert(reto9(str: "Mis amigas son tan buenas que me han venido para prepararme una fiesta sorpresa expectacular porque hoy es mi cumpleaños. Me han regalado unos zapatos, kiwis y un jersey.") == true, "error")


10) Vocales y consonantes

import UIKit

// Número de vocales y de consonantes
// Entrada: 1 String
// Salida: 2 Números (vocales, consonantes)

func reto10 (str: String) -> (vocales: Int, consonantes: Int) {
    // inicialización de constantes
    let vocales = Array("aeiou".characters)
    let consonantes = Array("bcdfghjklmnñpqrstvwxyz".characters)
    
    // inicialización de variables
    var nvocales = 0
    var nconsonantes = 0
    
    // reto
    for letra in str.lowercased().characters {
        if vocales.contains(letra) {
            nvocales += 1
        } else if consonantes.contains(letra) {
            nconsonantes += 1
        }
    }
    return (nvocales, nconsonantes)
}

assert(reto10(str: "hola caracola") == (6, 6), "error")



11) Tres letras diferentes

import UIKit

// Reto 11
// Entrada: 2 Strings
// Salida: 1 Boolean

// "casa" y "cosa" --> true
// "casas" y "casa" --> false
// "caballo" y "camello" --> true
// "amigo" y "elijo" --> true 
// "martillo" y "molinill" --> false

func reto11 (str1: String, str2: String) -> Bool {
    var string1 = Array(str1.lowercased().characters)
    var string2 = Array(str2.lowercased().characters)
    var letrasDiferentes = 0
    
    if string1.count == string2.count {
        while string1.count != 0 {
            if string1.removeFirst() != string2.removeFirst() {
                letrasDiferentes += 1
            }
        }
    } else {
        return false
    }
    return letrasDiferentes <= 3
}


assert(reto11(str1: "casa", str2: "cosa") == true, "error")
assert(reto11(str1: "casas", str2: "casa") == false, "error")
assert(reto11(str1: "caballo", str2: "camello") == true, "error")
assert(reto11(str1: "amigo", str2: "elijo") == true, "error")
assert(reto11(str1: "martillo", str2: "molinill") == false, "error")



12) El prefijo más largo

import UIKit

// Reto 12
// Entrada: 1 String de palabras separadas por espacios
// Salida: 1 String

// "muñeco muñeca" -> "muñec"
// "camion camioneta" -> "camion"
// "hola adios" -> ""
// "casa cosa cosita" -> "c"

func reto12 (str: String) -> String {
    let palabras = str.components(separatedBy: " ".lowercased())
    guard let primeraPalabra = palabras.first else { return "" }
    var prefijoActual = ""
    var mejorPrefijo = ""
    for letra in primeraPalabra.characters {
        prefijoActual.append(letra)
        
        for palabra in palabras {
            if !palabra.hasPrefix(prefijoActual) {
                return mejorPrefijo
            }
        }
        mejorPrefijo = prefijoActual
    }
    return mejorPrefijo
}

print(reto12(str: "casa caseta casino"))
print(reto12(str: "muñeco muñeca"))


13) Codificación de Strings

import UIKit


func reto13 (str: String) -> String {
    var resultado = ""
    var entrada = Array(str.characters)
    if str == "" {
        return resultado
    } else {
        while entrada.count != 0 {
            let letra = entrada.removeFirst()
            var contador = 1
            while entrada.count != 0 && letra == entrada.first {
                entrada.removeFirst()
                contador += 1
            }
            resultado.append("\(letra)\(contador)")
        }
        return resultado
    }
}

print(reto13(str: "abc")) // -> "a1b1c1"
print(reto13(str: "aabbcca")) // -> "a2b2c2a1"
print(reto13(str: "aaAAbB")) // -> "a2A2b1B1"


14) Permutaciones de Strings

import UIKit

// "a" -> "a"
// "ab" -> "ab" "ba"
// "abc" -> "abc" "acb" "bac" "bca" "cab" "cba"

func reto14(string: String, actual: String) {

    let longitud = string.characters.count
    let strArray = Array(string.characters)
    
    if longitud == 0 {
        print(actual)
    } else {

        // para cada caracter del string
        for i in 0..<longitud {
            
            // coger parte izquierda y parte derecha dejando la letra i del string en el limbo
            let izq = String(strArray[0..<i])
            let der = String(strArray[i+1..<longitud])
            
            // utilizar recursividad
            reto14(string: izq + der, actual: actual + String(strArray[i]))
            
        }
    }
}

reto14(string: "abc", actual: "")

15) Revertir las palabras de un String


import UIKit

// "Esto es un reto" -> "otsE se nu oter"

func reto15(str: String) -> String {
    let palabras = str.components(separatedBy: " ")
    let invertidas = palabras.map{String($0.characters.reversed())}
    return invertidas.joined(separator: " ")
}

print(reto15(str: "Esto es un reto"))



//Quizz










0 comentarios:

Publicar un comentario