Random Noise

cat /dev/random >> /dev/dsp

RotateString v2.0

leave a comment »

I added the ability to rotate string right or left. Here is the code:


public enum Direction { Right, Left }

string rotateString(string source, int rotationCount, Direction direction)
{
    if (String.IsNullOrEmpty(source) || rotationCount <= 0)
        return source;

    int pivot = 0;
    List<int> delimiterLocations = new List<int>();
    char[] sourceChars = new char[source.Length];

    char temp;
    // Reverse the whole string and
    // save the dilimiter locations
    for (int i = 0; i < source.Length; i++)
    {
        sourceChars[source.Length - i - 1] = source[i];

        if (source[i] == ' ')
            delimiterLocations.Add(source.Length - i - 1);
    }

    // calculate neededDelimiters mod wordCount
    // (assume words = delimiterCount + 1)
    pivot = rotationCount % delimiterLocations.Count;

    if (pivot > 0)
    {
        if (direction == Direction.Left)
            pivot = delimiterLocations.Count - pivot;

        pivot = delimiterLocations[delimiterLocations.Count - pivot];
    }
    else
    { return source; }

    // reverse the first part
    for (int i = 0, j = pivot - 1; i <= j; i++, j--)
    {
        temp = sourceChars[i];
        sourceChars[i] = sourceChars[j];
        sourceChars[j] = temp;
    }

    // reverse the second part
    for (int i = pivot + 1, j = sourceChars.Length - 1;
         i <= j; i++, j--)
    {
        temp = sourceChars[i];
        sourceChars[i] = sourceChars[j];
        sourceChars[j] = temp;
    }

    return new string(sourceChars);
}
Advertisements

Written by Vivek Unune

September 27, 2008 at 4:46 pm

Posted in .NET

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: