Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invert the values of a logical jagged array in c#?

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??

like image 862
Nauzet Avatar asked Jul 18 '15 16:07

Nauzet


People also ask

What is the syntax of jagged array?

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];

What is the difference between jagged array and multidimensional array?

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.

What is the use of jagged array in C#?

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.


2 Answers

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.

like image 161
Sergey Kalinichenko Avatar answered Sep 21 '22 10:09

Sergey Kalinichenko


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();
like image 36
Ulugbek Umirov Avatar answered Sep 23 '22 10:09

Ulugbek Umirov