Skip to content

Instantly share code, notes, and snippets.

@asm-jaime
Created June 13, 2016 07:01
Show Gist options
  • Save asm-jaime/21b4b07721d105e8d96d341dc931e053 to your computer and use it in GitHub Desktop.
Save asm-jaime/21b4b07721d105e8d96d341dc931e053 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"encoding/json"
"fmt"
"os"
"sort"
"strconv"
)
const file_path string = "data.json"
const num_count int = 6
type SomeJson struct {
Slice []int `json:"data"`
}
type IntSlice []int
var this_slice IntSlice
var this_ints []int
var this_str string
var sum_count int = 0
func main() {
this_slice = *sequence_int(num_count)
permutate(num_count)
sort.Ints(this_ints)
this_json := &SomeJson{Slice: this_ints}
res_json, err := json.Marshal(this_json)
if err != nil {
fmt.Print("error! make json object failed!")
return
}
fmt.Print(string(res_json))
open_write(string(res_json))
fmt.Print(len(res_json))
}
func permutate(n int) {
if n == 0 {
this_str = ""
sum_count++
for _, cell := range this_slice {
this_str += strconv.Itoa(cell)
}
this_int, _ := strconv.Atoi(this_str)
this_ints = append(this_ints, this_int)
return
} else {
for j := 0; j < n; j++ {
this_slice.swap(j, n-1)
permutate(n - 1)
this_slice.swap(j, n-1)
}
}
}
func (slice IntSlice) swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
func sequence_int(num int) *[]int {
seq := make([]int, num)
for i := 0; i < num; i++ {
seq[i] = i + 1
}
return &seq
}
func open_write(data string) {
if data == "" {
fmt.Print("error! nothing to write!")
return
}
foi, err := os.OpenFile(file_path, os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
fmt.Print("error! open file failed!")
return
}
writer := bufio.NewWriter(foi)
defer foi.Close()
defer writer.Flush()
writer.WriteString(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment