Use Byte Slice Instead of Strings

Hello Folks. This is just a quick post on the topic and a reminder for myself and everybody to ALWAYS USE []BYTE INSTEAD OF STRINGS. []Byte is marginally faster than a simple Strings. In fact, I would say using []byte should be the standard instead of strings. Sample code: package solutions import "fmt" const ( //INPUT input INPUT = "1321131112" //LIMIT limit LIMIT = 50 ) //LookAndSay translates numbers according to Look and Say algo func LookAndSay(s string, c chan string) { charCount := 1 look := "" for i := range s { if i+1 < len(s) { if s[i] == s[i+1] { charCount++ } else { look += fmt.Sprintf("%d%s", charCount, string(s[i])) charCount = 1 } } else { look += fmt.Sprintf("%d%s", charCount, string(s[i])) } } c <- look } //GetLengthOfLookAndSay Retrieve the Length of a lookandsay done Limit times func GetLengthOfLookAndSay() { c := make(chan string, 0) go LookAndSay(INPUT, c) finalString := <-c for i := 0; i <= LIMIT-2; i++ { go LookAndSay(finalString, c) finalString = <-c // fmt.Println(finalString) } fmt.Println("Lenght of final String:", len(finalString)) } This, with the limit raised to 50 run for ~1 hour. Even with the routines although they were just for show since they had to wait for each others input. ...

December 29, 2015 · 2 min · hannibal

Recursive Letter Frequency Count

Hello everybody! I wanted to do a sort post about word frequency count. I did it many times now and I was curious as how a recursive solution would perform as opposed to looping. So I wrote it up quickly and added a few benchmarks with different sized data. First…. The code: var freqMap = make(map[string]int, 0) func countLettersRecursive(s string) string { if len(s) == 0 { return s } freqMap[string(s[0])]++ return countLettersRecursive(s[1:]) } func countLettersLoop(s string) { for _, v := range s { freqMap[string(v)]++ } } Very simple. The first run with a small sample: “asdfasdfasdfasdfasdf” ...

December 23, 2015 · 1 min · hannibal

Go Development Environment

Hello folks. Here is a little something I’ve put together, since I’m doing it a lot. Go Development Environment If I have a project I’d like to contribute, like GoHugo, I have to setup a development environment, because most of the times, I’m on a Mac. And on OSX things work differently. I like to work in a Linux environment since that’s what most of the projects are built on. So here you go. Just download the files, and say vagrant up which will do the magic. ...

December 8, 2015 · 1 min · hannibal

Go JIRA API client

Hi folks. So, I was playing around and created a client for JIRA written in Go. It was nice to do some JSON transformation. And sending POSTS was really trivial. It’s still in it’s infancy and I have a couple of more features I want to implement, but, here is the code. package main import ( "bytes" "encoding/json" "flag" "fmt" "io/ioutil" "log" "net/http" "os" "github.com/BurntSushi/toml" ) var configFile = "~/.jira_config.toml" var parameter string var flags struct { Comment string Description string IssueKey string Priority string Resolution string Title string Project string } //Issue is a representation of a Jira Issue type Issue struct { Fields struct { Project struct { Key string `json:"key"` } `json:"project"` Summary string `json:"summary"` Description string `json:"description"` Issuetype struct { Name string `json:"name"` } `json:"issuetype"` Priority struct { ID string `json:"id"` } `json:"priority"` } `json:"fields"` } //Transition defines a transition json object. Used for starting, stoppinp //generally for state stranfer type Transition struct { Fields struct { Resolution struct { Name string `json:"name"` } `json:"resolution"` } `json:"fields"` Transition struct { ID string `json:"id"` } `json:"transition"` } //Credentials a representation of a JIRA config which helds API permissions type Credentials struct { Username string Password string URL string } func init() { flag.StringVar(&flags.Comment, "m", "Default Comment", "A Comment when changing the status of an Issue.") flag.StringVar(&flags.Description, "d", "Default Description", "Provide a description for a newly created Issue.") flag.StringVar(&flags.Priority, "p", "2", "The priority of an Issue which will be set.") flag.StringVar(&flags.IssueKey, "k", "", "Issue key of an issue.") flag.StringVar(&flags.Resolution, "r", "Done", "Resolution when an issue is closed. Ex.: Done, Fixed, Won't fix.") flag.StringVar(&flags.Title, "t", "Default Title", "Title of an Issue.") flag.StringVar(&flags.Project, "o", "IT", "Define a Project to create a ticket in.") flag.Parse() } func (cred *Credentials) initConfig() { if _, err := os.Stat(configFile); err != nil { log.Fatalf("Error using config file: %v", err) } if _, err := toml.DecodeFile(configFile, cred); err != nil { log.Fatal("Error during decoding toml config: ", err) } } func main() { if len(flag.Args()) < 1 { log.Fatal("Please provide an action to take. Usage information:") } parameter = flag.Arg() switch parameter { case "close": closeIssue(flags.IssueKey) case "start": startIssue(flags.IssueKey) case "create": createIssue() } } func closeIssue(issueKey string) { if issueKey == "" { log.Fatal("Please provide an issueID with -k") } fmt.Println("Closing issue number: ", issueKey) var trans Transition //TODO: Add the ability to define a comment for the close reason trans.Fields.Resolution.Name = flags.Resolution trans.Transition.ID = "2" marhsalledTrans, err := json.Marshal(trans) if err != nil { log.Fatal("Error occured when marshaling transition: ", err) } fmt.Println("Marshalled:", trans) sendRequest(marhsalledTrans, "POST", issueKey+"/transitions?expand=transitions.fields") } func startIssue(issueID string) { if issueID == "" { log.Fatal("Please provide an issueID with -i") } fmt.Println("Starting issue number:", issueID) } func createIssue() { fmt.Println("Creating new issue.") var issue Issue issue.Fields.Description = flags.Description issue.Fields.Priority.ID = flags.Priority issue.Fields.Summary = flags.Title issue.Fields.Project.Key = flags.Project issue.Fields.Issuetype.Name = "Task" marshalledIssue, err := json.Marshal(issue) if err != nil { log.Fatal("Error occured when Marshaling Issue:", err) } sendRequest(marshalledIssue, "POST", "") } func sendRequest(jsonStr []byte, method string, url string) { cred := &Credentials{} cred.initConfig() fmt.Println("Json:", string(jsonStr)) req, err := http.NewRequest(method, cred.URL+url, bytes.NewBuffer(jsonStr)) req.Header.Set("Content-Type", "application/json") req.SetBasicAuth(cred.Username, cred.Password) client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println("response Status:", resp.Status) fmt.Println("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) fmt.Println("response Body:", string(body)) } It can also be found under my github page: GoJira Github. ...

November 20, 2015 · 3 min · hannibal

Go Progress Quest

Hi Folks. I started to build a Progress Quest type of web app in Go. If you’d like to join, or just tag along, please drop by here => Go Progress Quest and feel free to submit an issue if you have an idea, or would like to contribute! I will try and document the Progress. Thank you for reading! Gergely.

November 9, 2015 · 1 min · hannibal

Circular buffer in Go

I’m proud of this one too. No peaking. I like how go let’s you do this kind of stuff in a very nice way. package circular import "fmt" //TestVersion testVersion const TestVersion = 1 //Buffer buffer type type Buffer struct { buffer []byte full int size int s, e int } //NewBuffer creates a new Buffer func NewBuffer(size int) *Buffer { return &Buffer{buffer: make([]byte, size), s: 0, e: 0, size: size, full: 0} } //ReadByte reads a byte from b Buffer func (b *Buffer) ReadByte() (byte, error) { if b.full == 0 { return 0, fmt.Errorf("Danger Will Robinson: %s", b) } readByte := b.buffer[b.s] b.s = (b.s + 1) % b.size b.full-- return readByte, nil } //WriteByte writes c byte to the buffer func (b *Buffer) WriteByte(c byte) error { if b.full+1 > b.size { return fmt.Errorf("Danger Will Robinson: %s", b) } b.buffer[b.e] = c b.e = (b.e + 1) % b.size b.full++ return nil } //Overwrite overwrites the oldest byte in Buffer func (b *Buffer) Overwrite(c byte) { b.buffer[b.s] = c b.s = (b.s + 1) % b.size } //Reset resets the buffer func (b *Buffer) Reset() { *b = *NewBuffer(b.size) } func (b *Buffer) String() string { return fmt.Sprintf("Buffer: %d, %d, %d, %d", b.buffer, b.s, b.e, b.size) }

October 15, 2015 · 1 min · hannibal

DataMunger Kata with Go

Quickly wrote up the Data Munger code kata in Go. Next time, I want better abstractions. And a way to select columns based on their header data. For now, this is not bad. package main import ( "bufio" "fmt" "log" "math" "os" "regexp" "strconv" "strings" ) //Data which is Data type Data struct { columnName string compareOne float64 compareTwo float64 } func main() { // datas := []Data{WeatherData{}, FootballData{}} fmt.Println("Minimum weather data:", GetDataMinimumDiff("weather.dat", , 1, 2)) fmt.Println("Minimum football data:", GetDataMinimumDiff("football.dat", 1, 6, 7)) } //GetDataMinimumDiff gathers data from file to fill up Columns. func GetDataMinimumDiff(filename string, nameColumn int, compareColOne int, compareColTwo int) Data { data := Data{} minimum := math.MaxFloat64 readLines := ReadFile(filename) for _, value := range readLines { valueArrays := strings.Split(value, ",") name := valueArrays[nameColumn] trimmedFirst, _ := strconv.ParseFloat(valueArrays[compareColOne], 64) trimmedSecond, _ := strconv.ParseFloat(valueArrays[compareColTwo], 64) diff := trimmedFirst - trimmedSecond diff = math.Abs(diff) if diff <= minimum { minimum = diff data.columnName = name data.compareOne = trimmedFirst data.compareTwo = trimmedSecond } } return data } //ReadFile reads lines from a file and gives back a string array which contains the lines. func ReadFile(fileName string) (fileLines []string) { file, err := os.Open(fileName) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) //Skipping the first line which is the header. scanner.Scan() for scanner.Scan() { line := scanner.Text() re := regexp.MustCompile("\\w+") lines := re.FindAllString(line, -1) if len(lines) > { fileLines = append(fileLines, strings.Join(lines, ",")) } } if err := scanner.Err(); err != nil { log.Fatal(err) } return }

October 4, 2015 · 2 min · hannibal

Sieve of Eratosthenes in Go

I’m pretty proud of this one as well. package sieve //Sieve Uses the Sieve of Eratosthenes to calculate primes to a certain limit func Sieve(limit int) []int { var listOfPrimes []int markers := make([]bool, limit) for i := 2; i < limit; i++ { if !markers[i] { for j := i + i; j < limit; j += i { markers[j] = true } listOfPrimes = append(listOfPrimes, i) } } return listOfPrimes }

July 30, 2015 · 1 min · hannibal