Skip to content

Instantly share code, notes, and snippets.

@doppiogancio
Created April 25, 2019 09:59
Show Gist options
  • Save doppiogancio/dc0993b41d2d08c3ae3bc5759f516e2e to your computer and use it in GitHub Desktop.
Save doppiogancio/dc0993b41d2d08c3ae3bc5759f516e2e to your computer and use it in GitHub Desktop.
Generator of AB strings
package main
const (
letterA = "a"
letterB = "b"
)
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
if len(os.Args) != 3 {
fmt.Fprintf(os.Stderr, "Usage: %s number_of_As number_of_Bs\n", os.Args[0])
os.Exit(1)
}
// Input arguments
numberOfAs, _ := strconv.ParseInt(os.Args[1], 10, 32)
numberOfBs, _ := strconv.ParseInt(os.Args[2], 10, 32)
word, err := GenerateString(int(numberOfAs), int(numberOfBs))
if err != nil {
println(err.Error())
return
}
println(word)
}
package main
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
package main
import (
"github.com/pkg/errors"
"strings"
)
func GenerateString(numberOfAs, numberOfBs int) (string, error) {
char1 := letterA
char2 := letterB
max := numberOfAs
min := numberOfBs
generateWord := ""
if numberOfBs > numberOfAs {
char1 = letterB
char2 = letterA
max = numberOfBs
min = numberOfAs
}
if max > (2*min)+2 {
return "", errors.New("Wrong numbers")
}
x := minInt(max-min, min)
y := min - x
z := 0
if max > (2 * min) {
z = max - 2*min
}
// generateWord = AAB^x + AB^y + A^z
generateWord += strings.Repeat(char1+char1+char2, x)
generateWord += strings.Repeat(char1+char2, y)
generateWord += strings.Repeat(char1, z)
return generateWord, nil
}
@doppiogancio
Copy link
Author

Having in input two numbers "number of As" and "number of Bs", the goal is to generate a string containing the requested number A and B. The only constraint is that the generate word can not have a letter 3 times in a row.

Valid word
abaa

Not valid word
aaab

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment