Skip to content

Instantly share code, notes, and snippets.

@alexei-led
Last active March 10, 2016 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexei-led/097ede7c2b3f0f9b9b45 to your computer and use it in GitHub Desktop.
Save alexei-led/097ede7c2b3f0f9b9b45 to your computer and use it in GitHub Desktop.
Print list of valid IPs from passed string
package main
import (
"fmt"
"strconv"
)
type tree struct {
nodes []*tree
val int
}
func (t *tree) buildTree(s string) {
n := 3
if len(s) < n {
n = len(s)
}
for i := 1; i <= n; i++ {
x, _ := strconv.Atoi(string(s[0:i]))
if x < 256 {
node := tree{make([]*tree, 3), x}
node.buildTree(string(s[i:]))
t.nodes[i-1] = &node
}
}
}
func printIP(t *tree) {
fmt.Println("List of valid IPs")
var walk func(*tree, int, string)
walk = func(t *tree, level int, prefix string) {
if level > 4 {
return
}
if t.nodes[0] == nil && t.nodes[1] == nil && t.nodes[2] == nil && level == 4 {
fmt.Println(prefix + "." + strconv.Itoa(t.val))
}
for i := 0; i < 3; i++ {
if t.nodes[i] != nil {
var s string
if level > 0 {
if prefix != "" {
s = prefix + "." + strconv.Itoa(t.val)
} else {
s = strconv.Itoa(t.val)
}
}
walk(t.nodes[i], level+1, s)
}
}
}
walk(t, 0, "")
}
func main() {
var s string
fmt.Scanln(&s)
// s := "12323201" // uncomment to try hard coded string, without reading from stdio
if len(s) < 4 || len(s) > 12 {
return
}
r := tree{make([]*tree, 3), -1}
r.buildTree(s)
printIP(&r)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment