[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

```Imagine instead of coins, you have a dice with 10 sides with numbers from
0..9. Than, to generate all you permutations is just printing all the
numbers from 000 to 999 in decimal system. What you have is a binary system.

-----Original Message-----
From: Costello, Roger L. [mailto:costello@xxxxxxxxx]
Sent: Saturday, August 31, 2013 1:50 PM
To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
Subject: [xsl] Show all permutations of N coins ... without using recursion?

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>

```