Subject: [xsl] Show all permutations of N coins ... without using recursion? From: "Costello, Roger L." <costello@xxxxxxxxx> Date: Sat, 31 Aug 2013 11:50:12 +0000 |
Hi Folks, I want to print out all permutations of N coins. If N = 3 then I can find all permutations using a triply nested loop: <xsl:for-each select="('H','T')"> <xsl:variable name="coin1" select="." /> <xsl:for-each select="('H','T')"> <xsl:variable name="coin2" select="." /> <xsl:for-each select="('H','T')"> <xsl:variable name="coin3" select="." /> <xsl:value-of select="concat($coin1, $coin2, $coin3, ' ')"/> </xsl:for-each> </xsl:for-each> </xsl:for-each> Output: HHH HHT HTH HTT THH THT TTH TTT If N is arbitrary, then that approach won't work. So I created a recursive function that does the job, which I show below. Now I want to eliminate the recursion and use loops instead. How do I do that? Would you please show me how to output all permutations of N coins, without using recursion? /Roger ----------------------------------------------------------------------- Show all permutations of N coins ----------------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:map="http://www.w3.org/2005/xpath-functions/map" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:f="function" version="3.0"> <xsl:template match="/"> <xsl:value-of select="f:show-coins(4, '')" /> </xsl:template> <xsl:function name="f:show-coins"> <xsl:param name="N" as="xs:integer" /> <xsl:param name="coins" as="xs:string*" /> <xsl:choose> <xsl:when test="$N eq 0"> <xsl:value-of select="concat($coins, ' ')" /> </xsl:when> <xsl:otherwise> <xsl:for-each select="('H','T')"> <xsl:value-of select="f:show-coins($N - 1, concat($coins, .))" /> </xsl:for-each> </xsl:otherwise> </xsl:choose> </xsl:function> </xsl:stylesheet>
Current Thread |
---|
|
<- Previous | Index | Next -> |
---|---|---|
Re: [xsl] square root function in X, Dimitre Novatchev | Thread | RE: [xsl] Show all permutations of , Jakub Malý |
Re: [xsl] Arabic alphabetical lists, Patricia Piolon | Date | RE: [xsl] Show all permutations of , Jakub Malý |
Month |