xsl-list
[Top] [All Lists]

[xsl] Show all permutations of N coins ... without using recursion?

2013-08-31 06:50:27
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>

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--


<Prev in Thread] Current Thread [Next in Thread>