Skip to content

Instantly share code, notes, and snippets.

@rachelcarmena
Last active September 20, 2021 14:21
Show Gist options
  • Save rachelcarmena/cad9781f96cc14e1930e190a5595617d to your computer and use it in GitHub Desktop.
Save rachelcarmena/cad9781f96cc14e1930e190a5595617d to your computer and use it in GitHub Desktop.
FormParens
package kata
import (
"strings"
"strconv"
)
//
// First possible value (odd number):
//
// - If n == 2: (()) ~ 0011
// - If n == 3: ((())) ~ 000111
// - If n == 4: (((()))) ~ 00001111
// - ...
//
// Last possible value (not included): 011_ ~ ())_
//
func FormParens(n int) []string {
if n == 1 { return []string{"()"} }
var result []string
maxLength := n*2
first := (1 << n) - 1
last := 3 << (maxLength - 3)
for i := first; i < last; i = i+2 { // Just odd numbers
candidate := strings.Map(toParentheses, toBinary(i, maxLength))
if validExpression(candidate) {
result = append(result, candidate)
}
}
return result
}
func toParentheses(bit rune) rune {
if bit == '0' {
return '('
}
return ')'
}
func toBinary(value, length int) string {
result := strconv.FormatInt(int64(value), 2)
return strings.Repeat("0", length - len(result)) + result
}
func validExpression(expr string) bool {
open := 0
closed := 0
for i := 0; i < len(expr); i++ {
if expr[i] == '(' {
open ++
} else {
closed ++
}
if closed > open {
return false
}
}
return (open == closed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment