Home > Mobile >  Go Function that returns a random int in a range, excluding numbers in a slice
Go Function that returns a random int in a range, excluding numbers in a slice

Time:03-17

I am trying to make a function that takes 3 arguments. A minimum number, a maximum number and a slice of blacklisted numbers in between that range,I've been able to "bruteforce" it by generating a new number and comparing it to the slice again if the generated number matches an entry, but this is obviously a very inefficient way to do it.It gets very slow once the list grows large as it keeps generating blacklisted numbers. Does anyone have any idea how I could do it?

CodePudding user response:

Something like this ought to do you:

import "math/rand"

func getRandomIntWithBlacklist(min int, max int, blacklisted []int) int {
  
  // if blacklisted is/can be large, you might want to think about caching it
  excluded :=  map[int]bool{};
  for _,x := range blacklisted {
    excluded[x] = true
  }
  
  // loop until an n is generated that is not in the blacklist
  for {
    n := min   rand.Intn(max 1) // yields n such that min <= n <= max
    if !excluded[n] {
      return n
    }
  } 
  
}

But don't forget to see rand with some entropy (unless you want eminently repeatable random sequences.

CodePudding user response:

In response to your inquiry, I built a function using the min, max, and blacklisted arguments. As a result, the code creates a function with those parameters and returns an array of ints. The ints include the numbers that are not banned, presuming that is what you need. I also wrote an includes function that returns a bool value and takes two inputs, an int slice and an integer value, because this code utilizes integers. The exclude function cycles from min to max and calls the contains function; if it is not true, it adds it to the list; if it is true, it displays "Number is blacklisted, skipping" to the command line. The slices of integers are then returned.

func Exclude(min, max int, blacklisted []int) []int {
    var listOfNums []int
    log.Printf("min: %v, max: %v, blacklisted: %v\n", min, max, blacklisted)
    for i := min; i <= max; i   {
        if !contains(blacklisted, i) {
            listOfNums = append(listOfNums, i)
        }else{
            log.Println("Number is blacklisted, skipping", i)
        }
    }
    return listOfNums
}
func contains(list []int, item int) bool {
    for _,v := range list {
        if v == item {
            return true
        }
    }
    return false
}
  • Related