0

I currently have a working method that shifts the values of one property of objects in an array:

    public class Group
    {
        public Position[] Positions { get; private set; }

        public void Shift()
        {
            var last = Positions[Count - 1].Tile;
            for( int i = Count - 1 ; i > 0 ; i-- )
            {
                // Note this shifts Tile value and not the array itself
                Positions[i].Tile = Positions[i - 1].Tile;
            }
            Positions[0].Tile = last;
        }
    }

    public class Position
    {
        // [other properties]

        public Tile Tile { get; set; }
    }

The problem is that this method needs to run a lot in an algorithm and it is the one that consumes most CPU time.

I'm searching for a better way to shift these values and found BlockCopy in this excellent answer: https://stackoverflow.com/a/52465132/1554208

But it's used to shift the array itself. Is there a way to copy the content of a property (here a simple pointer)?

I'm open to:

  • Use unsafe pointer methods
  • Change the Position class if needed
  • Any other suggestion

EDIT

Is there some way to "calculate" the size in bytes of a Position object, "calculate" the address of the Tile property within that object, and use something like Buffer.BlockCopy to copy these values at that specific address in the array?

2
  • 1
    How about have a references to Tile in an array and shift that. Commented May 12, 2019 at 9:12
  • Position is a necessary layer. One Position can be in multiple Groups. If a Tile change for a Position, it must change in all the groups. Commented May 12, 2019 at 12:59

1 Answer 1

0

you can solve it by Array.Copy in C#

public class Group
{
    public Position[] Positions { get; private set; }

    public void ShiftRight()
    {
        Array.Copy(Positions,0,Positions,1,Positions.Length-1);//Right
        Positions[0].Tile=null;

        Array.Copy(g,1,g,0,g.Length-1);
    }
    public void ShiftLeft()
    { 
        Array.Copy(Positions,1,Positions,0,Positions.Length-1)
        Positions[Positions.Length-1].Tile=null;
    }
}

public class Position
{
    // [other properties]

    public Tile Tile { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

No. This will shift the entiore Positions array, but it cannot move. Positions must keep the same index in the array. Only the Tiles inside them must shift.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.