Maybe you should take such an algorithm from a programming language you know very well and try then to translate it step-by-step to xslt.
if = xsl:if
if-then-else = xsl:choose/when/otherwise
....and so on, most of the time you will have to make workarounds and this is going to be a damn big xslt-stylesheet.
Or you look for an Java-function on the net wich does that and take that to build an extended:xslt-function, but i dont know much about that.
Best thing is probably to do that in another prg.language. xslt just isn't build for something like that.