How to generate a random vector, guaranteed to be within the hemisphere with respect to another vector? Given a normalized vector N, how can one generate a random direction vector that is guaranteed to be in the hemisphere with respect to N (i.e. the hemisphere where N is exactly in the middle)? The way I am currently doing this is to sample a random direction vector d and dot it with N and keep that vector if the dot product is greater than 0. This method is not guaranteed to generate a vector in the hemisphere that I am interested in as ~50% of the random vectors would have a 0 or negative dot product result.
I saw somewhere that there is a way to transform the randomly generated vector d to place it in the right hemisphere using a transformation matrix but I don't know how to do it. Can someone write a [pseudo]code for how one generate a direction vector using the transformation method?

To answer your followup question from the comments: If you're in 3D, we have the convenient fact that the $z$ coordinate of a random point on the unit sphere is uniformly distributed. So if you take $z\sim U(\cos\theta,1)$, $\phi\sim U(0,2\pi)$, $r=\sqrt{1-z^2}$, then $\left(r\cos\phi,r\sin\phi, z\right)$ is a random point on the sphere within $\theta$ radians of the positive $z$-axis.
To transform this to be within $\theta$ radians of $N$, multiply it by an orthonormal matrix whose last column is $N$. (In other words, apply the transformation $(x,y,z)\mapsto(xV,yW,zN)$ where $V$ and $W$ are unit vectors that are orthogonal to $N$ and to each other.)
