a basic solution is as follows,

this in not optimised, ie very inefficient, can be improved considerably
an lends itself to a recursive solution.

Code removed per posting guidelines