M5A B4N

Personal Blog of Mustafa Basgun

Rotate Array by N Position – Via Programming Pearls

with 2 comments

Lately, I have been trying to finish reading the Programming Pearls written by John Bentley. The chapters related with designing and developing algorithms are really entertaining. One of the questions that was discussed in the early chapters of the book was about an algorithm of rotating a one-dimensional vector, and I want to share my solution written in VB.NET and C# by utilizing a simple string array.

Question (with the terms of an array)

Rotate a one-dimensional array of K elements from left by N positions.
For instance, with K=7 and N=3, the array {a, b, c, d, e, f, g} is rotated to {d, e, f, g, a, b, c}.

Solution

As suggested in the book, I will be using the Array.Reverse method. I will also write the function that rotates an array from right as well in order to carry out the discussion further.

In VB.NET – Rotate By N From Left

In C# – Rotate By N From Left

In VB.NET – Rotate By N From Right

In C# – Rotate By N From Right

Page_Load of an ASP.NET environment would be a good place to test and visualize the results in this case.

In VB.NET

In C#

Finally, results on the browser should be like:

About these ads

Written by Mustafa Basgun

April 11, 2008 at 6:00 AM

Posted in C#, VB.NET

2 Responses

Subscribe to comments with RSS.

  1. A detailed explanation of this array rotation problem with 7 possible solutions with code, time and space complexities at:

    http://www.rawkam.com/?p=1008

    Sunil

    August 8, 2010 at 1:11 PM

  2. Neat solution to a tricky problem. Might check out that Programming Pearl book!

    Oliver

    November 9, 2010 at 9:34 AM


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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: