Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Using Lists to make an Anagram Application

3.62/5 (5 votes)
10 Nov 2015CPOL3 min read 13K   37  
Basic C# App to make an Anagram using a StringBuilder and Lists

Introduction

The app is a pretty simple app that takes a string, and passes it through Char List and StringBuilder to remove spacing, shuffle the Characters, then reorder the spacing to where it originally was.

Background

This tip is the response to a question I asked and got an answer to this question.

I asked the question on how to reorder a List to add some spaces back at set intervals. I asked the question as my previous efforts where a little way off in my application of the StringBuilder. I built the App to make an anagram puzzle for an Office Quiz.

Using the Code

The Form consists of a TextBox, a Button and a Richtextbox. One types a title into the Textbox and then presses the button for the code produces an anagram of all the letters keeping the original spacing. As an example 'The Departed' could come back like 'rae epdhdtte'.

When administrating, this did become a bone of contention as I did not specify that the letters where jumbled around all the words, not in the words they were taken from, as the first three letters are 'rae' as opposed to a mix of 'the'.

After collecting the string component, the code creates an integer called 'spacecount'. This integer has two purposes; the first being a counter, and the other to mark the point at which the spaces are located in the original string.

The reason for this is that when the characters will be shuffled and we are to keep the order of what the spaces were at originally. To accomplish this, we use a List of Integers to store the points at which I will add the spacing back in. The list is made by looping through the initial string to find at what point the spaces are located.

There are more Lists to come in the program and Lists were chosen for this task as they have no set bounds on size like an Array and are a little easier to resize than Array; like an Array they also have an index to utilize.

C#
string film = textBox1.Text;
int spacecount = 0;

// make a list of Ints to make note of where 

List<int> spacepoint = new List<int>();

// loop out the spaces and fill the int list

foreach (char i in film)
      {  
         spacecount += 1;
                if (i == ' ')
                {
                    spacepoint.Add(spacecount);
                }
      }

Making the Char Array and Shuffling It

I create a Char Array from the string so I can place the text into a List of Chars. This List is then iterated through to make a new List with it contents distributed randomly into the new List.

To distribute the 'lettersold' List Randomly, we use the Random 'r', for the index of 'lettersold' List. The 'lettersold' list has its contents distributed randomly to the 'letters' List while at the same time removing that index of the 'letterold' List. This loop is controlled while it has constituents. As such, we now have the Char randomly distributed into the 'letters' List.

C#
//make a char array
char[] letter = film.ToCharArray();

//create random  for shuffle
Random r = new Random();

// make new list to incorporate shuffled letter
List<char> letters = new List<char>();

// Create list of letters to transform
List<char> lettersold = new List<char>(letter);

//loop list into the jumble
 while (lettersold.Count > 0)
     {      
      int index = r.Next(0, lettersold.Count);
      letters.Add(lettersold[index]);
      lettersold.RemoveAt(index);     
     }

Removing the Spaces

Again, I create another List of Chars 'letter2' to have the contents of the 'letters' List distributed into it without the spacing. This is done by checking for the Char value of ' ' and not adding it to the 'letters2' List.

C#
//
//  make a list without the spaces

List<char> letters2 = new List<char>();
for (int m = 0; m < letters.Count; m++)
            {
                if (letters[m] != ' ')
                {
                      letters2.Add(letters[m]);
                }
            }

Making the Respaced String

I then use a StringBuilder in a loop of the 'letters2' List to make one jumbled string with no spaces.

After the string is made, it is passed with the 'spacepoint' List into the Make Spaces Function.

In the function, I use a foreach loop to put the space into the stringbuilder using the StringBuilders Insert method. This method takes two parameters, one for the space at which to insert the string and the string itself. The StringBuilder .ToString() method is used to make a string which is then returned, as the jumbled word with the original spacing.

C#
//
// Any source code blocks look like this

int[] resizedspaced = spacepoint.ToArray();

StringBuilder sb = new StringBuilder();
string mcsc;
for (int zz = 0; zz < letters2.Count; zz++ )
{
         sb.Append(letters2[zz]);
}

mcsc = sb.ToString();
richTextBox1.AppendText(MakeSpaces(mcsc, List<int> spaces ));

public string MakeSpaces(string sourcestring, int[] spaces)
        {
            var sortedparams = spaces
            StringBuilder sb1 = new StringBuilder(sourcestring);
            foreach (var yy in sortedparams) sb1.Insert(yy - 1, ' ');
            return sb1.ToString();
        }

Points of Interest

The main point of this exercise was to demonstrate how flexible a structure the Lists are, and how easy it was to interchange an Array into a List or use the Contents of a list. Moreover, the same also applied to the StringBuilder class and its ease of use to create a string or add parts to the StringBuilder to formulate a String.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)