C# Select id int nested array by pair - c#

I have array1 like this
int[][] array1 = int[][] { int[]{0,7}, int[]{0,1}, int[]{0,6}, int[]{0,5}, int[]{1,7} }
and I have array2 like this:
int[][] array2 = int[][] { int[]{0,7}, int[]{0,5} }
How can I get index of element in array1 from elements in array2?
For instance:
int[] { 0, 7 } is id of 0 because it is first element
int[] { 0, 5 } - id - 3 because it is fourth element in array1.
And int[] { 0, 5 } and int[] { 5, 0 } are the same members.
Should I simply loop array1 and check members inside? Or there is smarter way of searching coincident items in array1?

You can do this if you want to get every id in array1.
You'll need to add a using System.Linq;
List<int> ids = new List<int>();
foreach (int[] arr in array2)
{
var ordered = arr.OrderBy(x => x);
ids.Add(Array.FindIndex(array1, a => a.OrderBy(x => x).SequenceEqual(ordered)));
}
Note that ids will contain -1 where arr is not found in array1.
The arrays are being sorted before checking them for being equal, as you mentioned that [5, 0] is the same member as [0, 5].

Related

How create multidimensional array in c#

I would like to create a multidimensional array in c#, but I`m not sure how. The array should look like this:
array1, array2, array3
array4, array5, array6
array7, array8, array9
The each small array will store 3 ints. I managed to create a multidimensional array that stores 1 array on each line, but I need to store 3 arrays on each line.
The code is below:
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 3, 5 };
jaggedArray[1] = new int[] { 0, 2, 4 };
jaggedArray[2] = new int[] { 11, 22, 33 };
Your description corresponds to 2d array of arrays int[,][]:
int[] array1 = new int[] {1, 2, 3};
...
int[] array9 = new int[] {89, 562, 356};
...
// 2d array of arrays (array1..array9)
int[,][] array = new int[,][] {
{ array1, array2, array3, },
{ array4, array5, array6, },
{ array7, array8, array9, },
};
You can declare as given below. you can use jagged arrays.
int[][,] jaggedArray4 = new int[3][,]
{
new int[,] { {1,3,3}, {5,7,7},{1,2,3} },
new int[,] { {1,3,3}, {5,7,7},{1,2,3} },
new int[,] { {1,3,3}, {5,7,7},{1,2,3} }
};
Console.WriteLine(jaggedArray4[0][1,0]);//displayed first row , 2nd element array's first element
If you always have 3x3x3, you can use a 3d array:
int[,,] my3dArray = new int[3,3,3];
And you can access it like so:
my3dArray[0,0,0] = 5;
my3dArray[0,0,1] = 2;
my3dArray[1,2,0] = 41;
Console.WriteLine(myArray[1,2,0]); // prints 41
If each dimension is a variable size, you could used an array of arrays of arrays (kind of a 3d jagged array):
int[][][] myJagged = new int[3][][];
myJagged[0] = new int[3][];
myJagged[0][0] = new int[] {1, 2, 3}; // etc. until you've initialized all the arrays at all levels
Console.WriteLine(myJagged[0][0][2]); // prints 3
Alternatively, if only your last dimension is a variable size (or if it's easier to work with), you could use a 2d array of arrays:
int[,][] myArray = new int[3,3][];
myArray[0,0] = new int[] { 5, 2, 41 };
Console.WriteLine(myArray[0,0][2]); // prints 41

Trying to arrange a 2D array in ascending order C#

I'm trying to arrange a 2D array in ascending order. This code runs for a 1D array but i'm struggling to implement it for 2D so that it places each row of the array in ascending order.
1D
public static void Main(string[] args)
{
int[] sam = { 4, 7, 2, 0 };
Array.Sort(sam);
foreach (int value in sam)
{
Console.Write(value);
Console.Write(' ');
}
Console.WriteLine();
}
2D
public static void Main(string[] args)
{
int[] sam = { 4, 7, 2, 0 }, {4, 6, 2, 0};
Array.Sort(sam);
foreach (int value in sam)
{
Console.Write(value);
Console.Write(' ');
}
Console.WriteLine();
}
You can do something like this:
static void Main(string[] args) {
int[][] sam = new int[2][];
sam[0] = new int[] {4, 6, 2, 0};
sam[1] = new int[] {4, 7, 2, 0};
foreach(var array in sam)
{
Array.Sort(array);
foreach(var item in array)
Console.Write(item+" ");
Console.WriteLine();
}
}
Here, we are declaring a 2D array and then initializing each array one at a time. Then, we are looping through the sam array and then sorting each 1D array within it.
There are multiple solutions, one solution I'm thinking is using Array of Arrays (Jagged Array).
Let's say, if you have jagged array as defined below
int[][] numbers2 = new int[][] {
new int[]{4,5,6},
new int[]{1,2,3},
new int[]{7,8,9}
...
};
You can get sorted Jagged array using
int[][] sorted = numbers2.Select(x=> string.Join("-", x.ToArray()))
.OrderBy(x=>x)
.Select(x=> x.Split('-').Select(int.Parse).ToArray())
.ToArray();
Another option, let's your input is a 2d array you could do more or less same but output is sorted Jagged array.
int[][] sorted_array = numbers.Cast<int>()
.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / (numbers.GetUpperBound(0) +1))
.Select(x => string.Join("-", x.Select(v => v.Value)) )
.OrderBy(x=>x)
.Select(x=> x.Split('-').Select(int.Parse).ToArray())
.ToArray();
These are just my options, you will be the best to choose which is right to your solution.
Check this Example

Find index of an array in List of arrays in C#

If you had a List of arrays like:
List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });
How would you find the index of { 2, 1} in the List?
I do not want to use an iteration loop. I would like a concise method like the one suggested by PaRiMaL RaJ in Check if string array exists in list of string:
list.Select(ar2 => arr.All(ar2.Contains)).FirstOrDefault();
(the above code will return true if members of a given string array exist in a list of string arrays)
var myArr = new int[] { 2, 1 };
List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 4, 1 });
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });
int index = ListOfArrays.FindIndex(l => Enumerable.SequenceEqual(myArr, l));
You can use the SequenceEqual method for this. See MSDN: https://msdn.microsoft.com/en-us/library/vstudio/bb348567(v=vs.100).aspx
You can try this:
List<int[]> ListOfArrays = new List<int[]>();
ListOfArrays.Add(new int[] { 1, 1 });
ListOfArrays.Add(new int[] { 2, 1 });
var chk = ListOfArrays.FindIndex(e => (e.SequenceEqual(new int[] { 2, 1 })));

How to remove int[] from List<int[]>?

I'm quite new in using List as arrays in C#. So I've encounter a problem while using it.
I'm trying to removed an int[] (integer array) from a List<int[]> using the Remove but failed to removed the int[] from the List<int[]>.
here is the code:
List<int[]> trash = new List<int[]>()
{
new int[] {0,1},
new int[] {1,0},
new int[] {1,1}
};
int[] t1 = {0,1};
trash.Remove(t1);
Is it just a bug?
Or it doesn't recognize int[] ?
The problem is that every array type is a reference type and List removes items based on equality where equality for reference types is by default reference equality. That means, you have to remove the very same array as is in the list.
The following for example works perfectly well:
int[] t1 = {0,1};
List<int[]> trash = new List<int[]>()
{
t1,
new int[] {1,0},
new int[] {1,1}
};
trash.Remove(t1);
If you want to remove all the lists which have the same contents (in the same order) as a target list, you can do so using List.RemoveAll() along with Linq's SequenceEqual():
List<int[]> trash = new List<int[]>
{
new [] {0, 1},
new [] {1, 0},
new [] {1, 1}
};
int[] t1 = {0, 1};
trash.RemoveAll(element => element.SequenceEqual(t1));
Console.WriteLine(trash.Count); // Prints 2
This is very slow though. Better to use an index if you can.
Error is List of array uses reference type data. therefore please use the removeAt method of List like below:
List<int[]> trash = new List<int[]>()
{
new int[] {0,1},
new int[] {1,0},
new int[] {1,1}
};
trash.RemoveAt(0);
With RemoveAt you need to pass the index of integer array you want to remove from the list.
Your t1 variable is a new instance of the array. So it won't be equal to the first element in the list.
Try:
trash.Remove(trash[0]);
or
trash.RemoveAt(0);
The .Remove method looks the address of the element. If they are equal, then it removes. You should do like this.
int[] t1 = {0,1};
int[] t2 =new int[] {1,0};
int[] t3 =new int[] {1,1};
List<int[]> trash = new List<int[]>()
{
t1,t2,t3
};
trash.Remove(t1);
foreach(var x in trash)
{
if(x[0] == t1[0] && x[1] == t[1])
{
trash.Remove(x);
break;
}
}
this should work aswell
It is just because you are trying to remove item that is new.
Its address reference is different than the object that is already in list.That is why it is not remove.
Int is value type..
And Int[] is reference type..
So when you do it with Int list
List<int> trash = new List<int>(){ 1, 13, 5 };
int t1 = 13;
trash.Remove(t1);//it will removed
But for Int[]
List<int[]> trash = new List<int[]>()
{
new int[] {0,1},
new int[] {1,0},
new int[] {1,1}
};
var t1 = {0,1};
trash.Remove(t1);//t1 will not removed because "t1" address reference is different than the "new int[] {0,1}" item that is in list.
To remove-
trash.Remove(trash.Find(a => a.SequenceEqual(t1)));
SequenceEqual() Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.
If you want to remove the exact sequence, but you don't have the possibility to remove the exact object (sequence coming out from elsewhere) you can search for the right sequence using a lambda expression or an anonymous method:
List<int[]> trash = new List<int[]>
{
new [] {0, 1},
new [] {1, 0},
new [] {1, 1}
};
int[] t1 = { 0, 1 };
//using anonymous method
trash.RemoveAll(delegate(int[] element) { return element.SequenceEqual(t1); });
//using lambda expression
trash.RemoveAll(element => element.SequenceEqual(t1));

How to access and re-format Jagged Array in C#

I have 2D array in c#, like this:
int[][] 2darray = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
how can I get one column as normal array, like
int[] array = 2darray[1][]; //example, not working
and have
int[] array = {3,4};
?
Thanks.
There are several reasons why your code can't compile
This way it works:
int[][] array2d = { new[]{ 1, 2 }, new[]{ 3, 4 }, new[]{ 5, 6 }, new[]{ 7, 8 } };
int[] array = array2d[0];
Problems:
2darray is not a valid variable name
The indexing is wrong
The initialization of the original array is wrong
EDIT:
As stated by #heltonbiker, if you require all elements of the first column, you can use this:
int[] col = array2d.Select(row => row[0]).ToArray();
For an array with two columns and four rows, you can use LINQ this way:
using System.Linq;
first_column = _2darray.Select(row => row[0]).ToArray();
Note that changing the first or second array will not change the other one.
You are confusing jagged arrays and multidimensional arrays in C#. While they are similar, there is a slight difference. Rows in a jagged array can have a different number of elements, while in a 2D-array they are of the same length. Therefore when working with jagged arrays you need to remember to write handling for a missing column element. I composed a sample console app below to show how both of them work - it uses 0 as a substitute for a missing element, but you can throw an error etc.:
using System.Collections.Generic;
namespace JaggedArrayExample
{
class Program
{
static void Main(string[] args)
{
//jagged array declaration
int[][] array1;
//jagged array declaration and assignment
var array2 = new int[][] {
new int[] { 1, 2 },
new int[] { 3, 4 },
new int[] { 5, 6 },
new int[] { 7, 8 }
};
//2D-array declaration
int[,] array3;
//2D-array declaration and assignment (implicit bounds)
var array4 = new int[,] {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
//2D-array declaration and assignment (explicit bounds)
var array5 = new int[4, 2] {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
//get rows and columns at index
var r = GetRow(array2, 1); //second row {3,4}
var c = GetColumn(array2, 1); //second column {2,4,6,8}
}
private static int[] GetRow(int[][] array, int index)
{
return array[index]; //retrieving the row is simple
}
private static int[] GetColumn(int[][] array, int index)
{
//but things get more interesting with columns
//especially if jagged arrays are involved
var retValue = new List<int>();
foreach (int[] r in array)
{
int ub = r.GetUpperBound(0);
if (ub >= index) //index within bounds
{
retValue.Add(r[index]);
}
else //index outside of bounds
{
retValue.Add(0); //default value?
//or you can throw an error
}
}
return retValue.ToArray();
}
}
}
try this, it should work
int[] array = array2d[1];
Change the name of the variable to array2d, you cannot have variable that starts with number, a variable can start with letter or underscore.

Categories