Good afternoon, I have a c# jagged array with true and false values (or 0's and 1's) and I want to reverse the values like:
1 1 1 1
0 1 1 0
1 1 1 1
1 0 0 1
to became:
0 0 0 0
1 0 0 1
0 0 0 0
0 1 1 0
Is there an easy way to do it not looping it? something like !myJaggedArray??
A jagged array is an array whose elements are arrays, possibly of different sizes. A jagged array is sometimes called an "array of arrays." The following examples show how to declare, initialize, and access jagged arrays. jaggedArray[0] = new int[5]; jaggedArray[1] = new int[4]; jaggedArray[2] = new int[2];
In a multidimensional array, each element in each dimension has the same, fixed size as the other elements in that dimension. In a jagged array, which is an array of arrays, each inner array can be of a different size. By only using the space that's needed for a given array, no space is wasted.
Jagged arrays are a special type of arrays that can be used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays. An array may be defined as a sequential collection of elements of the same data type.
There is no built-in operation for inverting an array like that, but you can use LINQ to do the inversion without explicit loops:
var res = myJaggedArray.Select(a => a.Select(n => 1-n).ToArray()).ToArray();
The 1-n
trick is a common way of replacing zeros with ones and ones with zeros without using conditional execution.
There is no built-in function, but you can use LINQ.
int[][] input = new[]
{
new[] { 1, 1, 1, 1 },
new[] { 0, 1, 1, 0 },
new[] { 1, 1, 1, 1 },
new[] { 1, 0, 0, 1 }
};
int[][] output = input.Select(row => row.Select(value => value == 1 ? 0 : 1).ToArray()).ToArray();
For logical values:
bool[][] input = new[]
{
new[] { true, true, true, true },
new[] { false, true, true, false },
new[] { true, true, true, true },
new[] { true, false, false, true }
};
bool[][] output = input.Select(row => row.Select(value => !value).ToArray()).ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With