to convert a list to array[,] there is code:
double[,] arr = new double[list.Count, list[0].Length];
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list[0].Length; j++)
{
arr[i, j] = list[i][j];
}
}
I want to convert it to flatten array so Using the fact
Flattened array index computation
array[(Y coordinate * width) + X coordinate]
2D array index computation
array[Y coordinate, X coordinate]
code changes to
double[] arr = new double[list.Count * list[0].Length];
for (int i = 0; i < list.Count ; i++)
{
for (int j = 0; j < list[0].Length; j++)
{
arr[i] = list[i * list[0].Length + j];
}
}
But What would be the code to convert a List < List < double > > to flatten array?
Is it possible to do it in 2 loops as the above code?
the List<List<double>> represents a double[,] arr
Honestly I'm not 100% sure what you're asking, but to flatten a List<List<>> you can use SelectMany from Linq, here's a simple example:
static void Main(string[] args)
{
var first = new List<double> {1, 2, 3};
var second = new List<double> { 3, 4, 5 };
var lists = new List<List<double>> {first, second};
var flatten = lists.SelectMany(a => a).ToArray();
foreach (var i in flatten)
{
Console.WriteLine(i);
}
}
Given the fact that your list ist a nested enumerable you can simply use Linq.
double[] array = nestedList.SelectMany(a => a).ToArray();
In a loop (i.e. without LINQ) would be something like
public static void Main()
{
List<List<double>> listOfLists = new List<List<double>>();
listOfLists.Add(new List<double>() { 1, 2, 3 });
listOfLists.Add(new List<double>() { 4, 6 });
int flatLength = 0;
foreach (List<double> list in listOfLists)
flatLength += list.Count;
double[] flattened = new double[flatLength];
int iFlat = 0;
foreach (List<double> list in listOfLists)
foreach (double d in list)
flattened[iFlat++] = d;
foreach (double d in flattened)
Console.Write("{0} ", d);
Console.ReadLine();
}
Related
I have a 2D string array.
I just want to randomize the rows order and shuffle the items within each row.
So for example:
[1,2
3,4]
I want it to be as below, row pairs stay same here (order change is valid):
[4,3
1,2] or
[3,4
2,1] or
[4,3
2,1] or
[1,2
3,4] or
[2,1
3,4] or
[2,1
4,3] or
[3,4
1,2]
and i want to avoid below shuffling because i'll read my array row by row, i want to keep my rows to contain same elements. I want to keep my row pairs. Below, my [1,2] and [3,4] rows does not exist anymore :
[1,3
2,4] or
[3,1
4,2] or
[3,1
2,4] or
[1,4
2,3] ....
So here is my array:
array_to_shuffle = new string[len_2d,2];
Shuffle(array_to_shuffle);
and the function i need help :
public void Shuffle(Random rand, string[,] array)
{
rand = new Random();
int[] randomised_array = new int[len_2d];
for (int i = 0; i < len_2d; i++)
{
randomised_array[i] = i;
}
int[] MyRandomArray = randomised_array.OrderBy(x => rand.Next()).ToArray();
string tmp1 = String.Empty;
string tmp2 = String.Empty;
array[MyRandomArray[0], 0] = tmp1;
array[MyRandomArray[0], 1] = tmp2;
array[MyRandomArray[0], 0] = array[MyRandomArray[1],0];
array[MyRandomArray[0], 1] = array[MyRandomArray[1],1];
array[MyRandomArray[1], 0] = tmp2;
array[MyRandomArray[1], 1] = tmp1;
}
Thank you everyone...
Try this code (necessary comments are in code):
static void Main(string[] args)
{
int[,] matrix = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 }, { 9, 10 }, { 11, 12 } };
matrix = Shuffle(matrix);
}
static T[,] Shuffle<T>(T[,] matrix)
{
int howManyRows = matrix.GetLength(0);
int howManyColumns = matrix.GetLength(1);
T[,] randomizedMatrix = new T[howManyRows, howManyColumns];
//we will use those arrays to randomize indexes
int[] shuffledRowIndexes = Enumerable.Range(0, howManyRows).ToArray();
int[] shuffledColumnIndexes = Enumerable.Range(0, howManyColumns).ToArray();
Random rnd = new Random();
shuffledRowIndexes = shuffledRowIndexes.OrderBy(x => rnd.Next()).ToArray();
for (int i = 0; i < howManyRows; i++)
{
// at every loop we get new randomized column idexes, so every row will be shuffled independently
shuffledColumnIndexes = shuffledColumnIndexes.OrderBy(x => rnd.Next()).ToArray();
for (int j = 0; j < howManyColumns; j++)
randomizedMatrix[i, j] = matrix[shuffledRowIndexes.ElementAt(i), shuffledColumnIndexes.ElementAt(j)];
}
return randomizedMatrix;
}
Helpful articles:
Best way to randomize an array with .NET
What are the differences between a multidimensional array and an array of arrays in C#?
This question already has answers here:
Converting jagged array to 2D array C#
(4 answers)
Closed 3 years ago.
I am converting a list within a list to an int[][] using:
int[][] preConvertInts = processedList.Select(array => array.ToArray().ToArray()) as int[][];
I am returning an int[,] in my method. What is the best way to convert an int[][] to an int[,]?
Edit: method
public static int[,] GetIntArrayInts(string dataString){
string data = dataString;
data = data.Replace(Environment.NewLine, "\n");
List<List<int>> processedList = new List<List<int>>();
string[] rows = data.Split('\n');
foreach (string row in rows){
string[] columns = row.Split(',');
List<int> ints = new List<int>();
foreach (string column in columns){
if (int.TryParse(column, out int tileGid)) ints.Add(tileGid);
}
processedList.Add(ints);
}
int[][] preConvertInts = processedList.Select(array => array.ToArray().ToArray()) as int[][];
int[,] processedIntArray = new int[preConvertInts[0].Length, preConvertInts[1].Length];
for (int i = 0; i < preConvertInts.Length; i++){
int[] intArray = preConvertInts[i];
for (int j = 0; j < intArray.Length; j++){
processedIntArray[i, j] = preConvertInts[i][j];
}
}
return processedIntArray;
}
What is the best way to convert an int[][] to an int[,]?
it is the one that is described in this post. Yours will actually also work if all sub-arrays have the same Length. But to cite you:
Unfortunately, my array is not rectangular. – Luna
Then it would not make much sense to try to convert it. Unless you loose values or you add values to make the dimensions of all sub arrays equal.
But your problem in the code is not this conversion but this one:
I am converting a list within a list to an int[][] using:
int[][] preConvertInts = processedList.Select(array => array.ToArray().ToArray()) as int[][];
This is wrong. You will get null for preConvertInts! if you check the return value of the Select call:
You can see that it returns IEnumerable<int[]> and not int[][]. Casting it with as int[][]; does not work and masks only the fact that the 2 types are different from the compiler. What you do there is to convert each sublist into an array and then convert (the already converted array) simply again into an array.
You need to make the select in the proper way:
int [][] preConvertInts = processedList.Select(x=>x.ToArray()).ToArray();
Explanation:
1) in the first step you collect all sublists and convert each one into an array: Select(x=>x.ToArray())
2) now this call returns an IEnumerable<int[]> which you need to convert again to an array:
Select(x=>x.ToArray()).ToArray();
^^
||
note the dot behind the closing parentesis of the Select call
Jagged Array
public static T[,] ToMultiArray<T>(this IList<T[]> arrays)
{
var length = arrays[0].Length;
var result = new T[arrays.Count, length];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
if (array.Length != length)
{
throw new ArgumentException("Misaligned arrays");
}
for (var j = 0; j < length; j++)
{
result[i, j] = array[j];
}
}
return result;
}
Multidimensional Array
public static T[][] ToJaggedArray<T>(this IList<T[]> arrays)
{
var result = new T[arrays.Count][];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
var length = array.Length;
result[i] = new T[length];
for (var j = 0; j < length; j++)
{
result[i][j] = array[j];
}
}
return result;
}
Usage
var preConvertInts = list.ToJaggedArray();
or
var preConvertInts = list.ToMultiArray();
Update
this IList<T[]> arrays this method is for lists which contain arrays,
to fit OP's example it should be (this IList<List<T>> arrays) – Mong
Zhu
Jagged Array
public static T[][] ToJaggedArray<T>(IList<List<T>> arrays)
{
var result = new T[arrays.Count][];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
var length = array.Count;
result[i] = new T[length];
for (var j = 0; j < length; j++)
{
result[i][j] = array[j];
}
}
return result;
}
Multidimensional Array
public static T[,] ToMultiArray<T>(IList<List<T>> arrays)
{
var length = arrays[0].Count;
var result = new T[arrays.Count, length];
for (var i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
if (array.Count != length)
{
throw new ArgumentException("Misaligned arrays");
}
for (var j = 0; j < length; j++)
{
result[i, j] = array[j];
}
}
return result;
}
Note : Totally untested
I am trying to practice some c# questions and I came across a question where given an integer of array, return the array with elements that can be repeated only N times. So, if I have {1,2,3,4,1,1,2,3} and my N=2, my result should be {1,2,3,4,1,2,3}. I tried something but I get the result as {2,3,4,1,1,2,3}.I don't want the first repeated element be removed.
This is what I have tried :
int[] intArray = {3,2,3,1,3};
int N = 2;
var list = new List<int>(intArray);
var newList = new List<int>();
for (int i = 0; i < list.Count; i++)
{
int occur = 1;
for (int j = i+1; j < list.Count; j++)
{
if (occur < N && list[i] == list[j])
{
occur++;
newList.Add(list[j]);
}
else
{
if (list[i] == list[j] )
list.Remove(list[j]);
}
}
}
foreach (var l in list)
{
Console.WriteLine(l);
}
}
}
I would really appreciate any help or guidance.
I suggest using Dictionary<T, int> to count appearances:
private static IEnumerable<T> RepeatOnly<T>(IEnumerable<T> source, int times) {
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (var item in source) {
int count;
if (counts.TryGetValue(item, out count))
counts[item] = ++count;
else
counts.Add(item, count = 1);
if (count <= times)
yield return item;
}
}
....
int[] source = new int[] { 1, 2, 3, 4, 1, 1, 2, 3 };
int[] result = RepeatOnly(source, 2).ToArray();
Console.Write(string.Join(Environment.NewLine, result));
I'd use a dictionary to keep track of how many times each integer has been encountered:
int[] intArray = { 1, 2, 3, 4, 1, 1, 2, 3 };
int N = 2;
var lookup = new Dictionary<int, int>();
LIst<int> list = new List<int>();
foreach (int num in intArray)
{
if (!lookup.ContainsKey(num))
{
lookup[num] = 1;
list.Add(num);
}
else if (lookup[num]++ < N)
{
list.Add(num);
}
}
Hi I am trying to loop through a set of int variables and do an if on each one. I.e.
int a0, a1, a2,a3;
for (int I=0; I < 3; I++)
{
if("a" + I > 10)
{
// do something
}
}
Is this possible?
If you want to iterate you need a collection
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 10 };
foreach (var item in numbers)
{
if(item > 10)
{
// do something
}
}
When you write "a" + I all you are doing is create a string that is a concatenation of the two pieces and is not the parameter you defined before
You can then proceed and use linq:
var filtered = numbers.Where(item => item > 10)
You can use array as variable so you can iterate that :
int[] a = new int[3];
a[0] = 5;
a[1] = 10;
a[2] = 15;
for (int I = 0; I < 3; I++)
{
if (a[I] > 10)
{
// do something, example:
Console.WriteLine(a[I])
}
}
Result :
15
My array is below
int[] T1 = new int[]{1,5,4};
int[] T2 = new int[]{2,4,3};
int[] T3 = new int[]{7,9,1};
A result of the sequence I want it is as follows .
int[] result = {7,9,4}
I want to look for a max value same index[(e.g) 1,2,7) in array.
and Merging array is int[] result = {7,9,4}
please let me know best way
thanks
Here is a simple method for performing your desired operation.
int[] result = new int[T1.Length];
for (int i = 0; i < T1.Length; i++)
{
result[i] = new[] {T1[i], T2[i], T3[i]}.Max();
}
You'll have to add using System.Linq in order to enable the Max() extension.
EDIT
Here is a method that allows you to use any number of arrays:
static T[] MaxElements<T>(params T[][] arrays) where T : IComparable<T>
{
return Enumerable.Range(0, arrays[0].Length)
.Select(i => Enumerable.Range(0, arrays.Length)
.Select(a => arrays[a][i]).Max()).ToArray();
}
You'll have to add the using System.Linq; for this one too. You'll have to make sure that all the elements passed in have the same lengths else you will run into an IndexOutOfRangeException.
It can be used as follows;
var result = MaxElements(T1, T2, T3);
Here is what you need:
static void Main(string[] args)
{
GetMaxArray(new[] { 1, 5, 4 }, new[] { 2, 4, 3 }, new[] { 7, 9, 1 });
}
private static void GetMaxArray(params int[][] m)
{
var length = m.First().Length;
var r = new int[length];
for (var i = 0; i < length; i++)
r[i] = m.Select(a => a[i]).Max();
}
public int[] GetMaxValueArray(List<int[]> arrayList)
{
int[] result = null;
int maxArraySize;
int maxCurrentArrayItemValue;
if (arrayList != null && arrayList.Count > 0)
{
maxArraySize = 0;
foreach (int[] array in arrayList)
if (array.Length > maxArraySize)
maxArraySize = array.Length;
result = new int[maxArraySize];
for (int i = 0; i < maxArraySize; i++)
{
maxCurrentArrayItemValue = 0;
foreach (int[] array in arrayList)
if (i < array.Length)
if (array[i] > maxCurrentArrayItemValue)
maxCurrentArrayItemValue = array[i];
result[i] = maxCurrentArrayItemValue;
}
}
return result;
}