Monday, July 23, 2007

All Permutations For A String

Suppose you have a auxiliary Numbers table with integer numbers.

DECLARE @s VARCHAR(5);
SET @s = 'ABCDE';

WITH Subsets AS (
SELECT CAST(SUBSTRING(@s, Number, 1) AS VARCHAR(5)) AS Token,
CAST('.'+CAST(Number AS CHAR(1))+'.' AS VARCHAR(11)) AS Permutation,
CAST(1 AS INT) AS Iteration
FROM dbo.Numbers WHERE Number BETWEEN 1 AND 5
UNION ALL
SELECT CAST(Token+SUBSTRING(@s, Number, 1) AS VARCHAR(5)) AS Token,
CAST(Permutation+CAST(Number AS CHAR(1))+'.' AS VARCHAR(11)) AS
Permutation,
s.Iteration + 1 AS Iteration
FROM Subsets s JOIN dbo.Numbers n ON s.Permutation NOT LIKE
'%.'+CAST(Number AS CHAR(1))+'.%' AND s.Iteration < 5 AND Number
BETWEEN 1 AND 5
--AND s.Iteration = (SELECT MAX(Iteration) FROM Subsets)
)
SELECT * FROM Subsets
WHERE Iteration = 5
ORDER BY Permutation

Token Permutation Iteration
----- ----------- -----------
ABCDE .1.2.3.4.5. 5
ABCED .1.2.3.5.4. 5
ABDCE .1.2.4.3.5. 5
(snip)
EDBCA .5.4.2.3.1. 5
EDCAB .5.4.3.1.2. 5
EDCBA .5.4.3.2.1. 5

(120 row(s) affected)

4 Comments:

At 10:28 PM, Anonymous Anonymous said...

Alex privet, pochemy ne zahoidish na
microsoft.private.mvp.sqlserver
to say Hello. Zdem tebya

Uri Dimant

 
At 10:30 PM, Anonymous Anonymous said...

Alex privet .Pochemy ne zahodish na
microsoft.private.mvp.sqlserver
to say Hello
Zdem tebya
Uri Dimant

 
At 10:37 PM, Blogger Uri Dimant said...

Alex privet
Pochemy ne zahoduish
na microsoft.private.mvp.sqlserver

to say hello
Zdem tebya
Uri Dimant

 
At 10:10 AM, Anonymous Anonymous said...

This is a Combination and NOT a Permutation. Order matters on a Permutation where the Letters "ABC" is the same as "BCA". 10 things taken 4 at a time is less in Permutations then in Combinations.

 

Post a Comment

<< Home