-2

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

Bussiere
  • 500
  • 13
  • 60
  • 119
  • It's a random number with constraints ... like the number of digit ... Not a random string in an array ... Ant no zero in the first post. – Bussiere Dec 03 '18 at 12:26

1 Answers1

1

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.

Ullaakut
  • 3,554
  • 2
  • 19
  • 34