Created
March 10, 2021 15:40
-
-
Save quackduck/c8cd3f955cff38689f55564ed77605ea to your computer and use it in GitHub Desktop.
Implement a kolakoski sequence generator: OEIS:A000002
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" | |
"strconv" | |
"strings" | |
) | |
var ( | |
// n is the number of terms to calculate | |
n int = 1000 | |
) | |
func main() { | |
seq := make([]int, 0, n+1) // n+1 because inst 2 could add one extra | |
var ind, i, toAppend int | |
seq = append(seq, 1, 2, 2) | |
ind = 2 // follow third instruction next | |
i += 3 | |
for i < n { // i also functions as the length of the array | |
if seq[ind] == 1 { // add one number | |
toAppend = getUniq(seq) | |
if seq[len(seq)-1] == 1 { | |
toAppend = 2 | |
} else { | |
toAppend = 1 | |
} | |
seq = append(seq, toAppend) | |
i++ // we added a number | |
ind++ // next instruction | |
} else { // add two numbers | |
toAppend = getUniq(seq) | |
seq = append(seq, toAppend, toAppend) | |
i += 2 // we added two numbers | |
ind++ | |
} | |
} | |
seq = seq[:n] | |
printFormatted(seq) | |
} | |
func getUniq(seq []int) int { | |
if seq[len(seq)-1] == 1 { | |
return 2 | |
} else { | |
return 1 | |
} | |
} | |
func printFormatted(a []int) { | |
b := make([]string, len(a)) | |
for i, v := range a { | |
b[i] = strconv.Itoa(v) | |
} | |
fmt.Println(strings.Join(b, ", ")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment