Created
June 12, 2023 22:10
-
-
Save thrawn01/1c3c9047ad72811456b6c401cebf8224 to your computer and use it in GitHub Desktop.
Distribution plot of rand.Shuffle() on a 3 item array 1000 times
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 ( | |
"image/color" | |
"log" | |
"math/rand" | |
"gonum.org/v1/plot" | |
"gonum.org/v1/plot/plotter" | |
) | |
func main() { | |
var array []int | |
for i := 0; i < 3; i++ { | |
array = append(array, rand.Int()) | |
} | |
var dist []int | |
for i := 0; i < 1000; i++ { | |
rand.Shuffle(len(array), func(i, j int) { | |
array[i], array[j] = array[j], array[i] | |
}) | |
dist = append(dist, array[0]) | |
} | |
hist(dist, "uniform", "Distribution") | |
} | |
func hist(dist []int, name, title string) { | |
n := len(dist) | |
vals := make(plotter.Values, n) | |
for i := 0; i < n; i++ { | |
vals[i] = float64(dist[i]) | |
} | |
plt := plot.New() | |
plt.Title.Text = title | |
hist, err := plotter.NewHist(vals, 25) // 25 bins | |
if err != nil { | |
log.Println("Cannot plot:", err) | |
} | |
hist.FillColor = color.RGBA{R: 255, G: 127, B: 80, A: 255} // coral color | |
plt.Add(hist) | |
err = plt.Save(400, 200, name+".png") | |
if err != nil { | |
log.Panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment