Last active
June 8, 2020 00:54
-
-
Save almaleh/7d230025aed9da24161be9074c177345 to your computer and use it in GitHub Desktop.
Revisions
-
almaleh revised this gist
Jun 8, 2020 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ // Solution A: Unwind the recursion using DFS func printXY(_ n: Int) -> [String] { -
almaleh revised this gist
Jun 8, 2020 . 1 changed file with 42 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,3 +1,5 @@ // Solution A: Unwind the recursion using a stack func printXY(_ n: Int) -> [String] { var explored = Set<Int>() @@ -38,5 +40,45 @@ func printXY(_ n: Int) -> [String] { return output } let res = printXY(4) res.forEach { print($0) } // Solution B: no stack let n = 4 var array = [Character](repeating: "X", count: n) outerLoop: do { print(String(array)) for i in 0..<n { if array[i] == "X" { array[i] = "Y" continue outerLoop } array[i] = "X" } } // Solution C: Recursive func printXY(_ n: Int) -> [String] { guard n > 1 else { return ["X", "Y"] } let next = printXY(n - 1) var output = [String]() for element in next { output.append(element + "X") output.append(element + "Y") } return output } let res = printXY(4) res.forEach { print($0) } -
almaleh created this gist
Jun 8, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,42 @@ func printXY(_ n: Int) -> [String] { var explored = Set<Int>() var stack = [n] var output = [String]() while let last = stack.last { let next = last - 1 if last == 1 { // base case output = ["X", "Y"] explored.insert(last) } else { if explored.contains(next) { var newOutput = [String]() for element in output { newOutput.append(element + "X") newOutput.append(element + "Y") } output = newOutput } else { explored.insert(next) stack.append(next) continue } } stack.popLast() } return output } let res = printXY(4) res.forEach { print($0) }