Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!


1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


stitchs

Member Since 22 Feb 2011
Offline Last Active Mar 22 2015 04:04 PM

Topics I've Started

String: How to find the most common character occurrence.

13 March 2015 - 11:04 AM

Hi all,

 

I've been presented with a small challenge:

 

1) Make a function that counts the number of each individual character in a string. Report back to the user in the form <character, number of occurrences> the character that appears the most.

 

So the function would take a string input; i.e. "rabbit" and output the character that occurs the most in said string; i.e. <'b', 2>.

 

I have coded up a function (to my understanding of Big O notation is that it is Linear O(N)).

public static string GetMostFrequentCharacter(string input)
        {
            string result = "The String is empty.";

            if (IsStringValid(input))
            {
                int INDEX_CONVERTER = 32;

                int[] characterCounts = new int[127 - INDEX_CONVERTER];

                char characterToConvert;

                // first loop counts the occurrence of each character in the string
                for (int i = 0; i < input.Length; i++)
                {
                    characterToConvert = input[i];

                    characterCounts[(int)characterToConvert - INDEX_CONVERTER]++;
                }

                int highestCount = 0, arrayPosition = -1;

                // second loop finds which character appeared the most, only the last
                // highest count to appear in the list will count.
                for (int i = 0; i < characterCounts.Length; i++)
                {
                    // check to see if the current index value is higher
                    // than the previous higher count
                    if (characterCounts[i] >= highestCount)
                    {
                        // get the value at the current index
                        highestCount = characterCounts[i];
                        arrayPosition = i;
                    }
                }

                if (arrayPosition < 0)
                {
                    result = "There was an error in processing the string.";
                }
                else
                {
                    // finally, convert the arrayPosition into a suitable char representation
                    char characterToOutput = (char)(arrayPosition + INDEX_CONVERTER);
                    // format the output string
                    result = string.Format("<'{0}', {1}>", characterToOutput, highestCount);
                }
            }

            return result;
        }

I'm happy with the way most of it works. My only problem is that, say I have 2 characters that appear an equal number of times. My current method only takes the last highest value, in order of UNICODE value. Say we have the string "foof". The output for said function would be <'o', 2>, it does not present the last letter to appear, only the last in order of UNICODE.

 

I don't want to create another storage for characters that appear equal number of times (I already have 2 arrays). I have looked on the internet, but the only responses I am finding is if someone knows the character they are looking for, before they use the function; they ask "How many times does 'a' appear?"

 

Any help or feedback would be greatly appreciated.

 

Stitchs.


C# Linked List implementation review

07 March 2015 - 09:02 AM

Hi all,

 

I am part way through implementing my own Linked List class (only stores Strings for now) to better understand how they work. I have completed the major portions of it; Add, Delete, Insert etc. and was just wondering if I could get some feedback on the code thus far.

private StringNode list;

public MyStringList()
{
     list = null;    // empty by default;
}
public void InsertNode(string stringIn, uint index)
        {
            // Check that user is not trying to insert outside the valid
            // range of nodes.
            if (IndexOutOfUpperBounds(index))
            {
                return;
            }

            // create a string node to insert into the list
            StringNode newNode = new StringNode(stringIn);
            StringNode current;
            StringNode temp;

            if (index == 0)
            {
                // store the list head.
                temp = list;
                // set the new node as the new list head
                list = newNode;
                // reconnect the old list head to the new list head.
                list.next = temp;

                return;
            }

            // temp node that is a reference to the beginning node
            current = list;

            // loop to the position of the node at index
            // because of the way that current is initialized, we can
            // skip index zero.
            for (int i = 1; i < index; i++)
            {
                // check that there is another node to process.
                if (current.next != null)
                {
                    current = current.next;
                }
            }

            // store a reference to the next node (the one at the index we desire) so as to preserve it
            temp = current.next;

            // set the current.next to point to the location of the new node
            // and set the new nodes next to point to that of the old
            current.next = newNode;
            newNode.next = temp;
        }

        public bool DeleteNode(uint index)
        {
            if (IndexOutOfUpperBounds(index))
            {
                return false;
            }

            // temp node representing the current node in the list.
            StringNode current = list;
            // temp node representing the previous node in the list.
            StringNode previous = null;

            // if the user has searched for a node that is not the first in the list

            if (index > 0)
            {
                // loop from 0 to the index position.
                for (int i = 0; i < index; i++)
                {
                    if (current != null)
                    {
                        previous = current;
                        current = current.next;
                    }
                }
            }

            // need conditions to assure that the predecessor of a node,
            // removed from the end will point to null

            // a check to see if we are at the end of the list.
            if ((current.next == null) && (current != list))
            {
                // make the very last node null, so it will be removed by
                // garbage collection
                previous.next = null;
                current = null;
            }

            // condition that a node removed from the middle will link the two
            // nodes that surround it, properly
            else if ((current.next != null) && (current != list))
            {
                // change the previous node to link to the node up ahead.
                previous.next = current.next;
                current = null;
            }

            // condition that the successor of a node removed from the front
            // will properly set the new list head.
            else
            {
                // check that the list head is not the only node
                if (current.next != null)
                {
                    list = current.next;
                }
                else
                {
                    list = null;
                }
            }

            // reduce number of nodes by 1, if we have got to this point,
            // there is no need to check if we are allowed to decrement.
            this.Count--;

            return true;
        }

I have not included the entire implementation, for simplicity's sake. I would like to draw your attention to the Insert and Delete methods. They work in all the tests I have performed. I feel like they could be streamlined more. If you need anymore information, feel free to ask and I shall do my best to explain.

 

Many thanks,

 

Stitchs.


C# Code Snippet Review

12 January 2015 - 11:50 AM

Hi community,

 

Working my way through a book, I've come to that classic "Create a deck of cards and Shuffle method" question.

 

I research shuffling techniques online as I wanted to implement this on my own. I decided to use the 'Overhand Shuffle' technique (details found: http://en.wikipedia.org/wiki/Shuffling#Overhand_shuffle). The basic premise is that you cut the deck and at 2 points and move this middle section to the top, or bottom, of said deck, repeating until sufficiently shuffled.

 

I have created a method that implements the same behavior:

public void ShuffleDeck(Random pRng)
        {
            int deckCutPoint = 0;
            List<Card> firstCutDeck = new List<Card>();
            List<Card> secondCutDeck = new List<Card>();

            for (int i = 0; i < MAX_SHUFFLE; i++)
            {
                // RNG a point at which to cut the deck.
                deckCutPoint = pRng.Next(DECK_LIMIT);

                for (int j = 0; j <= deckCutPoint; j++)
                {
                    firstCutDeck.Add(DrawCard());
                }

                // RNG a point at which to cut the deck, based on the new deck count.
                deckCutPoint = pRng.Next(lDeck.Count);

                for (int k = 0; k < deckCutPoint; k++)
                {
                    secondCutDeck.Add(DrawCard());
                }

                lDeck = lDeck.Concat(secondCutDeck).Concat(firstCutDeck).ToList();
                // Clear the cut decks so that they can be reloaded on the next shuffle.
                firstCutDeck.Clear();
                secondCutDeck.Clear();
            }
        }

I have a list of Cards in my DeckOfCards class. This is the main deck. I create 2 more decks in my method, that I use to draw cards out of the deck, adding each card to the back of the list. I randomly cut into my deck the first time by using its size to generate the index position. I do the same for the second cut, using the updated size.

 

To achieve the actual shuffle, I Concat the secondCut to the original deck, and then Concat the first cut to the back of the now modified main Deck.

 

My question/desire for feedback is how efficient is this? I understand that each time I draw my original list is getting smaller, and new memory has to be allocated for the new temporary lists. FYI; MAX_SHUFFLE is set to 25, meaning it repeats this process 25 times.

 

My thanks in advance,

 

Stitchs.


Reading Integers from a Text File

22 November 2014 - 11:03 AM

Hello,

 

I am working on an exercise for C# that involves reading from a Text file, extracting any Integer values (+ or -) and displaying them in the console window, in a tabular format.

 

On a 'one value per line' basis, I have managed to accomplish this. My code runs through the text file, ignores any decimals or non-numeric characters (NNC), and outputs Integers into a table.

 

I want to make this a bit more robust, the exercise never specifies how text in the file should be laid out, so I want to assume that having multiple Integers, Decimals/NNC on the same line can be accounted for. These would be separated by Whitespace.

 

My pseudo-code would be as follows:

 

  1. while Not at the end of the Stream
  2. create a StringBuilder
  3. while StreamReader.Peek is not a whitespace or null (should break on detecting whitespace)
  4. append the value at StreamReader.Read() to the string builder
  5. Try to parse this new string to an integer data type for output later.
  6. Repeat

My issue stems from points 3 and 4, the inner loop. Peek doesn't seem to recognise a whitespace value and the loop won't break.

 

while (!String.IsNullOrWhiteSpace(sr.Peek().ToString()))
{
       sb.Append((char)sr.Read());
}

sr is the StreamReader object. Is there something I'm missing here, or am I making it too hard on myself?

 

Please ask if you need any more information.

 

Many thanks,

 

Stitchs.

 

Update: I have stepped through the StringBuilder every time it is appended too, and have also found out that Read is also taking the \n and \r escape sequences into account. How would I account for these?


Problem with Programming Exercise; Loops within Loops

15 November 2014 - 02:25 PM

Hello,

 

I am working through a programming books exercises. I am on a chapter dealing with loops, and an exercise that makes use of inner loops. The aim of the exercise is to print a limited number of rows, each one printing a certain amount of spaces and stars:

 

-----*

----***

---*****

--*******

-*********

-*********

--*******

---*****

----***

-----*

 

I have come up with a solution, but it seems a bit messy to me and I cannot figure out how to clean it up.

int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS / 2; row++)
            {
                for (int space = row; space <= MAX_ROWS / 2; space++)
                {
                    Console.Write("-");
                }
                for (int star = 1; star <= row * 2 - 1; star++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }

            // Variable to subtract the number of stars to be printed on every run
            // of the second loop. This is decremented on each full run of the outer
            // loop.
            int starReducer = 5;

            for (int row = 6; row <= MAX_ROWS; row++)
            {
                for (int space = 1; space <= row - 5; space++)
                {
                    Console.Write("-");
                }
                
                for (int star = MAX_ROWS - 1; star >= row - starReducer; star--)
                {
                    Console.Write("*");
                }
                starReducer--;

                Console.WriteLine();
            }

(The dashes are meant to be spaces, but are used to show if the loop prints the correct number of characters).

 

My issue comes from the two nested loops dealing with drawing the stars. On the first 5 rows, I want the star count to be ascending, adding two more stars to each row, at a time. I currently do this by setting star count to one, and it loops until star count becomes <= (the current row * 2) - 1. This prints the required; * *** ***** etc. for each row.

 

The second sets star count to 9, and does a reverse loop that stops when star count >= the current row (starting with 6) - (a new variable to reduce the amount that the loop counts down each time) starReducer, which is decremented on every completion of said loop.

 

Is there a better, cleaner solution to this? It works but it bugs me that if I were to come back to this in a few days, it might not be as clear to me as it is now.

 

I appreciate anyone who takes the time to have a look.

 

Many thanks,

 

Stitchs.


PARTNERS