forked from mouredev/retos-programacion-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b34ecf2
commit 56eb553
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
Retos/Reto #36 - PERMUTACIONES [Media]/swift/radostinaTachova.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
//: PERMUTACIONES | ||
|
||
import Foundation | ||
|
||
//Explicación | ||
//Empezamos con prefijo vacio y en sufijo está la palabra que se quiere permutar. | ||
//Se van recoriendo las letras del sufijo y se van creando todos los posibles prefijos añadiendo letra a letra. | ||
//En el ejemplo: con prefijo letra s, hacemos prefijo + o, prefijo + l que serán los nuevos prefijos, y así hasta que no haya letras en sufijo y hayamos encontrado una permutación. | ||
|
||
// PREF || SUF PREF || SUF PREF(¡RESULTADOS!) | ||
// | ||
// s ---->ol ---> so ---> l ----> sol | ||
// ---> sl ---> o ----> slo | ||
// | ||
// o ---->sl ---> os ---> l ----> osl | ||
// ---> ol ---> s ----> ols | ||
// | ||
// l ---->so ---> ls ---> o ----> lso | ||
// ---> lo ---> s ----> los | ||
|
||
func perm(pref: String, suf: String, permutations: inout [String] ) { | ||
if suf.count == 0 { | ||
permutations.append(pref) | ||
} | ||
suf.forEach({ letter in | ||
let newPref = pref + String(letter) | ||
var newSuf = suf | ||
if let index = suf.firstIndex(of: letter) { | ||
newSuf = String(suf.prefix(upTo: index) + suf.suffix(from: suf.index(after: index))) | ||
} | ||
perm(pref: newPref, suf: newSuf , permutations: &permutations) | ||
}) | ||
} | ||
|
||
var myString = "sol" | ||
var permutations: [String] = [] | ||
perm(pref: "", suf: myString, permutations: &permutations) | ||
|
||
print(permutations) |