This question already has an answer here:
I would like to generate number for invitation code.
I get a number of digit for this and i need to generate a string number according to this digit.
Example : For 3 i need to generate a string number beetween 111 and 999 for 4 1111 to 9999 for 2 11 to 99 etc...
What is the best way to do that ?
I have some idea like making two empty string filling them with 1 for the first one according to x, with 9 for the second one according to X.
Then converting them to int and make a random between these two number, but i don't thik it's the optimal way to do it.
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
)
func randInt(min int, max int) int {
return min + rand.Intn(max-min)
}
func main() {
x := 3
first := ""
second := ""
i := 0
for i < x {
first = first + "1"
i = i + 1
}
i = 0
for i < x {
second = second + "9"
i = i + 1
}
rand.Seed(time.Now().UTC().UnixNano())
fmt.Println(first)
fmt.Println(second)
firstInt, _ := strconv.Atoi(first)
secondInt, _ := strconv.Atoi(second)
fmt.Println(randInt(firstInt, secondInt))
}
regards
</div>
You can do something like this:
package main
import (
"fmt"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var numbers = []rune("0123456789")
func GenerateNumberString(length int) string {
b := make([]rune, length)
for i := range b {
b[i] = numbers[rand.Intn(len(numbers))]
}
return string(b)
}
func main() {
fmt.Println(GenerateNumberString(2))
fmt.Println(GenerateNumberString(3))
fmt.Println(GenerateNumberString(4))
}
Try it here in the go playground.