Originally there was a huge cloud of dust and gas that gravity was causing to spin around its center, where a giant lump was being formed. That lump grew massive enough for its own crushing weight to cause it to burst into nuclear fire. That's the sun. Gravity then caused the remaining dust cloud spinning around the sun to fall into lumps as well. Those became the planets.
Dust Cloud To Planet
Why are the planets where they are instead of somewhere else? Could, I don't know, Jupiter just as easily have been right next to the earth?
Well, no, because its strong gravity would have caused the earth to be drawn into collision with it. What we call the earth would've just become part of Jupiter.
Planets can't be in just any orbit, they have to be far enough apart so that they don't hit each other, and aren't drawn into collision by gravity.
How Could Planets Figure That Out?
They didn't figure anything out. It's just a matter of which orbits will cause the forming planets to hit each other at some point, and which ones won't. Big lumps of matter in orbits that would cause them to collide with other lumps did, in fact, collide, thus forming bigger lumps. That's partly how the planets grew so large.