let pick = sample(images) doAssert pick in images resp "<img src='" & pick & "'/>"
I'm using the random library to do a function that returns a random image but when I use randomize() and initRand(), it doesn't return a random result, it just returns a fixed result Is this a problem with my code?
How do I use initRand() and randomize() correctly in this code?
I guess you missed to call randomize
#from https://nim-lang.org/docs/random.html
import std/random
# Call randomize() once to initialize the default random number generator.
# If this is not called, the same results will occur every time these
# examples are run.
randomize()
Not sure what you are using but here is an example using starlight
import random
import starlight
randomize()
var app = newApp(newSettings())
proc hello(ctx: Context) {.async, get(app, "/hello").} =
resp "Hello world!"
proc randImg(ctx: Context) {.async, get(app, "randimg").} =
let images = ["1.jpeg", "2.jpeg", "3.jpeg", "4.jpeg", "5.jpeg", "6.jpeg"]
let pick = sample(images)
echo pick
resp "<img src='" & pick & "'/>"
app.run()
When opening http://127.0.0.1:8080/randimg
it gives different result on every refresh with obvious repeating item :)
DEBUG GET /randimg
DEBUG 200 OK {"content-type": @["text/html; charset=UTF-8"]}
DEBUG GET /2.jpeg
DEBUG GET /randimg
DEBUG 200 OK {"content-type": @["text/html; charset=UTF-8"]}
DEBUG GET /3.jpeg
DEBUG GET /randimg
DEBUG 200 OK {"content-type": @["text/html; charset=UTF-8"]}
DEBUG GET /3.jpeg
DEBUG GET /randimg
DEBUG 200 OK {"content-type": @["text/html; charset=UTF-8"]}
DEBUG GET /5.jpeg
DEBUG GET /randimg
DEBUG 200 OK {"content-type": @["text/html; charset=UTF-8"]}
DEBUG GET /3.jpeg
DEBUG GET /randimg
DEBUG 200 OK {"content-type": @["text/html; charset=UTF-8"]}
DEBUG GET /3.jpeg