0

NOTICE: I do not want do wrap the index of the array, in fact, I already did that. I also want to wrap the individual values of the array when they are set.

I am trying to get array values to automatically wrap around without using a for loop to do it, because I have a fairly large array (uint16 limit).

I was trying to use a get/set and use a simple wrap code if it is above the max or below the minimum.

Is there any way I can do this?

What I want:

MyArray[0] = 5

//MyArray's max is 3, and minimum is 0

Outcome: MyArray[0] = 2


The problem is not looping around indices, but instead to have the values reduced to a limited range.

I've seen how to implement indexer - like Example of Indexer and how to clamp value - Where can I find the "clamp" function in .NET? (some even were suggested as duplicates).

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Vinny
  • 33
  • 4
  • @AlexeiLevenkov that works on the indexes. OP wants the values mod 5 – pm100 Feb 01 '22 at 00:06
  • i think you will have to create a wrapper around an array and overload the indexer function – pm100 Feb 01 '22 at 00:08
  • @AlexeiLevenkov I will, give me a moment.. – Vinny Feb 01 '22 at 00:09
  • @AlexeiLevenkov no problem, I just want to solve this as quick as possible and I'm willing to do whatever it takes. – Vinny Feb 01 '22 at 00:12
  • @AlexeiLevenkov it´s also clearly not about clamping as a value of 5 would be converted to 2. – rewritten Feb 01 '22 at 00:12
  • https://ideone.com/h181Pi – pm100 Feb 01 '22 at 00:14
  • @AlexeiLevenkov Actually, I'm using my own set method to wrap them! I am currently integrating these answers now, and although I do believe it is a bit hacky, it will work. Thanks for your concern! – Vinny Feb 01 '22 at 00:32

2 Answers2

2

this help?

using System;
public class ModArray
{
    int [] _array;
    int _mod;
    public ModArray(int size, int mod){
        _array = new int[size];
        _mod = mod;
    }
    public int this[int index]
    {
        get => _array[index];
        set => _array[index] = value % _mod;
    }
}
public class Test
{
    public static void Main()
    {
        var ma = new ModArray(10,3);
        ma[0] = 5;
        Console.WriteLine(ma[0]);
        }
}
pm100
  • 48,078
  • 23
  • 82
  • 145
0

If you can change the way you set the values, you can just use the remainder operator (it should be like MyArray[0] = 5 % 3).

But if you can't, you will have to wrap your array in a class (as you cannot subclass arrays) similar to this:

class MyArray
{
   // Declare an array to store the data elements.
   private uint16[] arr = new uint16[100];

   // Define the indexer to allow client code to use [] notation.
   public uint16 this[int i]
   {
      get { return arr[i]; }
      set { arr[i] = value % 5; }
   }
}
rewritten
  • 16,280
  • 2
  • 47
  • 50