Swift Pattern printing: Print rectangle - COFPROG

Swift Pattern printing: Print rectangle

Print rectangle of n character

    

//This is for single string

    func frameGenrator(n:Int) -> String {

        var result = ""

        for _ in 1...n {

            result += "*"

        }

        

        for _ in 1...(n - 2) {

            result += "\n"

            result += "*"

            for _ in 1...(n - 2){

                result += " "

            }

            result += "*"

        }

        

        result += "\n"

        

        for _ in 1...n {

            result += "*"

        }

        return result


    }


//This is for array of string

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

        var result = [String]()

        var line = ""

        for _ in 1...n {

            line += "*"

        }

        result.append(line)


        for _ in 1...(n - 2) {

            var spacesLine = ""

            spacesLine += "*"

            for _ in 1...(n - 2){

                spacesLine += " "

            }

            spacesLine += "*"

            result.append(spacesLine)

        }

        


        line = ""

        for _ in 1...n {

            line += "*"

        }

        result.append(line)

        return result


    }


    print(frameGenrator(n: 8))


 


Previous
Next Post »

BOOK OF THE DAY