Hello. Suppose there is a folder 1 in it is always a different number of images in the format * .jpg. How to make a random file selection.
- oneFile list + random number representing the index. - user227465
- Can the code be approximate? - user236201
- 2No, nobody will do everything for you. If you have a specific question - ask. List of entities in the directory - golang.org/pkg/io/ioutil/#ReadDir , a random number - golang.org/pkg/math/rand/#Intn - user227465
- I understand the logic of how to do this. we have a random number, there is a list of files. So, what is next? - user236201
- Next, select the file from the list with the index corresponding to the number. - user227465 February
|
1 answer
Sample code that displays the name of a random file.
package main import ( "fmt" "math/rand" "time" "io/ioutil" ) func main() { // Получаем список файлов (структура элемента https://golang.org/pkg/os/#FileInfo) files, _ := ioutil.ReadDir(".") // Инициализируем генератор случайных чисел номером текущей наносекунды rand.Seed(time.Now().UTC().UnixNano()) // Выводим имя файла, выбранного случайно от нуля до количества файлов в списке fmt.Println(files[rand.Intn(len(files))].Name()) } https://play.golang.org/p/PWzYGpYv0m
PS: In play.golang.org, the random number generator is always initialized with the same number, so it will generate the same number.
|