This commit is contained in:
sunwoo1524 2024-01-14 15:39:36 +09:00
commit c55dac1b0f
4 changed files with 133 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
brainfuck-encoder

11
README.md Normal file
View file

@ -0,0 +1,11 @@
# Brainfuck Encoder
Encode ASCII text to brainfuck code.
## Using
```
# build
go build .
# run
./brainfuck-encoder "ASCII Text" [--format|-F]
```

3
go.mod Normal file
View file

@ -0,0 +1,3 @@
module git.worldc.one/sunwoo1524/brainfuck-encoder
go 1.21.6

118
main.go Normal file
View file

@ -0,0 +1,118 @@
package main
import (
"fmt"
"os"
"regexp"
"slices"
)
// encode text to brainfuck
func encode(text string, format bool) (bf string) {
pointer := 0
ascii_codes := []rune{}
bf += "++++++++++[\n"
for _, c := range text {
if !slices.Contains(ascii_codes, c) {
ascii_codes = append(ascii_codes, c)
bf += "> "
for i := 1; i <= int(int(c)/10); i++ {
if i%5 == 0 {
bf += "+ "
continue
}
bf += "+"
}
bf += "\n"
}
}
for i := 0; i < len(ascii_codes); i++ {
bf += "<"
}
bf += "-\n]\n"
printed_chars := []rune{}
for _, c := range text {
var next_pointer int
for i, ascii := range ascii_codes {
if ascii == c {
next_pointer = i + 1
break
}
}
pointer_delta := next_pointer - pointer
delta_abs := pointer_delta
if pointer_delta < 0 {
delta_abs = -pointer_delta
}
for i := 0; i < delta_abs; i++ {
if pointer_delta < 0 {
bf += "<"
continue
}
bf += ">"
}
is_printed := false
for _, printed_char := range printed_chars {
if c == printed_char {
is_printed = true
}
}
if !is_printed {
for i := 1; i <= int(c)%10; i++ {
if i%5 == 0 {
bf += "+ "
continue
}
bf += "+"
}
printed_chars = append(printed_chars, c)
}
bf += " .\n"
pointer = next_pointer
}
if !format {
re := regexp.MustCompile(`[^><+-.,\[\]]+`)
bf = re.ReplaceAllString(bf, "")
}
return bf
}
func main() {
format := false // if format is true, turn on formatter
// check there are arguments
if len(os.Args) < 2 {
panic("arguments error")
} else if len(os.Args) >= 3 {
// parse flag
if os.Args[2] == "--format" || os.Args[2] == "-F" {
format = true
}
}
// get ascii text
text := os.Args[1]
encoded_code := encode(text, format)
fmt.Println(encoded_code)
}