Skip to content

Instantly share code, notes, and snippets.

@MilyMilo
Created March 29, 2018 16:30
Show Gist options
  • Save MilyMilo/b08a5bf2f68b4f6895203e64dacde643 to your computer and use it in GitHub Desktop.
Save MilyMilo/b08a5bf2f68b4f6895203e64dacde643 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
"strings"
)
const (
RIGHT = iota
UP
LEFT
DOWN
)
func generate(size, max int) {
matrix := make([][]string, size)
for i := 0; i < size; i++ {
matrix[i] = make([]string, size)
}
dir := RIGHT
y := size / 2
var x int
if size%2 == 0 {
x = y - 1
} else {
x = y
}
for j := 1; j <= size*size; j++ {
if j > max {
matrix[y][x] = " "
} else if isPrime(j) {
matrix[y][x] = "#"
} else {
matrix[y][x] = "."
}
switch dir {
case RIGHT:
if x <= size-1 && matrix[y-1][x] == "" && j > 1 {
dir = UP
}
case UP:
if matrix[y][x-1] == "" {
dir = LEFT
}
case LEFT:
if x == 0 || matrix[y+1][x] == "" {
dir = DOWN
}
case DOWN:
if matrix[y][x+1] == "" {
dir = RIGHT
}
}
switch dir {
case RIGHT:
x += 1
case UP:
y -= 1
case LEFT:
x -= 1
case DOWN:
y += 1
}
}
for _, row := range matrix {
out := strings.Join(row, "")
out = strings.Replace(out, " ", "o", -1)
if !strings.ContainsAny(out, "# .") {
continue
}
out = strings.TrimRight(out, "o")
out = strings.Replace(out, "o", " ", -1)
fmt.Println(out)
}
}
func isPrime(a int) bool {
if a == 2 {
return true
}
if a <= 1 || a%2 == 0 {
return false
}
max := int(math.Sqrt(float64(a)))
for n := 3; n <= max; n += 2 {
if a%n == 0 {
return false
}
}
return true
}
func getSize(max int) float64 {
for {
sqrt := math.Sqrt(float64(max))
if sqrt*sqrt == float64(int(sqrt)*int(sqrt)) {
return math.Sqrt(float64(max))
}
max++
}
}
func main() {
var input int
fmt.Scanf("%d", &input)
if input != 1 {
generate(int(getSize(input)), input)
} else {
fmt.Println(".")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment