Skip to content

Instantly share code, notes, and snippets.

@almaleh
Last active June 8, 2020 00:54
Show Gist options
  • Select an option

  • Save almaleh/7d230025aed9da24161be9074c177345 to your computer and use it in GitHub Desktop.

Select an option

Save almaleh/7d230025aed9da24161be9074c177345 to your computer and use it in GitHub Desktop.

Revisions

  1. almaleh revised this gist Jun 8, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion printXY.swift
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    // Solution A: Unwind the recursion using a stack
    // Solution A: Unwind the recursion using DFS

    func printXY(_ n: Int) -> [String] {

  2. almaleh revised this gist Jun 8, 2020. 1 changed file with 42 additions and 0 deletions.
    42 changes: 42 additions & 0 deletions printXY.swift
    Original 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) }
  3. almaleh created this gist Jun 8, 2020.
    42 changes: 42 additions & 0 deletions printXY.swift
    Original 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) }