Let $X$ be a six sided die and $B$ is a Bernoulli random variable with mean $p$. If $B=0$, then $Y=X-1$. If $B=1$, then $Y=X+1$. What is the covariance of $X$ and $Y$?
I know $cov(X,Y) = E[XY] - E[X]E[Y]$ but I don't understand how to compute $E[XY]$ in this case. I tried to use iterated expectations $E[XY] = E[Y E[X \mid Y] ]$ but I can't see where that is going.
I can find the mean, variance of $X$ and $Y$. Any help will be much appreciated.
$$E[XY] = E[E[XY \mid B]] = p E[XY \mid B=1] + (1-p) E[XY \mid B=0]$$
When $B=1$, you know $Y=X-1$, so $E[XY \mid B=1] = E[X(X-1) \mid B=1]$. If $X$ and $B$ are independent (I guess this needs to be assumed), then this equals $E[X(X-1)]$. The other term $E[XY \mid B=0]$ can be handled similarly.
In the end, we'd have $$E[XY]=pE[X(X+1)] + (1-p)E[X(X-1)] = E[X^2] - (1-2p) E[X]$$ and $E[Y] = E[E[Y \mid B]] = pE[X+1] + (1-p)E[X-1] = E[X] - (1-2p)$ and thus $$\text{Cov}(X,Y) = E[X^2] - (1-2p)E[X] - E[X](E[X] -( 1-2p)) = \text{Var}(X)$$ as Matthew Pilling obtained with his much slicker approach.