fork(2) download
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "strings"
  6. )
  7.  
  8. func nextRow(prevRow []int) []int {
  9. current := make([]int, 0, len(prevRow)+1)
  10.  
  11. current = append(current, 1)
  12.  
  13. for i := 1; i < len(prevRow); i++ {
  14. current = append(current, prevRow[i-1]+prevRow[i])
  15. }
  16.  
  17. current = append(current, 1)
  18.  
  19. return current
  20. }
  21.  
  22. func Triangle(rows int) [][]int {
  23. triangle := [][]int{}
  24. if rows <= 0 {
  25. return triangle
  26. }
  27. triangle = append(triangle, []int{1})
  28. for i := 1; i < rows; i++ {
  29. triangle = append(triangle, nextRow(triangle[i-1]))
  30. }
  31. return triangle
  32. }
  33.  
  34. func present(line []int) string {
  35. words := make([]string, len(line), len(line))
  36. for i, v := range line {
  37. words[i] = fmt.Sprintf("%4v ", v)
  38. }
  39. return strings.Join(words, " ")
  40. }
  41.  
  42. func main() {
  43. tri := Triangle(10)
  44. for _, line := range tri {
  45. fmt.Println(present(line))
  46. }
  47. }
  48.  
Success #stdin #stdout 0s 790016KB
stdin
Standard input is empty
stdout
   1 
   1     1 
   1     2     1 
   1     3     3     1 
   1     4     6     4     1 
   1     5    10    10     5     1 
   1     6    15    20    15     6     1 
   1     7    21    35    35    21     7     1 
   1     8    28    56    70    56    28     8     1 
   1     9    36    84   126   126    84    36     9     1