Read array 2D and output as table C# - c#

I am new at programming in C# and I'm trying to display to whole content of a matrix in the format of a table, however what I got so far is to read the enum and read one line from the matrix. Instead I need to read multiple lines from the matrix and output as a table.
when I run the program I get to insert data twice in row and the output should've been this data inside a table, but only one line is being shown.
Here's the code:
static int getInsertIndex(string[,] matrix)
{
for (int j = 0; j < matrix.GetLength(0); j++)
{
if (string.IsNullOrEmpty(matrix[j, 0])) return j;
}
return -1;
}
private static void InsertData<T>(string[,] matrix)
{
// int newId = generateId(ref id);
int n = getInsertIndex(matrix), id = 1;
matrix[n, 0] = Convert.ToString(id++);
int x = matrix.GetLength(1) - 1;
matrix[n, x] = "true";
for (var j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"\nInsert {GetHeader<T>(j)}: ");
matrix[0, j] = Console.ReadLine();
} while (string.IsNullOrEmpty(matrix[0, j]));
}
}
private static void ListData<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var l = 0; l < matrix.GetLength(0); l++)
{
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[0, i];
}
}
PrintRow(array);
PrintLine();
}
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
private static void ShowHeader<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = GetHeader<T>(i);
}
PrintLine();
PrintRow(array);
PrintLine();
}
private static void PrintLine()
{
Console.WriteLine(new string('-', Console.WindowWidth - 1));
}
private static void PrintRow(IReadOnlyCollection<string> columns)
{
var width = (Console.WindowWidth - 1 - columns.Count) / columns.Count;
var row = columns.Aggregate("|", (current, column) => current + AlignCentre(column, width) + "|");
Console.WriteLine(row);
}
static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;
return string.IsNullOrEmpty(text)
? new string(' ', width)
: text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
enum ClientHeader { Id, Name, Surname, Addres, CodPostal, Telephone, Email, State };
private static void Main()
{
var client = new string[4, 7];
InsertData<ClientHeader>(client);
Console.Clear();
InsertData<ClientHeader>(client);
ShowHeader<ClientHeader>(client);
ListData<ClientHeader>(client);
}
}
}

There are 2 issues:
1) In the InsertData() function, you want to update the n th row.
Replace
matrix[0, j] = Console.ReadLine();
by
matrix[n, j] = Console.ReadLine();
2) In the ListData() function you want to show each row, so you need to move the array variable into the first for loop. Replace array[i] = matrix[0, i] with array[i] = matrix[l, i] because you are displaying the l th row.
private static void ListData<T>(string[,] matrix)
{
for (var l = 0; l < matrix.GetLength(0); l++)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[l, i];
}
PrintRow(array);
}
PrintLine();
}

Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
public class Program
{
private static void Main()
{
List<List<string>> data = new List<List<string>>() {
new List<string>() { "Name", "Age", "Weight"},
new List<string>() { "John", "33", "180"},
new List<string>() { "Mary", "32", "125"},
new List<string>() { "Harry", "40", "200"}
};
DataTable dt = new DataTable();
for (int i = 0; i < data.Count; i++)
{
if (i == 0)
{
foreach (string col in data[i])
{
dt.Columns.Add(col);
}
}
else
{
dt.Rows.Add(data[i].ToArray());
}
}
}
}
}

Related

Merge sort 2d array c#

I have task to create merge sort algorithm in c# for 2d array. Array looks like that
X1 Y1
X2 Y2
…
Xn Yn
I need to take array from file and sort the lines in ascending x order, also the program should check for the absence of pairs of coordinates with the same X values and at the same time different Y values, when array was sorted, the programm should write it in the file.
I had created algorithm for 1d array, but can't understand how to rewrite it for 2d array, here is my code, please help me
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
class Program
{
//array merging
static void Merge(int[] num, int lowIndex, int middleIndex, int highIndex)
{
var left = lowIndex;
var right = middleIndex + 1;
var tempArray = new int[highIndex - lowIndex + 1];
var index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (num[left] < num[right])
{
tempArray[index] = num[left];
left++;
}
else
{
tempArray[index] = num[right];
right++;
}
index++;
}
for (var j = left; j <= middleIndex; j++)
{
for (var i=0;;) {
tempArray[index] = num[j];
index++; }
}
for (var j = right; j <= highIndex; j++)
{
for (var i = 0; ;)
{
tempArray[index] = num[j];
index++;
}
}
for (var j = 0; j < tempArray.Length; j++)
{
for(var i=0; ;)
{
num[lowIndex + j] = tempArray[j];
}
}
}
//merge sorting
static int[] MergeSort(int[] num, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
var middleIndex = (lowIndex + highIndex) / 2;
MergeSort(num, lowIndex, middleIndex);
MergeSort(num, middleIndex + 1, highIndex);
Merge(num, lowIndex, middleIndex, highIndex);
}
return num;
}
public static int[] MergeSort(int[] num)
{
return MergeSort(num, 0, num.Length - 1);
}
static void Main(string[] args)
{
Console.WriteLine("Merge sorting");
string[] lines = File.ReadAllLines(#"C:\Users\glebk\source\repos\ConsoleApp18\ConsoleApp18\file.txt");
int[,] num = new int[lines.Length, lines[0].Split(' ').Length];
for (int i = 0; i < lines.Length; i++)
{
string[] temp = lines[i].Split(' ',',');
for (int j = 0; j < temp.Length; j++)
{
num[i, j] = Convert.ToInt32(temp[j]);
Console.Write(num[i, j]+" ");
}
Console.ReadKey();
}
Console.WriteLine("Sorted array: {0}", string.Join(",", MergeSort(num)));
}
}`
The most direct way of doing it is replacing
tempArray[index] = num[left];
with something like this
static void CopyLine(int[,] destArr, int destIndex, int[,] sourceArr, int sourceIndex)
{
for (int i = 0; i < destArr.GetLength(1); ++i)
{
destArr[destIndex, i] = sourceArr[sourceIndex, i];
}
}
here is the whole code
static void CopyLine(int[,] destArr, int destIndex, int[,] sourceArr, int sourceIndex)
{
for (int i = 0; i < destArr.GetLength(1); ++i)
{
destArr[destIndex, i] = sourceArr[sourceIndex, i];
}
}
//array merging
static void Merge(int[,] num, int lowIndex, int middleIndex, int highIndex)
{
var left = lowIndex;
var right = middleIndex + 1;
var tempArray = new int[highIndex - lowIndex + 1, num.GetLength(1)];
var index = 0;
while ((left <= middleIndex) && (right <= highIndex))
{
if (num[left, 0] < num[right, 0])
{
CopyLine(tempArray, index, num, left);
left++;
}
else
{
CopyLine(tempArray, index, num, right);
right++;
}
index++;
}
for (var j = left; j <= middleIndex; j++)
{
CopyLine(tempArray, index, num, j);
index++;
}
for (var j = right; j <= highIndex; j++)
{
CopyLine(tempArray, index, num, j);
index++;
}
for (var j = 0; j < tempArray.GetLength(0); j++)
{
CopyLine(num, lowIndex + j, tempArray, j);
}
}
//merge sorting
static void MergeSort(int[,] num, int lowIndex, int highIndex)
{
if (lowIndex < highIndex)
{
var middleIndex = (lowIndex + highIndex) / 2;
MergeSort(num, lowIndex, middleIndex);
MergeSort(num, middleIndex + 1, highIndex);
Merge(num, lowIndex, middleIndex, highIndex);
}
}
public static void MergeSort(int[,] num)
{
MergeSort(num, 0, num.GetLength(0) - 1);
}
static void WriteArray(string description, int[,] arr)
{
Console.WriteLine(description);
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[,] num = new int[,] { { 3, 5 }, { 1, 10 }, { 7, 3 }, { 2, 1 }, { 5, 2 } };
WriteArray("Original array:", num);
MergeSort(num);
WriteArray("Sorted array:", num);
Console.ReadKey();
}
There are also other options, you can fuse two int values into one long value and sort it as 1D array. But it would need additional steps.

Trying to write my void method as a string array method

I created a sort method that takes in a string array and sorts it alphabetically. However, I made a void method, not thinking about the fact that I can't really write a void method's data to a file, which is what I am trying to do. So now I am having trouble converting my method to a string array method as opposed to the void method. Can someone please point me in the right direction?
public void Sort(String[] arr)
{
String temp = "";
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i].CompareTo(arr[j]) > 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.WriteLine(arr[i]);
}
}
updated code with my call to method:
class InsertionSort
{
public static string[] Sort(String[] arr)
{
String temp = "";
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i].CompareTo(arr[j]) > 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
return arr;
}
}
}
class Program
{
static void Main(string[] args)
{
String[] words = File.ReadLines("jumbled english FILTERED.ALL.txt").ToArray();
String[] sortedWords = InsertionSort.Sort(words);
System.IO.File.WriteAllLines("sortedtext.txt", sortedWords);
}
}
}
my code
what it prints
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
String[] arr = new String[3];
arr[0] = "B";
arr[1] = "C";
arr[2] = "A";
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console.WriteLine(arr[2]);
Sort(arr);
Console.WriteLine(arr[0]);
Console.WriteLine(arr[1]);
Console.WriteLine(arr[2]);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\Test\Result.txt"))
{
foreach (string str in arr)
{
file.WriteLine(str);
}
}
Console.ReadLine();
}
public static void Sort(String[] arr)
{
String temp = "";
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i].CompareTo(arr[j]) > 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
//Console.WriteLine(arr[i]);
}
}
}
}
Result :
Ben,
Let me try to answer your question in two parts.
First, you wanted to return values from the method. For this, you need to change the return Type to string[] and return the arr after processing
public string[] Sort(string[] arr)
{
string temp = "";
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i].CompareTo(arr[j]) > 0)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
return arr;
}
Second part, you mentioned in comment that you want to write this to a file. You can use System.IO.File.WriteLineAllLines method to write to a file.
var input = new []{ "First line", "Third line" , "Second line" };
string[] lines = Sort(input);
System.IO.File.WriteAllLines(#"OutputFile.txt", lines);
To read more on writing contents to a file, please refer
Why make your own sorter and not use Array.Sort?
var lines = new[] { "one", "two", "three", "four" };
Array.Sort(lines, StringComparer.Ordinal);
System.IO.File.WriteAllLines("file.txt", lines);
I don't know why you creating such method as we have already linq to do such thing.
You can do this way. I hope it will work for you.
string[] words = { "India", "England", "America", "China", "Australia" };
string[] Ascending = words.OrderBy(c => c).Select(c=>c).ToArray(); // Ascending order
string[] Descending = words.OrderByDescending(c => c).Select(c => c).ToArray(); // Ascending order
foreach (var item in Ascending)
{
Console.WriteLine(item);
}
foreach (var item in Descending)
{
Console.WriteLine(item);
}

Delete columns from CSV then save in different folder path

I need a script that opens a CSV from a specific file path, deletes specific columns and then exports the CSV to a specified folder.
Due to other scripts that will be integrated with this at a later stage, I have decided to do this using C#.
I have previously used Perl and achieved the desired result, but it isn't suitable for my application.
I found this link where I found this code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace CSV
{
class CSV
{
private Dictionary<Tuple<int, int>, string> _data;
private int _rows;
private int _cols;
public int Rows { get { return _rows; } }
public int Cols { get { return _cols; } }
public CSV()
{
Clear();
}
public void Clear()
{
_rows = 0;
_cols = 0;
_data = new Dictionary<Tuple<int, int>, string>();
}
public void Open(StreamReader stream, char delim = ',')
{
string line;
int col = 0;
int row = 0;
Clear();
while ((line = stream.ReadLine()) != null)
{
if (line.Length > 0)
{
string[] values = line.Split(delim);
col = 0;
foreach (var value in values)
{
this[col, row] = value;
col++;
}
row++;
}
}
stream.Close();
}
public void Save(StreamWriter stream, char delim = ',')
{
for (int row = 0; row < _rows; row++)
{
for (int col = 0; col < _cols; col++)
{
stream.Write(this[col, row]);
if (col < _cols - 1)
{
stream.Write(delim);
}
}
stream.WriteLine();
}
stream.Flush();
stream.Close();
}
public string this[int col, int row]
{
get
{
try
{
return _data[new Tuple<int, int>(col, row)];
}
catch
{
return "";
}
}
set
{
_data[new Tuple<int, int>(col, row)] = value.ToString().Trim();
_rows = Math.Max(_rows, row + 1);
_cols = Math.Max(_cols, col + 1);
}
}
static void Main(string[] args)
{
CSV csv = new CSV();
csv.Open(new StreamReader(#"C:\mid\Dev\CSV_Splitter\VR_Path\New\Import_User_Sample_en.csv"));
csv[0, 0] = "Column0";
csv[1, 1] = "100";
csv[2, 2] = "200";
csv[3, 3] = "300";
csv[4, 4] = "400";
csv.Save(new StreamWriter(#"C:\mid\Dev\CSV_Splitter\VR_Path\Proccessed\test_out.csv"));
}
}
}
This uses C# to open a CSV file, manipulate it and save it in a new path.
I want to delete columns 0, 1, 2 and 3 from the csv file instead of manipulating the data.
Can anyone help?
You can use code you posted, just change Save method, initialize col variable with 4 and you should be done.
public void Save(StreamWriter stream, char delim = ',')
{
if(_cols > 4)
{
for (int row = 0; row < _rows; row++)
{
for (int col = 4; col < _cols; col++)
{
stream.Write(this[col, row]);
if (col < _cols - 1)
{
stream.Write(delim);
}
}
stream.WriteLine();
}
}
stream.Flush();
stream.Close();
}
Update:
To exclude 10th column, skip writing data in the 10th position.
public void Save(StreamWriter stream, char delim = ',')
{
if(_cols > 4)
{
for (int row = 0; row < _rows; row++)
{
for (int col = 4; col < _cols; col++)
{
if(col != 10)
{
stream.Write(this[col, row]);
if (col < _cols - 1)
{
stream.Write(delim);
}
}
}
stream.WriteLine();
}
}
stream.Flush();
stream.Close();
}

Display values from array 2D inside table C#

I am new at programming in C# and I'm trying to create a method that allows me to create a table and visualize the data inside of a matrix. However none of the methods I have tried seems to work as supposed.
Basically the method works to visualize the header which is the Enum, however I need to read the data from the matrix and the output has to be in the form of a table. Here´s the code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
enum clientHeader { Id, Name, Surname, Addres, Cod_Postal, Telephone, Email, State };
class Program
{
static void Main(string[] args)
{
string[,] client = new string[3, 7];
insertData<clientHeader>(client);
Console.Clear();
showHeader<clientHeader>(client);
listData<clientHeader>(client);
Console.ReadKey();
}
static void insertData<T>(string[,] matrix)
{
int x = matrix.GetLowerBound(1);
matrix[0, x] = "1";
for (int j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"\nInsert {GetHeader<T>(j)}: ");
matrix[0, j] = Console.ReadLine();
} while (String.IsNullOrEmpty(matrix[0, j]));
}
}
static void listData<T>(string[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"{matrix[i, j]}\t");
}
}
Console.WriteLine();
}
}
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
static void showHeader<T>(string[,] matrix)
{
int x = matrix.GetUpperBound(1);
string[] array = new string[x];
for (int i = 0; i < array.Length; i++)
{
array[i] = GetHeader<T>(i);
}
PrintLine();
PrintRow(array);
PrintLine();
}
static int tableWidth = 120;
static void PrintLine()
{
Console.WriteLine(new string('-', tableWidth));
}
static void PrintRow(params string[] columns)
{
int width = (tableWidth - columns.Length) / columns.Length;
string row = "|";
foreach (string column in columns)
{
row += AlignCentre(column, width) + "|";
}
Console.WriteLine(row);
}
static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;
if (string.IsNullOrEmpty(text))
{
return new string(' ', width);
}
else
{
return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
}
}
}
In the code below, the main modification I made was to have your ListData method act like your ShowHeader method, so that the data is aligned in columns underneath the header:
private static void ListData<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[0, i];
}
PrintRow(array);
PrintLine();
}
See if that works for you. Here's the full code with some other refactoring:
private static void InsertData<T>(string[,] matrix)
{
// Just add dummy data while testing
matrix[0, 0] = "1";
matrix[0, 1] = "FirstName";
matrix[0, 2] = "LastName";
matrix[0, 3] = "123 Main St";
matrix[0, 4] = "98765";
matrix[0, 5] = "(123) 456-7890";
matrix[0, 6] = "user#provider.com";
return;
matrix[0, matrix.GetLowerBound(1)] = "1";
for (var j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"\nInsert {GetHeader<T>(j)}: ");
matrix[0, j] = Console.ReadLine();
} while (string.IsNullOrEmpty(matrix[0, j]));
}
}
private static void ListData<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[0, i];
}
PrintRow(array);
PrintLine();
}
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
private static void ShowHeader<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (var i = 0; i < array.Length; i++)
{
array[i] = GetHeader<T>(i);
}
PrintLine();
PrintRow(array);
PrintLine();
}
private static void PrintLine()
{
Console.WriteLine(new string('-', Console.WindowWidth - 1));
}
private static void PrintRow(IReadOnlyCollection<string> columns)
{
var width = (Console.WindowWidth - 1 - columns.Count) / columns.Count;
var row = columns.Aggregate("|", (current, column) => current + AlignCentre(column, width) + "|");
Console.WriteLine(row);
}
static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;
return string.IsNullOrEmpty(text)
? new string(' ', width)
: text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
enum ClientHeader { Id, Name, Surname, Addres, CodPostal, Telephone, Email, State };
private static void Main()
{
var client = new string[3, 7];
InsertData<ClientHeader>(client);
Console.Clear();
ShowHeader<ClientHeader>(client);
ListData<ClientHeader>(client);
GetKeyFromUser("\nDone! Press any key to exit...");
}
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
Output
I tried doing like this, don't know if it's what you meant, however the program crashes. Still doesn't read second line, I think the variable text from the method AlignCenter is null for some reason.
private static void ListData<T>(string[,] matrix)
{
var array = new string[matrix.GetUpperBound(1)];
for (int j = 0; j < array.GetUpperBound(0); j++)
{
for (var i = 0; i < array.Length; i++)
{
array[i] = matrix[j, i];
}
PrintRow(array);
PrintLine();
}
}

How to sort a 2D array filld with random numbers

I'm doing a class assignment,
I need to create an 2D array of random numbers and sort them either bubble or other sorting codes. I'm fine with single array, but the problem is a 2D array filled with random numbers, I just don't get it.
Random numbers should be made of (-I,I) interval it's a user input. Sorry for bad english, haven't gotten any degree. In working on visual C# windows form.
looking for simple couple cicles method.
example. : A[MxN] ->>> B[MxN] (Sorted 1.....n)
Getting the random numbers is trivial:
Random rnd;
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
array[y][x] = l - rnd.Next(2 * l + 1);
Random.Next() will return a random value between 0 and the given parameter (excluding the parameter; which is the reason for the + 1).
A 2D array can be sorted just like a 1D array, it only depends how you want to handle multiple lines, e.g. is it just for display or do you want to sort every line for itself, etc.
Here's a solution which first sorts each row's columns into order, then sorts each row comparing by first column, then second, etc:
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
double[,] data = GenerateData();
OutputData(data, "Before");
SortData(ref data);
OutputData(data, "After");
}
double[,] GenerateData()
{
Random randomGenerator = new Random(DateTime.UtcNow.Millisecond);
double[,] data = new double[5, 5];
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
data[i, j] = (randomGenerator.NextDouble() * 2) - 1;
}
}
return data;
}
void OutputData(double[,] data, string message)
{
Console.WriteLine("=====================");
Console.WriteLine(message);
Console.WriteLine("=====================");
for (int i = 0; i < data.GetLength(0); i++)
{
for (int j = 0; j < data.GetLength(1); j++)
{
Console.Write(data[i, j]);
Console.Write("\t");
}
Console.WriteLine();
}
}
void SortData(ref double[,] data)
{
//sort sub arrays
SortDataRows(ref data);
//sort this array
for (int i = 0; i < data.GetLength(0)-1; i++)
{
for (int j = i; j < data.GetLength(0); j++)
{
for (int k = 0; k < data.GetLength(1); k++)
{
if (data[i, k].CompareTo(data[j, k]) < 0) //if already in order exit loop
{
break;
} else if (data[i, k].CompareTo(data[j, k]) > 0) //if out of order switch and loop
{
SwapRows(ref data, i, j);
break;
}//else orders are equal so far; continue to loop
}
}
}
}
void SortDataRows(ref double[,] data)
{
for (int row = 0; row < data.GetLength(0); row++)
{
for (int i = 0; i < data.GetLength(1) - 1; i++)
{
for (int j = i; j < data.GetLength(1); j++)
{
if (data[row, i].CompareTo(data[row, j]) > 0)
{
Swap<double>(ref data[row, i], ref data[row, j]);
}
}
}
}
}
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
void SwapRows(ref double[,]data, int i, int j)
{
for (int k = 0; k < data.GetLength(1); k++)
{
Swap<double>(ref data[i, k], ref data[j, k]);
}
}
}
}
The code's not the best (haven't had a cup of tea yet), but should do what you're after.
Here's a better solution (not using a 2D array as such, but using a structure which can easily be converted to/from such an array):
sing System.Diagnostics;
namespace StackOverflow.Demos
{
class Program
{
public static void Main(string[] args)
{
new Program();
Console.WriteLine("Done");
Console.ReadKey();
}
Program()
{
List<List<double>> data = GenerateData(5, 5).ToList<List<double>>();
OutputData(data,"Before");
foreach (List<double> item in data)
{
item.Sort();
}
data.Sort(CompareListOfDoubles);
OutputData(data,"After");
}
private IEnumerable<List<double>> GenerateData(int index1, int index2)
{
Random rnd = new Random(DateTime.UtcNow.Millisecond);
List<double> result;
for (int i = 0; i < index1; i++)
{
result = new List<double>(index2);
for (int j = 0; j < index2; j++)
{
result.Add(rnd.NextDouble() * 2 - 1);
}
yield return result;
}
}
private void OutputData(List<List<double>> data, string message)
{
Console.WriteLine(message);
foreach (List<double> list in data)
{
foreach (double datum in list)
{
Console.Write(datum);
Console.Write("\t");
}
Console.WriteLine();
}
}
static int CompareListOfDoubles(List<double> a, List<double> b)
{
for (int i = 0; i < a.Count; i++)
{
if (i > b.Count) return -1;
if (a[i] > b[i]) return -1;
if (a[i] < b[i]) return 1;
}
if (b.Count > a.Count) return 1;
return 0;
}
double[,] ConvertListListDoubleTo2DArray(List<List<double>> data)
{
double[,] result = new double[data.Count, data[0].Count];
for (int i = 0; i < result.GetLength(0); i++)
{
for (int j = 0; j < result.GetLength(1); j++)
{
result[i, j] = data[i][j];
}
}
return result;
}
}

Categories

Resources