Reversing order of elements in multidimensional array - c#

I have an array with elemnents in order 1,2,3,4,5 and I would need to reverse it so it will be 5,4,3,2,1.
What about the following pseudo code? Is here not an easier way
EDIT: I Am sorry I thought multidimensional array
someclass [,] temporaryArray=new someclass [ArrayLenght,ArrayLenght];
//for each dimension then
for(int I=0;I<ArrayLenghtOfDimension;I++)
{
temporaryArray[ArrayLenghtOfDimension-I]=Array[I];
}
Array=temporaryArray;

The array base class has a Reverse() extension method built in
int[] originalArray = new int[] { 1, 2, 3, 4, 5 };
int[] reversedArray = originalArray.Reverse().ToArray();
Note that the Reverse method returns IEnumerable, so you need to call ToArray() on the result.
And if you need to just iterate over the elements in the array, then all you need is
foreach (int element in originalArray.Reverse())
Console.WriteLine(element);
Oops - Reverse is on IEnumerable, not Array, so you can use that with any collection.
IEnumerable<int> IEnumerableInt = new List<int>() { 1, 2, 3 };
int[] reversedArray2 = IEnumerableInt.Reverse().ToArray();

Yes there is fast solution exists in .net
int[] values = new int[] { 1, 2, 3, 4, 5 };
Array.Reverse(values);
Your array is reversed. so you can iterate through it
foreach (int i in values)
{
Response.Write(i.ToString());
}
the above code will display
54321
It will also work for string[], char[] or other type of arrays

Event though the Array class has Reverse methods defined:
Array.Reverse(originalArray); // original array is now reversed
If all you need to do is iterate backwards over it do the following:
for(int I= ArrayLength - 1; I >= 0; I--)
{
}
This avoid re-allocating memory for the reversed array.

Array.Reverse is the best way to do this. Do you care about order of the elements at all? If so,then you can do the following.
int[] originalArray = new int[] { 10, 2, 13, 4, 5 };
int[] descOrderedArray = originalArray.OrderByDescending(i => i).ToArray();
int[] ascOrderedArray = originalArray.OrderBy(i => i).ToArray();

For a multi-dimensional array it's the same idea
int[][] multiDimArray = new int[][] { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 } };
int[][] reversedMultiArray = multiDimArray.Reverse().ToArray();
produces an array of two arrays that is: {4, 5, 6}, {1, 2, 3}

Related

Operate LINQ queries on 'vertical' rather than 'horizontal' space

I can't figure out how to do this, if even possible.
An example:
int[][] myArrays = {
new int[] {1, 2, 3},
new int[] {4, 5, 3},
new int[] {1, 2, 3}
};
int[] avgArray = myArrays.//Some LINQ statement to average every Nth element in the second dimension (essentially "flatten" the array)
//avgArray == {2, 3, 3}
To do this so far, I can only think of:
int ndDimLen = myArrays.GetLength(1);
int[] avgArray = new int[ndDimLen];
myArrays.Select(
arr => arr.Select( (n, i) => avgArray[i] += n )
);
avgArray = avgArray.Select( n => n / ndDimLen ).ToArray();
But this defeats the purpose, and isn't a particularly good idea on jagged arrays...
Also, I'd definitely like to avoid transposition, as it's quite a slow operation when operating on large arrays!
Thank you for your time!
You could iterate throught the [Columns] index while a [Row].Length reports that it contains a [Column] in the dimension whose values you need to average.
(Using the terms Column and Row for simplicity, as a visual aid)
An example, using Linq's .Average() to compute the average value of the sequence:
int[][] myArrays = {
new int[] {1, 2, 3},
new int[] {4, 5, 3},
new int[] {1, 2, 3},
};
int column = 2;
double avg = myArrays.Select((arr, i) => myArrays[i][column]).Average();
Result: 3
With a more complex structure, we need to verify whether the current [Column] contains a value:
int[][] myArrays = {
new int[] {1, 2, 3},
new int[] {3, 4, 5},
new int[] {3, 4},
new int[] {1, 2, 3, 4},
new int[] {1},
new int[] {4, 5, 3}
};
int column= 2;
double? avg = myArrays.Select((arr, i) =>
((arr.Length > column) ? myArrays?[i][column] : null)).Average();
Result Column 1: { 1, 3, 3, 1, 1, 4 } => 2.1666666...
Result Column 2: { 2, 4, 4, 2, 5 } => 3.4
Result Column 3: { 3, 5, 3, 3 } => 3.5
Result Column 4: { 4 } => 4
Same method, applied to all the [Columns]:
var Averages = Enumerable.Range(0, myArrays.Max(Arr => Arr.Length))
.Select(col => myArrays
.Select((arr, idx) =>
((arr.Length > col) ? myArrays?[idx][col] : null))
.Average()).ToList();
Enumerable.Range gives some flexibility.
The code above generates a series of int elements starting from 0 and incrementing the value to the number of Colums in the Array (Max(Arr => Arr.Length) selects the Array's Row containing the higher number of elements).
So, you could average the numbers in the first Column only (Index = 0) with:
var Averages = Enumerable.Range(0, 1).Select( ... )
or from Columns 1 to 3 (Indexes 1 to 3):
var Averages = Enumerable.Range(1, 3).Select( ... )
Yes, it is possible, but not on this object.
Basically, myArrays is an array of arrays, so LINQ only sees one row at a time, you cannot make it to see columns, because it's just not how it works.
What you could do, is to transpose this "table" first, that is change places of columns and rows. How to do it has already been discussed here so I will just refer you to it.
Using knowledge how to transpose it, you can make a method that will do it, and use LINQ on it, like:
Transpose(myArray).Select(predicate);
You didn't specify what you want if the arrays have unequal length:
int[][] myArrays =
{
new int[] {1, 2},
new int[] {4, 5, 3, 7, 5, 3, 4, 5, 1},
new int[] {1, 2, 3}
};
Let's assume your arrays all have the same length.
If you plan to use this functionality regularly, consider writing an extension function for two dimensional arrays. See Extension Methods Demystified
public static IEnumerable<int> ToVerticalAverage(this int[][] array2D)
{
if (array2D == null) throw new ArgumentNullException(nameof(array2D);
// if input empty: return empty
if (array2D.Any())
{ // there is at least one row
// check number of columns:
int nrOfColumns = array2D.First().Length;
if (!array2D.All(row => row.Length == nrOfColumns)
{
// TODO: decide what to do if arrays have unequal length
}
// if here, at least one row, all rows have same number of columns
for(int columNr = 0; columNr < nrOfColumns; ++columNr)
{
yield return array2D.Select(row => row[i]).Average();
}
}
// else: no rows, returns empty sequence
}
Usage:
int[][] myInputValues = ...
IEnumerable<int> averageColumnValues = myInputValues.ToVerticalAverage();
If you have several functions where you need the values of the columns, write an extension function to fetch the columns (= transpose the matrix)
public static IEnumerable<IEnumerable<int>> Transpose(this int[][] array2D)
{
// TODO: check input
int nrOfColumns = array2D.First().Length;
for(int columNr = 0; columNr < nrOfColumns; ++columNr)
{
yield return array2D.Select(row => row[columnNr];
}
}
public static IEnumerable<int> ToVerticalAverage(this int[][] array2D)
{
// TODO: check input
foreach (IEnumerable<int> column in array2D.Transpose())
{
yield return column.Average();
}

Find duplicates of exactly two items from Array1 in Array2 using LINQ C#

Say I've got an
Array1 [1,2,3]
and a List of arrays Array2 [3,2,4] Array3 [2,16,5]
I need to return only those elements of the List which contain exactly two ints from Array1. In this case, Array2 since integers 2 and 3 intersect;
Thanks
Try to combine Where() and Count():
var matches = new int[] { 1, 2, 3 };
var data = new List<int[]>
{
new int[] { 3, 2, 4 },
new int[] { 2, 16, 5 }
};
var result = data.Where(x => x.Count(matches.Contains) == 2);
since it's int[] you can use the .Intersect() directly. For example
from a in arrays where a.Intersect(Array1).Count() == 2 select a
//arrays contains Array2 and Array3

How to add data from 1d to 2d array in C#

How can I add an array to another 2D array? For example
//change this
array2d = { {1,2,3}, {4,5,6} };
//to this
array2d = { {1,2,3}, {4,5,6}, {7,8,9} };
//by adding
array1d = {7,8,9};
Is there any better way other than create a new array, which is bigger than the old one, then copy the old array to the array?
I would recommend a List<List<int>> for something like this, unless you have a reason not to.
The code for it may look something like this:
List<List<int>> my2dList = new List<List<int>>()
{
new List<int>()
{
1,
2,
3
},
new List<int>()
{
4,
5,
6
},
};
my2dList.Add(new List<int>(){7,8,9});
Alternatively, if you really want to limit each column to a length of three, consider using an inner structure with an immutable size (array of size 3, etc)
It seems like you might want to use a different data structure, a list of arrays would make this much easier.
Extended version of the code snippet posted by #VP. includes the back-conversion from List(List> to Jagged Array using Linq:
// 2d array to List
List<List<int>> ar2list = new List<List<int>>()
{
new List<int>() { 1, 2, 3 },
new List<int>() { 4, 5, 6 },
};
// adding item to List
ar2list.Add(new List<int>() { 7, 8, 9 });
// List to Jagged array conversion using Linq
int[][] _arrConcat = ar2list.Select(Enumerable.ToArray).ToArray();
Finally, pertinent to this particular use-case as requested by OP, int[][] can be easily converted to int[,] with simple for loop:
array2d = new int[_arrConcat.Length, 3];
for (int i = 0; i<_arrConcat.Length; i++)
{
for (int j = 0; j < 3; j++)
{
array2d[i, j] = _arrConcat[i][j];
}
}
where array2d is the original array with added index/content.
Hope this will help. Best regards,

Compact an Array function in C#

How can I make a Function to compact an array with duplicate entries?
For example!
A function that will take a sorted array of integers and return the array compacted. That is, given an array containing: 1, 2, 6, 8, 8, 8, 9, 10, 10, when the function returns, the contents of the array should be: 1, 2, 6, 8, 9, 10.
This is NOT hw. I am trying to make a function that will do this.
How about:
array = array.Distinct().ToArray();
or, as a function:
private int[] RemoveDuplicates(int[] array)
{
return array.Distinct().ToArray();
}
then call it with:
array = RemoveDuplicates(array);
extension methods:
public static T[] RemoveDuplicates<T>(this T[] array)
{
return array.Distinct().ToArray();
}
public static List<T> RemoveDuplicates<T>(this List<T> list)
{
return list.Distinct().ToList();
}
using for array:
int[] array = new[] {1, 3, 4, 3};
array = array.RemoveDuplicates();
using for list:
List<int> list = new List<int> {1, 3, 4, 3};
list = list.RemoveDuplicates();
The most straightforward way is probably with Linq
array = array.Distinct().ToArray()
However, Linq is not always the fastest approach.
If you do not wish to use Linq, you can do something like this (untested, but close)
List<int> compacted = new List<int>();
// If array is not a local variable:
// Assign to a variable to avoid re-evaluating the property every loop iteration
// Otherwise use array.Length as the loop termination condition to enable array
// bounds check elimination. Thanks #Harold for the insight
// http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx
int max = array.Length;
int last = 0;
for (int i=0; i < max; i++)
{
if (i == 0)
{
compacted.Add(array[i]);
last = array[i];
}
else
{
if (array[i] != last) compacted.Add(array[i]);
last = array[i];
}
}
array = compacted.ToArray();

How to easily order an array from largest to smallest in Visual C#?

I have a small array of ints. I want to reorder the array from largest to smallest. Is there a method to do this?
You could use Array.Sort:
int[] array = new[] { 1, 3, 2 };
Array.Sort(array, (x, y) => y.CompareTo(x));
As far as complexity is concerned:
On average, this method is an O(n log
n) operation, where n is the Length of
array; in the worst case it is an O(n
^ 2) operation
You can do it using Array Sort & Reverse:
Array.Sort(array);
Array.Reverse(array);
Example:
[Test]
public void Test()
{
var array = new[] { 1, 3, 2 };
Array.Sort(array);
Array.Reverse(array);
CollectionAssert.AreEquivalent(new[] { 3, 2, 1 }, array);
}
You can try something like this
int[] ints = new int[] {1, 2, 3, 4, 1, 2, 3};
var sorted = ints.OrderBy(i => i);
Found at Sort array of items using OrderBy<>

Categories

Resources