-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (72 loc) · 1.88 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"flag"
"fmt"
"image"
"image/color"
"os"
"github.com/kloster/ulam/prime"
"golang.org/x/image/bmp"
)
func main() {
var dim int
flag.IntVar(&dim, "dim", 100, "The dimension of the resulting image (it will be square)")
flag.Parse()
outputFile := "./UlamSpiral.bmp"
if len(flag.Args()) > 0 {
outputFile = flag.Arg(0)
}
// Force the dimension to be odd to avoid black lines in the image
if dim%2 == 0 {
dim++
}
// Create the image
img := image.NewRGBA(image.Rect(0, 0, dim, dim))
// Fill it with the Ulam spiral
fillWithUlamSpiral(img, color.RGBA{255, 255, 255, 255}, color.RGBA{0, 150, 0, 0})
// Create the ouput file
imgFile, err := os.Create(outputFile)
if err != nil {
fmt.Println(err)
return
}
defer imgFile.Close()
// Encode the image as a bmp file
if err = bmp.Encode(imgFile, img); err != nil {
fmt.Println(err)
}
}
// A straightforward implementation
func fillWithUlamSpiral(img *image.RGBA, compositeColor, primeColor color.RGBA) {
bounds := img.Bounds()
dim := bounds.Dx() // One of the dimensions of the image (it is square)
x, y := dim/2, dim/2 // The points to be painted. We start from the center
dx, dy := 1, -1 // The increment direction
alreadyMovedX, alreadyMovedY := 0, 0 // The points we already have moved in the current row/column
rowSize, columSize := 1, 1 // The current row/column size
totalPoints := dim * dim
for i := 0; i < totalPoints; i++ {
numToCheck := i + 1
if prime.Is(numToCheck) {
img.Set(x, y, primeColor)
} else {
img.Set(x, y, compositeColor)
}
if alreadyMovedX < rowSize {
x += dx
alreadyMovedX++
} else {
if alreadyMovedY < columSize {
y += dy
alreadyMovedY++
}
if alreadyMovedY >= columSize {
dx *= -1
dy *= -1
alreadyMovedX, alreadyMovedY = 0, 0
rowSize++
columSize++
}
}
}
}