3

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).

dee-see
  • 23,668
  • 5
  • 58
  • 91
Giliweed
  • 4,997
  • 8
  • 26
  • 35

4 Answers4

8

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

int index;
array1[index % array1.Length]
weston
  • 54,145
  • 21
  • 145
  • 203
5

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

new_index = (current_index+3)%length_of_array
Tianyun Ling
  • 1,045
  • 1
  • 9
  • 24
  • I'm still not clear........ how does multiplying the array length helps? could you clear it out a little bit? – Giliweed Sep 17 '14 at 15:51
  • 1
    eg: i+3=b. actually "i" is the 8 element. "b" is the 1 element. (8+3)%10=1. That way gives you the right positon.(You know % operation and array index starts from 0, right) – Tianyun Ling Sep 17 '14 at 15:53
  • yes yes now ... I understand... I misunderstood at first. – Giliweed Sep 17 '14 at 15:58
0

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.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
0

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];
user3473830
  • 7,165
  • 5
  • 36
  • 52