Advertisement
kaenan

A Tour of Go: Exercise: Slices

Jan 14th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.61 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "golang.org/x/tour/pic"
  6. )
  7.  
  8. // Used in func duplicate
  9. var P = Pascal(11)
  10.  
  11. // The x, y of the pic
  12. const SIZE = 256
  13.  
  14. // Add a 0 at the beginning(right shift) or at the end (left shift)
  15. func Shift(x []uint8, left_or_right int) []uint8 {
  16.     if left_or_right == -1 {
  17.         return append(x, 0)
  18.     }
  19.  
  20.     L := []uint8{0}
  21.     n := len(x)
  22.  
  23.     for i := 0; i < n; i++ {
  24.         L = append(L, x[i])
  25.     }
  26.  
  27.     return L
  28. }
  29.  
  30. // Add the two shifts to form pascal triangle
  31. /*
  32.                 1
  33. (1)         1       1
  34. (2)     1       2       1
  35.     1       3       3       1
  36. ............................. so on ...
  37. [1 0] +
  38. [0 1] =
  39. [1 1] (1) --> Shift --> [1 1 0] +
  40.                         [0 1 1]
  41.                         [1 2 1] (2)
  42. ............................. so on ...
  43. */
  44. func Add(x, y []uint8) []uint8 {
  45.     L := make([]uint8, len(x))
  46.  
  47.     for i := range L {
  48.         L[i] = x[i] + y[i]
  49.     }
  50.  
  51.     return L
  52. }
  53.  
  54. func Pascal(x int) []uint8 {
  55.     if x == 1 {
  56.         return []uint8{1}
  57.     }
  58.  
  59.     L := make([]uint8, x)
  60.     L = Pascal(x - 1)
  61.  
  62.     return Add(Shift(L, -1), Shift(L, 1))
  63. }
  64.  
  65. // Take the P = Pascal(11) and copy it on each
  66. // row as many times as it can be copied
  67. func duplicate(x []uint8, d int) []uint8 {
  68.     if d < 11 {
  69.         for i := SIZE - d; i < SIZE; i++ {
  70.             x[i] = P[(i+d)-SIZE]
  71.         }
  72.         return x
  73.     }
  74.  
  75.     for i := SIZE - d; i < SIZE-d+11; i++ {
  76.         x[i] = P[(i+d)-SIZE]
  77.     }
  78.  
  79.     return duplicate(x, d-11)
  80. }
  81.  
  82. func Pic(dx, dy int) [][]uint8 {
  83.     rows := make([][]uint8, dy)
  84.  
  85.     // Init of each row
  86.     for i := range rows {
  87.         rows[i] = make([]uint8, dx)
  88.     }
  89.  
  90.     // Fill the rows
  91.     for i := range rows {
  92.         rows[i] = duplicate(rows[i], cap(rows[i]))
  93.     }
  94.  
  95.     return rows
  96.  
  97. }
  98.  
  99. func main() {
  100.     pic.Show(Pic)
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement