Giliweed
Giliweed

Reputation: 5177

Make an array work like a circle

I'm not quite sure how to do this.

pseudocode:

array1 = {"a","b", "c", "d", "e","f", "g","h", "i","j"} //there might be more values.
take c
loop =>c+3 =f
       f+3 =i
       i+3 =b
       b+3 =e
......
end loop

I need to work this array1 as a circle and find the letters adding 3 (f, i, b, e, and more).

Upvotes: 3

Views: 9743

Answers (4)

user3473830
user3473830

Reputation: 7285

We can use % operator to calculate circular index in the array,then we can abstract it in a class

class CircularList<T> : List<T>
        {
            public new T this[int index]
            {
                get { return base[index%Count]; }
                set { base[index%Count] = value; }
            }

            public T this[T item, int distance]
            {
                get
                {
                    var index = IndexOf(item);
                    return this[index + distance];
                }
                set
                {
                    var index = IndexOf(item);
                    this[index + distance] = value;
                }
            }
        }

usage:

    var arr = new CircularList<string> { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
    var b = arr[8 + 2];
    var b2 = arr["i", 2];

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73472

As other answer says % operator is the key to implement it. Here's the implementation.

private string[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };

private IEnumerable<string> GetStringWrapped(int position)
{
    int current = position - 1;
    while (true)
    {
        yield return strings[current];
        current += position;
        current %= strings.Length;
    }
}

Use it as

void SomeMethod()
{
    var resultArray = GetStringWrapped(3).Take(5).ToArray();
    //resultArray contains c,f,i,b,e
}

Note Take is important otherwise your method will never end, it will loop forever.

Upvotes: 0

weston
weston

Reputation: 54791

Use mod (%), then index can be any positive value and it will wrap around:

int index;
array1[index % array1.Length]

Upvotes: 9

Tianyun Ling
Tianyun Ling

Reputation: 1097

You need to write the "find the letters adding 3" function by yourself like:

new_index = (current_index+3)%length_of_array

Upvotes: 5

Related Questions