stung
stung

Reputation: 347

Efficiently shrinking a two dimensional array in C#

What is an efficient way to shrink a two dimensional array to a smaller size in C#?

For example:

var bigArray = new object[100, 100];
var smallArray = new object[10, 10];

bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;


startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;

smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);

How will you write SomeShrinkingMethod() ?

Thanks!

EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.

Upvotes: 2

Views: 2873

Answers (3)

winwaed
winwaed

Reputation: 7829

Yes the best method is almost certainly to loop over each cell, although it might be possible to copy a sequence of each 'row'. The method would need to know lower indices of the square to be copied from the source square, and the size (which might be implicit in the destination square definition).

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 546043

You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.

The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.

Edit:

In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.

Upvotes: 2

itsmatt
itsmatt

Reputation: 31416

Depends on what you want your shrinking function to do. You've got to make a new array and do the copy based on whatever your criteria is. My assumption is that you've got a 2d array for a reason, right? The copy could either be trivia (find the next location that has a non-zero value and put it in the next available location in the target) or based on something else. Can you provide more info?

Upvotes: 1

Related Questions