I'm looking to pick a random number from 1-6 but if for example 1 is picked by the program I want to make sure it is not again used until 2-6 has been picked. I want to do this in order to have a chance to go through all options instead of having the same option 2 or maybe 3 times in a row since there are only 6 options. Any ideas please?
//choose random number for recipe
rand.Seed(time.Now().UTC().UnixNano())
myrand := random(1, 6)
fmt.Println(myrand)
...
function that processes it
//random number function
func random(min, max int) int {
return rand.Intn(max-min) + min
}
The part of my program that uses myrand from each run is used in a if statement and is tied to the recipe that will be picked for the day
//choose random number for recipe
rand.Seed(time.Now().UTC().UnixNano())
myrand := random(1, 6)
fmt.Println(myrand)
//test below of random replacement
list := rand.Perm(6)
for i, _ := range list {
fmt.Printf("%d
", list[i]+1)
}
//logic for recipe to choose
if myrand == 1 {
fmt.Println(1)
printRecipeOfTheDay(recipe1)
} else if myrand == 2 {
fmt.Println(2)
printRecipeOfTheDay(recipe2)
} else if myrand == 3 {
fmt.Println(3)
printRecipeOfTheDay(recipe3)
} else if myrand == 4 {
fmt.Println(4)
}
}
I'm wondering if I'm doing something incorrectly ? I'm not sure how I can use the list on every run to generate a new number (myrand) and the program will be able to remember what the last number (myrand) was when it ran the previous time?
You can use rand.Perm(6)
and then loop through the result.
For example, here is code to print the numbers 1-6 in a random order, with no repeats:
package main
import "fmt"
import "math/rand"
func main(){
list := rand.Perm(6);
for i, _ := range list {
fmt.Printf("%d
", list[i]+1);
}
}
Note that we've added 1 to everything, since Perm(6)
returns 0-5 and you want 1-6. After you've used all six, call rand.Perm(6)
again for six new numbers.