Haha, well, that problem likely will never disappear
I have been writing code for a few decades, and I still have that problem. My first attempt usually fails at some point where I hit an unexpected block, or at best "it works", but not as I want it. No problem I just write it again. The second time you have a much better idea where you want to end up due to new information you learned from the first time, and the result is therefore much better. It may sound like a lot of work, but the 2nd time is much quicker, as you don't need to do thinking for things that were right the first time.
Usually, the second time is sufficient for me. However, if I would rewrite it again, it still improves.
Don't be afraid to throw away code, or try it a second or third time. The real battle is in finding out how to solve the problem with a computer, rather than in writing the solution into code. The more you work with the problem, the better you understand how it behaves, and the better your solution becomes.