Skip to content

Instantly share code, notes, and snippets.

@kuzzmi
Last active October 31, 2023 08:22
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 kuzzmi/754f7cd4a8487b77025b585d54040c73 to your computer and use it in GitHub Desktop.
Save kuzzmi/754f7cd4a8487b77025b585d54040c73 to your computer and use it in GitHub Desktop.
/*
Q1. We need a way to generate a random sequence of lower case letters and digits, and in the future may need other combinations. For example,
1. 7ns32bkzgg
2. 85674
3. mxxk9gk6a4n9thq59mfx
Please provide a solution in Go (any recent version of Go) - we are mostly interested in the interface and less interested in the implementation.
*/
package main
import (
"fmt"
"math/rand"
"time"
)
// This would allow
type Charset string
const (
CharsetNumeric Charset = "0123456789"
CharsetAlphaLower Charset = "abcdefghijklmnopqrstuvwxyz"
CharsetAlphaUpper Charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CharsetAlpha Charset = CharsetAlphaLower + CharsetAlphaUpper
CharsetAlphaLowerNumeric Charset = CharsetAlphaLower + CharsetNumeric
CharsetAlphaNumeric Charset = CharsetAlpha + CharsetNumeric
)
func generateRandomSequence(length int, charset Charset) string {
seededRand := rand.New(rand.NewSource(time.Now().UnixNano()))
randomSequence := make([]byte, length)
for i := range randomSequence {
randomSequence[i] = byte(charset[seededRand.Intn(len(charset))])
}
return string(randomSequence)
}
func main() {
fmt.Println(generateRandomSequence(10, CharsetAlphaLowerNumeric))
fmt.Println(generateRandomSequence(5, CharsetNumeric))
fmt.Println(generateRandomSequence(20, CharsetAlphaLowerNumeric))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment