Created
March 26, 2019 22:06
-
-
Save sarathsp06/1a400466975b7bd65917a444df4cc4fe to your computer and use it in GitHub Desktop.
Snapchat IP Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
) | |
// memoise this :D | |
func splitAsIP(s string, count int) []string { | |
if !isValidIP(s, count) { | |
return nil | |
} | |
if count == 1 { | |
return []string{s} | |
} | |
count-- | |
splitAt := 3 | |
if s[0] == '0' { | |
splitAt = 1 | |
} else if len(s) < splitAt { | |
splitAt = len(s) | |
} | |
var splits []string | |
for i := 1; i <= splitAt; i++ { | |
if !isValidSplit(s[:i]) { | |
continue | |
} | |
parts := splitAsIP(s[i:], count) | |
for _, part := range parts { | |
splits = append(splits, s[:i]+"."+part) | |
} | |
} | |
return splits | |
} | |
func isValidSplit(s string) bool { | |
i, err := strconv.Atoi(s) | |
return err == nil && i < 256 | |
} | |
func isValidIP(s string, count int) bool { | |
return len(s) >= count && len(s) <= count*3 | |
} | |
func main() { | |
fmt.Println(splitAsIP("2542540123", 4)) | |
} |
Author
sarathsp06
commented
Mar 26, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment