Created
August 23, 2020 00:13
-
-
Save michaelrockhold/165f5e85e79eefebb0b7e0dfce5f0be2 to your computer and use it in GitHub Desktop.
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
// | |
// main.swift | |
// string-permuter | |
// | |
// Created by Michael Rockhold on 8/22/20. | |
// Copyright © 2020 Michael Rockhold. All rights reserved. | |
// | |
import Foundation | |
func permuter(s: String, feedback: (String)->Void) { | |
func swapChars(_ s: String, i1: String.Index, i2: String.Index) -> String { | |
let c1 = s[i1] | |
let c2 = s[i2] | |
var ss = s | |
ss.replaceSubrange(i1...i1, with: [c2]) | |
ss.replaceSubrange(i2...i2, with: [c1]) | |
return ss | |
} | |
func permute(_ s: String, left: String.Index, right: String.Index) { | |
// Base case | |
if left == right { | |
feedback(s) | |
} | |
else { | |
var idx = left | |
repeat { | |
let swapped = swapChars(s, i1: left, i2: idx) | |
var nextLeft = left | |
s.formIndex(after: &nextLeft) | |
permute(swapped, left: nextLeft, right: right) | |
s.formIndex(after: &idx) | |
} while idx != right | |
} | |
} | |
permute(s, left: s.startIndex, right: s.endIndex) | |
} | |
permuter(s: "ABC") { ss in | |
print(ss) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment