Last active
December 11, 2015 09:38
-
-
Save vderyagin/4580889 to your computer and use it in GitHub Desktop.
Generating and printing Pascal Triangle of given size implemented in Go
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 characters
package main | |
import ( | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
) | |
func MakePascalTriangle(height int) [][]int { | |
pt := make([][]int, height) | |
for i := 0; i < height; i++ { | |
pt[i] = make([]int, i+1) | |
pt[i][0] = 1 | |
for j := 1; j < i; j++ { | |
pt[i][j] = pt[i-1][j] + pt[i-1][j-1] | |
} | |
pt[i][i] = 1 | |
} | |
return pt | |
} | |
func PrettyPrintPascalTriangle(height int) { | |
pt := MakePascalTriangle(height) | |
fieldWidth := make([]int, height) | |
for idx := range fieldWidth { | |
fieldWidth[idx] = len(strconv.Itoa(pt[height-1][idx])) + 1 | |
} | |
for _, row := range pt { | |
for col, item := range row { | |
fmt.Printf("%-*d", fieldWidth[col], item) | |
} | |
fmt.Println() | |
} | |
} | |
func main() { | |
var size int | |
var err error | |
if len(os.Args) == 1 { | |
size = 15 | |
} else { | |
size, err = strconv.Atoi(os.Args[1]) | |
} | |
if err != nil { | |
log.Fatal(err) | |
} | |
PrettyPrintPascalTriangle(size) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment