Thinking outside the box

Patron Saint of Lost Yaks
posts - 199, comments - 687, trackbacks - 4

My Links

Advertisement

News

Archives

Post Categories

Saturday, January 02, 2010

Create permutations, a simple way

This is one way to create permutations of a word. It is certainly not the fastest way (there are hardwired and specialized approaches, and there are other algorithms such as Fike) but this is very simple.


DECLARE @Word VARCHAR(10) = 'Peter'

;WITH cteYak(Word, Letters)
AS (
    SELECT  CAST(SUBSTRING(@Word, Number, 1) AS VARCHAR(10)) AS Word,
            STUFF(@Word, Number, 1, '') AS Letters
    FROM    dbo.TallyNumbers
    WHERE   Number BETWEEN 1 AND LEN(@Word)

    UNION ALL

    SELECT      CAST(Word + SUBSTRING(y.Letters, n.Number, 1) AS VARCHAR(10)) AS Word,
                STUFF(y.Letters, n.Number, 1, '') AS Letters
    FROM        cteYak AS y
    INNER JOIN  dbo.TallyNumbers AS n ON n.Number BETWEEN 1 AND LEN(y.Letters)
)
SELECT  DISTINCT
        Word
FROM    cteYak
WHERE   LEN(Word) = LEN(@Word)
 

posted @ Saturday, January 02, 2010 8:15 AM | Feedback (11) | Filed Under [ SQL Server 2008 Algorithms SQL Server 2005 ]

Powered by:
Powered By Subtext Powered By ASP.NET