As stated above, both the code in post #2 and that in post #7 appear to give correct results in my tests
However, here is the CoPilot critique of Philipp's simple function from post #7
EDIT: There are a lot of incorrect statements in the CoPilot summary above - See @posts #11 & #13 for details...