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?
Go Function that returns a random int in a range, excluding numbers in a slice
1.6k Views Asked by Vincent Adams At
2
There are 2 best solutions below
0
On
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
}
Something like this ought to do you:
But don't forget to see
randwith some entropy (unless you want eminently repeatable random sequences.