Wednesday, March 26, 2014

How to Solve Diagonal Print

Given a string and a number, and print the string diagonally filling in empty space with periods and going down as many lines as the given number. So "Peter piper picked a peck of pickled peppers" with n = 10 becomes
P.........r......... .........i.........p...
.e......... .........p.........c.........e..
..t.........p.........e.........k.........r.
...e.........i.........c.........l.........s
....r.........c.........k.........e.........
..... .........k......... .........d........
......P.........e.........o......... .......
.......i.........d.........f.........P...... 
........p......... ......... .........e.....
.........e.........a.........p.........p....
package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    str := os.Args[1]
    n, _ := strconv.Atoi(os.Args[2])
    for i := 0; i < n; i++ {
        for k := 0; k < i; k++ {
            fmt.Print(".")
        }
        for j := 0; j < len(str)-i; j++ {
            if (j % n == 0 && j+1 < len(str)) {
                fmt.Print(string(str[j+i]))
            } else {
                fmt.Print(".")
            }
        }
        fmt.Println()
    }
}