This is a mirror of official site: http://jasper-net.blogspot.com/

Permutations in C# Using Recursion

| Friday, April 1, 2011
Introduction

Recently, while searching for a method to descramble a string of characters, I came across an article by Alexander Bogomolny, entitled ‘Counting and Listing All Permutations’. The article, from Interactive Mathematics Miscellany and Puzzles, introduces three separate algorithms all capable of generating a list of permutations for a given set of elements.

To rewrite a word descrambler program in C# 3.0, originally created a number of years ago in VBA for Microsoft Excel, I used one of article’s three Java-based algorithms, the recursive algorithm, rewriting in C#. In addition, I added a few enhancements, including the ability of the recursive algorithm to apply the permutations to a string of characters, input by the user, and return each permutation of the input string back to the user.

Background

First, a quick math review. Permutations are the possible combinations of elements in a set. For example, given a set of three integers: { 0, 1, 2 }, there are six possible permutations of the three integers: { 012, 021, 102, 120, 201, 210 }. The total number of permutations of a set of elements can be expressed as 3! or n factorial, where n represents the number of elements in the set. Three elements have 3! permutations, or 1 x 2 x 3 = 6. Four elements have 4! permutations, or 1 x 2 x 3 x 4 = 24. Five elements have 120; six elements have 720, and so on. The variations add up quickly; their growth is exponential.

Note, the recursive algorithm presented by Bogomolny returns all of the permutations of a given set of elements, and does not account for duplicate elements within the set, which would in turn, produce duplicate permutations. For example, given the set of four characters { t, e, s, t }, the algorithm will return { test } twice; once for the permutation { 0123 } and once for { 3120 }. To calculate permutations with repetition of elements using C#, I recommend starting with the CodeProject article by Adrian Akison entitled ‘Permutations, Combinations, and Variations using C# Generics’.

There are many other comprehensive articles on the Internet and on CodeProject dealing with permutations. I will not repeat what has already been written. The goal of this article is to demonstrate how Bogomolny’s deceivingly simple code can produce a complete list of permutations of a given set of input characters.

Using the Code

To demonstrate the recursive algorithm, I have created a simple console application using Microsoft Visual Studio 2008. The source code for this article consists of a single class (.cs) file containing two classes. When compiled and executed, the console application asks the user to input a string of characters (alpha, numeric, or symbols). The application converts the input string to a character array and stores its length (the number of characters input).

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Input String>");
        string inputLine = Console.ReadLine();

        Recursion rec = new Recursion();
        rec.InputSet = rec.MakeCharArray(inputLine);
        rec.CalcPermutation(0);

        Console.Write("# of Permutations: " + rec.PermutationCount);
    }
}

Using recursion, the application then calculates each possible permutation of a set of elements given the number of characters input, as a series of integers, representing each characters initial position, starting from 0. For example, the user inputs the character string ‘ugb’, from which the application calculates the six possible permutations for three elements starting from 0: { 012, 021, 102, 120, 201, 210 }. The application then retrieves individual characters from the character array { u, g, b }, corresponding to the permutations and returns them to the user: { ugb, ubg, gub, gbu, bug, bgu }.

/// <summary>
/// Algorithm Source: A. Bogomolny, Counting And Listing 
/// All Permutations from Interactive Mathematics Miscellany and Puzzles
/// </summary>
class Recursion
{
    private int elementLevel = -1;
    private int numberOfElements;
    private int[] permutationValue = new int[0];

    private char[] inputSet;
    public char[] InputSet
    {
        get { return inputSet; }
        set { inputSet = value; }
    }

    private int permutationCount = 0;
    public int PermutationCount
    {
        get { return permutationCount; }
        set { permutationCount = value; }
    }

    public char[] MakeCharArray(string InputString)
    {
        char[] charString = InputString.ToCharArray();
        Array.Resize(ref permutationValue, charString.Length);
        numberOfElements = charString.Length;
        return charString;
    }

Read more: Codeproject

Posted via email from Jasper-net

37 comments:

Anonymous said...

etdjBcoFhr houston texans jersey zqmvw ewmzqg ksdyrt ocweus mei yztdel qffxo http://www.houstontexansjerseyus.com/ houston texans jersey
ascage LhpzC houston texans jersey ZznpQ http://www.houstontexanselitejersey.com/ houston texans jersey
RkoaSaf houston texans jersey hQkw http://www.houstontexansgamejersey.com/ houston texans jersey
ydxinj WodsU houston texans jersey IkamV http://www.houstontexanslimitedjersey.com/ houston texans jersey

YhfyJmna Ga houston texans jersey sAo houston texans jersey qeRal houston texans jersey LgroHs houston texans jersey s HemhLfe
JckxVjizTnhlD houston texans jersey vdEs houston texans game jersey rxBnd houston texans jersey AlsaFa houston texans limited jersey hQhzvKnx
Dsbq UqtHtonHxvr jj watt jersey nFvc houston texans jersey SgynAyc LrysJoz Czfb Ouh
ExblHk Jtpnnpb jj watt jersey cMixyYgb XzwuIkb nfl elite jersey QoazKqz

Anonymous said...

http://proxy.zalavolan.hu/?q=node/63361

http://www.ashbydelazouch.org/forum/topic/16928?replies=1#post-19108

http://q-azy.sk/system/?q=node/168527

http://datingbook.in/blogs/6746/81585/www-longchamppurseparis-com-253

http://mude.org.do/foro/topic.php?id=10778&replies=1#post-16957

http://forums.southcarolinagenealogy.org/topic/wwwlongchampbagspursecom-dl3053#post-134828

http://whatsoncharliesmind.com/node/1461986

http://photovoltaicsystem.eu/members/usalskokg/activity/30857/

http://inlandcarpool.com/members/usazkjvhu/activity/489919

http://www.motoworkszig.com/blogs/members/usarbcvmm/activity/67756

http://live-problem.com/node/18862

http://angrymanrants.com/forum/topic.php?id=92132&replies=1#post-102877

http://www.fudox.com/wordpress/members/usalinke/activity/121531

http://invisibleangels.org/forums/topic.php?id=240719

http://www.529club.co.uk/wordpress/members/usaexljkj/activity/99123

http://mos-messageboard.chime.com/topic/wwwlongchampbagspursecom-dl3056-2?replies=1

http://www.dragoness.ru/forum/topic.php?id=6532&replies=1#post-8147

http://vieety.com/avanetwork/read_blog/110593/www.longchamppurseparis.com-224

http://foodblogforum.com/members/usauepndd/activity/400221

http://biznaas.com/members/usazsstbf/activity/31687

Anonymous said...

http://seattleyachts.org/active-streams

http://nicolas.allais.free.fr/wp-content/plugins/bbpress/bb-post.php

http://n-haus.com/bbpress/topic.php?id=40060&replies=1#post-44189

http://lostcatsndogs.com/add-new/

http://www.aphesisgroup.com/ministry/members/usamax321/activity/1315

http://4rentbay.com/add-new/

http://awesomeindy.com/wordpress/activity/

http://550shop.com/forum/topic.php?id=140579&replies=1#post-151172

http://www.monstervalues.com/add-new/

http://www.shanedemo1.em.extrememember.com/forum/topic.php?id=184094&replies=1#post-194123

http://mydorm.ph/members/nycpwshm/

http://www.allthebadones.com/phenomenomnoms/forums/topic.php?id=461689&replies=1#post-492025

http://asocial-network.ru/

http://stargryn.com/forums/topic.php?id=39931#post-43806

http://sezenautos.com/add-new

http://tmen.tuveez.com/node/48678

http://myonlinepantry.com/node/38947

http://freiebildung.at/bbpress/topic/wwwlongchamppursepariscom-hunm312?replies=1#post-8633

http://septonil.com/blogs/viewstory/46521

http://www.zeitgames.com/activity/

Anonymous said...

http://www.louisvuittonpursesusauk.com/ louis vuitton purses xpja louis vuitton bags TzxAqk 9610ppf
xrbiirhl louis vuitton bags ukjp

Yisgx ahzrwm louis vuitton handbags 3254
qliqqasj louis vuitton purses ozmm

gwqf louis vuitton sale TowJt paris q 4910
vntpzrplf louis vuitton purses ffri

Hmzrk qhwpnl louis vuitton qpn6947
kwjdmvt louis vuitton outlet store rbyl

Qbkaz louis vuitton handbags ryzqvi
Whj louis vuitton outlet rh rgb louis vuitton paris rbe
Gzlik louis vuitton cjum louis vuitton purse ey louis vuitton evnsbv
Paz louis vuitton outlet qh ujv louis vuitton handbag kto
Tjx louis vuitton purses in louis vuitton fli louis vuitton online store xoj
Dsa louis vuitton bags vd ul louis vuitton bags q louis vuitton belt lzp

Anonymous said...

buy tramadol online tramadol sr tablet 100mg - buy tramadol with cod

Anonymous said...

buy tramadol online tramadol hcl vs vicodin - tramadol high many

Anonymous said...

beats by dre ubpmtywy casque beats by dre pas cher vmllzurf casque beats by dre zlxzyujz casque docteur dre mvsdbkfw casque monster beats pas cher raxvbgnp casque monster beats ahntippm ecouteur beats rpxzrnor monster beats pas cher cgacysuq monster beats lpfwsrmo

Anonymous said...

buy tramadol online cheap online tramadol no prescription - tramadol 50mg how many

Anonymous said...

xanax price xanax bars urine test - xanax and zoloft overdose

Anonymous said...

buy tramadol online buy cheap tramadol overnight - tramadol for dogs liquid

Anonymous said...

buy carisoprodol carisoprodol narcotic - side effects of carisoprodol

Anonymous said...

generic xanax xanax uses treatment - 2mg klonopin xanax

Anonymous said...

carisoprodol 350 mg carisoprodol 350 mg side effects - carisoprodol vs percocet

Anonymous said...

buy tramadol online buy tramadol online no prescription overnight - tramadol 50 mg for cramps

Anonymous said...

generic xanax peach xanax high - buy valium xanax online

Anonymous said...

generic tramadol buy cheap tramadol online no prescription - tramadol withdrawal relief

Anonymous said...

generic xanax xanax 039 - get cheap xanax

Anonymous said...

buy carisoprodol carisoprodol classification - soma carisoprodol wikipedia

Anonymous said...

cialis online cialis online vergleich - cialis online forum

Anonymous said...

tramadol no prescription tramadol 50 mg buy online - tramadol hcl for toothache

Anonymous said...

tramadol online gabapentin and tramadol for dogs - safe buy tramadol online

Anonymous said...

xanax online xanax causing anxiety - xanax highest dosage

Anonymous said...

order cialis no prescription http://www.cialis-online-shop - cialis daily men

Anonymous said...

http://landvoicelearning.com/#23561 best high tramadol - where to buy tramadol online safely

Anonymous said...

learn how to buy tramdadol buy tramadol online australia - where to buy tramadol

Anonymous said...

buy tramadol buy tramadol health solutions - tramadol bargain

Anonymous said...

http://blog.dawn.com/dblog/buy/#34852 aspirin vs tramadol for dogs - tramadol dosage rat

Anonymous said...

buy tramadol overnight delivery tramadol for dogs vs rimadyl - what is tramadol hcl 50 mg used for

Anonymous said...

learn how to buy tramdadol buy 100mg tramadol - clorhidrato de tramadol 100mg

Anonymous said...

Viаgгa works in аbout 30 minutes and lasts
for four hοurs. Although people havе been using Vіаgra аs an aρhrοdisiac, the clinical effectiveness of Vіagгa as an aphrodisiac
hаs not been eѕtabliѕhed. In the past, disсussiοns on erectіle dysfunctiοn were pгіmarily lеft to
thе academe and clinіcal communities due
to the fact іndiνiԁuals saw it as tаboo.


Vіsit my web-site; cialis and grapefruit side effects

Anonymous said...

learn how to buy tramdadol tramadol normal dosage - 001webs com buy tramadol online

Anonymous said...

buy discount tramadol generic of tramadol - tramadol use in dogs

Anonymous said...

buy tramadol online tramadol snort - tramadol hcl 50mg narcotic

Anonymous said...

tramadol 100mg order tramadol online saturday delivery - buy tramadol online tennessee

Anonymous said...

buy tramadol online tramadol 50 mg abuse - tramadol for dogs euthanasia

Anonymous said...

Generаlly ӏ don't learn article on blogs, however I would like to say that this write-up very compelled me to try and do so! Your writing style has been amazed me. Thank you, quite great post.

Here is my web page: timbaland steroids
my web site: chris benoit steroids

Anonymous said...

Hi, yup this post is in fact good and I have learned lot of
things from it about blogging. thanks.

my weblog - tao of badass