Created
August 9, 2018 17:56
-
-
Save programmerextraordinaire/2c580211fa6acb217fe64013db812a0c to your computer and use it in GitHub Desktop.
Array trim and delete helper functions in C#.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TrimArray.cs | |
// From: https://stackoverflow.com/questions/26303030/how-can-i-delete-rows-and-columns-from-2d-array-in-c | |
// See: https://stackoverflow.com/questions/1183083/is-it-possible-to-extend-arrays-in-c | |
void Main() | |
{ | |
int[,] array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; | |
array.Dump(); | |
var trim = TrimArray(1, 1, array); | |
var trimRow = ArrayRemoveRow(2, array); | |
trim.Dump(); | |
trimRow.Dump(); | |
} | |
public static int[,] TrimArray(int rowToRemove, int columnToRemove, int[,] originalArray) | |
{ | |
int[,] result = new int[originalArray.GetLength(0) - 1, originalArray.GetLength(1) - 1]; | |
for (int i = 0, j = 0; i < originalArray.GetLength(0); i++) | |
{ | |
if (i == rowToRemove) | |
continue; | |
for (int k = 0, u = 0; k < originalArray.GetLength(1); k++) | |
{ | |
if (k == columnToRemove) | |
continue; | |
result[j, u] = originalArray[i, k]; | |
u++; | |
} | |
j++; | |
} | |
return result; | |
} | |
public static int[,] ArrayRemoveRow(int rowToRemove, int[,] originalArray) | |
{ | |
int[,] result = new int[originalArray.GetLength(0) - 1, originalArray.GetLength(1)]; | |
for (int i = 0, j = 0; i < originalArray.GetLength(0); i++) | |
{ | |
if (i == rowToRemove) | |
continue; | |
for (int k = 0, u = 0; k < originalArray.GetLength(1); k++, u++) | |
{ | |
result[j, u] = originalArray[i, k]; | |
} | |
j++; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment