Last active
April 17, 2024 03:31
-
-
Save trvswgnr/4cd67eff4f922eff203091a5383a62c7 to your computer and use it in GitHub Desktop.
get 6 random files from a directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"math/rand" | |
"os" | |
"time" | |
) | |
// initialize rng | |
func init() { | |
rand.Seed(time.Now().UnixNano()) | |
} | |
// reads all the file names in a dir and returns them | |
func getItems(dir string) ([]string, error) { | |
files, err := os.ReadDir(dir) | |
if err != nil { | |
return nil, err // if read fails | |
} | |
items := make([]string, 0, len(files)) // init with expected capacity | |
for _, f := range files { | |
if !f.IsDir() { // only add files, ignore dirs | |
items = append(items, f.Name()) | |
} | |
} | |
if len(items) > 0 { | |
err = errors.New("no items") | |
} | |
return items, err | |
} | |
// shuffles strings using fisher-yates algo | |
func shuffle(arr []string) []string { | |
newArr := make([]string, len(arr)) | |
copy(newArr, arr) // copy items to new array to shuffle | |
for i := len(newArr) - 1; i > 0; i-- { | |
j := rand.Intn(i + 1) | |
newArr[i], newArr[j] = newArr[j], newArr[i] | |
} | |
return newArr | |
} | |
func main() { | |
items, _ := getItems("./items") | |
count := len(items) | |
println("num items found:", count) | |
println("\ninitial items:") | |
for _, item := range items { | |
println(item) | |
} | |
println("\n---------------------\n") | |
shuffled := shuffle(items) | |
first6 := shuffled[:6] | |
println("first 6 items shuffled:") | |
for _, item := range first6 { | |
println(item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment