How to resolve the algorithm Sierpinski carpet step by step in the Swift programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sierpinski carpet step by step in the Swift programming language

Table of Contents

Problem Statement

Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N.

For example, the Sierpinski carpet of order   3   should look like this: The use of the   #   character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sierpinski carpet step by step in the Swift programming language

Source code in the swift programming language

import Foundation
func sierpinski_carpet(n:Int) -> String {
    func middle(str:String) -> String {
        let spacer = str.stringByReplacingOccurrencesOfString("#", withString:" ", options:nil, range:nil)
        return str + spacer + str
    }
    
    var carpet = ["#"]
    for i in 1...n {
        let a = carpet.map{$0 + $0 + $0}
        let b = carpet.map(middle)
        carpet = a + b + a
    }
    return "\n".join(carpet)
}

println(sierpinski_carpet(3))

  

You may also check:How to resolve the algorithm Gamma function step by step in the R programming language
You may also check:How to resolve the algorithm Compiler/virtual machine interpreter step by step in the Go programming language
You may also check:How to resolve the algorithm Generator/Exponential step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Loops/Continue step by step in the Julia programming language
You may also check:How to resolve the algorithm Write entire file step by step in the D programming language