@Alan MC,
"...how did whatever causing evolution know that..."
This is an error that comes from perspective of the observer.
During the industrial revolution soot from smoke stacks became a common occurrence, and covered the local trees. That was a change in the environment; the soot-covered trees that used to be brown had become black.
And there were moths that lived on those trees. They were brown, and had bark-patterned wings to hide from the birds that ate them. But now that the trees were black instead of brown, those brown moths stood out against the background and the birds ate most of the brown moths.
Evolution doesn't propose a solution for the brown moths. What it does do (and had always done) is produce a sleight variety in brown moths. There were lighter brown moths and darker brown moths. The lightest stood out the most and so were eaten. They often didn't survive long enough to have baby light brown moths.
The darkest brown moths were hardest to spot and so more of those survived, and had baby dark brown moths. And there was also slight variety in the baby dark brown moths, so that some of them were just a little dark brown and some were very dark brown.
That process culled out the least fit to the environment so that the new normal for the moths became the color of soot-covered trees. The soot-colored moths continue to produce a small spread of color variance, and the most fit to the current environment will be the ones that have babies.