Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to generate N random integers, each with distinct digits and exact length L in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

// hasDistinctDigits checks whether all digits in the number are unique.
func hasDistinctDigits(num int, length int) bool {
    seen := make(map[rune]bool)
    s := fmt.Sprintf("%0*d", length, num) // pad with leading zeros if needed

    for _, ch := range s {
        if seen[ch] {
            return false
        }
        seen[ch] = true
    }
    return true
}

// generateDistinctDigitNumbers generates N integers of exact length L,
// each containing only distinct digits.
func generateDistinctDigitNumbers(N int, L int) []int {
    rand.Seed(time.Now().UnixNano())

    results := make([]int, 0, N)
    min := intPow(10, L-1)
    max := intPow(10, L) - 1

    for len(results) < N {
        candidate := rand.Intn(max-min+1) + min

        if hasDistinctDigits(candidate, L) {
            results = append(results, candidate)
        }
    }

    return results
}

// intPow computes integer powers.
func intPow(base, exp int) int {
    result := 1
    for i := 0; i < exp; i++ {
        result *= base
    }
    return result
}

func main() {
    N := 10
    L := 6

    numbers := generateDistinctDigitNumbers(N, L)
    fmt.Println("Generated numbers:", numbers)
}



/*
run:

Generated numbers: [308726 243708 742391 293470 183904 230415 983705 947352 421650 906748]

*/

 



answered Jul 16 by avibootz

Related questions

...