sort two dimension array [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to sort two dimension array in Ascending order ,I write this code in C# to sort array but it sort each line in array not all two dimension array , How can I sort all two dimension array
double[,] test_Descriptor = new double[3, 3];
double tempr;
test_Descriptor[0,0]=7;
test_Descriptor[1, 0] = 7;
test_Descriptor[2, 0] = 5;
test_Descriptor[0, 1] = 3;
test_Descriptor[1, 1] = 0;
test_Descriptor[2, 1] = 2;
test_Descriptor[0, 2] = 1;
test_Descriptor[1, 2] = 9;
test_Descriptor[2, 2] = 1;
for (int i = 0; i < test_Descriptor.GetLength(0); i++) // Array Sorting
{
for (int j = test_Descriptor.GetLength(1) - 1; j > 0; j--)
{
for (int k = 0; k < j; k++)
{
if (test_Descriptor[i, k] > test_Descriptor[i, k + 1])
{
tempr = test_Descriptor[i, k];
test_Descriptor[i, k] = test_Descriptor[i, k + 1];
test_Descriptor[i, k + 1] = tempr;
}
}
}
}
for (int y = 0; y < 3; y++)
for (int x = 0; x < 3; x++)
Console.WriteLine("y={0}", test_Descriptor[x,y]);
}

Sorting a true 2D array is difficult, because the sorting algorithm must take into account the 2D structure of the array. You would be better off if you
Make a plain array of size tmp[M*N],
Copy the data into tmp
Sort tmp
Copy the sorted data back into the original array
Here is how you can do it:
double tmp[test_Descriptor.GetLength(0)*test_Descriptor.GetLength(1)];
for (int i = 0; i != test_Descriptor.GetLength(0); i++) {
for (int j = 0; j != test_Descriptor.GetLength(1); j++) {
tmp[i*test_Descriptor.GetLength(1)+j] = test_Descriptor[i, j];
}
}
Array.sort(tmp);
for (int i = 0; i != test_Descriptor.GetLength(0); i++) {
for (int j = 0; j != test_Descriptor.GetLength(1); j++) {
test_Descriptor[i, j] = tmp[i*test_Descriptor.GetLength(1)+j];
}
}

Here is the quickest solution through Linq:
http://www.codeproject.com/Tips/166236/Sorting-a-Two-Dimensional-Array-in-Csharp

Related

Finding a minor matrix of a matrix with C# in Visual Studio

I'm developing an app will be used for calculating matrixes and I'm currently working on minor function and I need a minor matrix for that. So, I wrote the code shown below. It actually works without any error but there is an issue about 4x4 matrices. It changes the 4x1 and 4x2 values.
In this image, places of 9 and 10 are wrong. They are at each others place.
enter image description here
Note: There isn't any problem about textboxes, it's about the array (matrix).
Here is my code. I could easily solve it by rechanging them with a few lines of code but I'm trying to learn C# and Visual Studio, so I want to find the problem in my algorithm.
minorMatrix = new int[rowA.Value - 1, colA.Value - 1];
int k = 0, l = 0;
for (int i = 0; i < rowA.Value - 1; i++)
{
for (int j = 0; j < colA.Value - 1; j++)
{
if (i < row - 1)
{
k = i;
}
else
{
k = i + 1;
}
if (j < col - 1)
{
l = j;
}
else
{
l = j + 1;
}
minorMatrix[i, j] = matrixA[k, l];
}
}
Are you trying to remove the ith row and jth column? This should do it:
int[,] A = new int[3, 3]; // Original matrix
int[,] M = new int[2, 2]; // Matrix with ith row and jth column removed
int i = 2, j = 1; // 3rd row, 2nd column to remove
for (int Mi = 0; Mi < A.GetLength(0); Mi++)
for (int Mj = 0; Mj < A.GetLength(1); Mj++)
{
int Ai = Mi, Aj = Mj;
if (Mi >= i)
Ai = Mi + 1;
if (Mj >= j)
Aj = Mj + 1;
M[Mi, Mj] = A[Ai, Aj];
}

Convert list to 3D Array in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
does anyone know how to convert a List to a 3D Array?. My input list will actually always be a "flattened" verison of a 3D Array, so I will always know the arrays dimensions. Any clues would be great
T[,] output = new T[height, width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
output[i, j] = input[i * width + j];
}
}
This is to convert a List/Array to a 2D Array, but I dont seem to wrap my head around to convert to a 3D Array
You will need to know each dimension of the three of the 3D array. Lets say they are d1, d2, and d3, then you can use this code to get the array you want, assuming an int array:
int i, j, k, p;
int[,,] Arr = new int[d1, d2, d3];
p = 0;
for (i = 0; i < d1; i++)
for (j = 0; j < d2; j++)
for (k = 0; k < d3; k++)
a[i, j, k] = lst[p++];
If you want a solution similar to you example you can try this:
int i, j, k;
int[,,] Arr = new int[d1, d2, d3];
for (i = 0; i < d1; i++)
for (j = 0; j < d2; j++)
for (k = 0; k < d3; k++)
a[i, j, k] = lst[i * d2 * d3 + j * d3 + k];
You just need to know which order the items were stored in when going from an array to a list, and from that you can see how to calculate the index into the list:
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// N.B. You will have to pick which order the dimensions go in.
var ni = 4;
var nj = 3;
var nk = 2;
// Make a list that could be interpreted as a 3-d array:
var x = new List<string>();
for (int k = 0; k < nk; k++)
{
for (int j = 0; j < nj; j++)
{
for (int i = 0; i < ni; i++)
{
x.Add($"{k}-{j}-{i}");
}
}
}
Console.WriteLine(string.Join(", ", x));
// Copy the content of the list to a 3-d array:
string[,,] array1 = new string[nk, nj, ni];
for (int k = 0; k < nk; k++)
{
for (int j = 0; j < nj; j++)
{
for (int i = 0; i < ni; i++)
{
var idx = i + j * (nj + 1) + k * (nk + 1) * (nj + 1);
array1[k, j, i] = x[idx];
Console.Write(array1[k, j, i] + ", ");
}
}
}
Console.ReadLine();
}
}
}
Which outputs, for confirmation,
0-0-0, 0-0-1, 0-0-2, 0-0-3, 0-1-0, 0-1-1, 0-1-2, 0-1-3, 0-2-0, 0-2-1, 0-2-2, 0-2-3, 1-0-0, 1-0-1, 1-0-2, 1-0-3, 1-1-0, 1-1-1, 1-1-2, 1-1-3, 1-2-0, 1-2-1, 1-2-2, 1-2-3
0-0-0, 0-0-1, 0-0-2, 0-0-3, 0-1-0, 0-1-1, 0-1-2, 0-1-3, 0-2-0, 0-2-1, 0-2-2, 0-2-3, 1-0-0, 1-0-1, 1-0-2, 1-0-3, 1-1-0, 1-1-1, 1-1-2, 1-1-3, 1-2-0, 1-2-1, 1-2-2, 1-2-3,
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 3; k++)
a[i, j ,k] = x;

Infinite loop when iterating over a character array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
The following program is going in infinite loop when I am trying to access a multiple line input,do you have any idea why is it not working?
namespace AlternatingCharacters
{
class Program
{
static void Main(string[] args)
{
int N = Int32.Parse(Console.ReadLine());
string[] str = new string[N];
for (int i = 0; i < N ; i++)
{
str[i] = Console.ReadLine();
}
for (int i = 0; i < str.Length; i++)
{
int count = 0;
Char[] strArray = str[i].ToCharArray();
for (int j = 0; j < strArray.Length; j++)
{
if (strArray[i] == strArray[i + 1])
{
count++;
}
}
Console.WriteLine(count);
Console.ReadLine();
}
}
}
}
The problem is in this line:
for (int j = 0; i < strArray.Length; j++)
Your condition is checking on i, not on j, so i will always be 0 (start value) and will never change during the loop.
The right code is:
for (int j = 0; j < strArray.Length; j++)
After that it will fail on this line:
if (strArray[i] == strArray[i + 1])
At the end, it can't find 'the last index + 1' which you can prevent by subtracting one on the end, so this (also I think you need j here):
for (int j = 0; j < strArray.Length - 1; j++)
{
if (strArray[j] == strArray[j + 1])
{
count++;
}
}
The error comes from this piece of code:
for (int i = 0; i < str.Length; i++)
{
int count = 0;
Char[] strArray = str[i].ToCharArray();
for (int j = 0; i < strArray.Length; j++)
{
if (strArray[i] == strArray[i + 1])
{
count++;
}
}
Console.WriteLine(count);
Console.ReadLine();
}
First your loop-condition of the inner loop is whrong. While you increment j you check if i equals the number of elements in your array. More critical than this however is that you also use the whring array-elements. I guess you should use if (strArray[j] == strArray[j + 1]) instead of using i as index.
So all in all this should work:
for (int i = 0; i < str.Length; i++)
{
int count = 0;
Char[] strArray = str[i].ToCharArray();
for (int j = 0; j < strArray.Length; j++)
{
if (strArray[j] == strArray[j + 1])
{
count++;
}
}
Console.WriteLine(count);
Console.ReadLine();
}

How to "join" four smaller matrix together to form a bigger matrix? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
In c# I've got four 10x10 int square matrices and I need to create a 20x20 square matrix by merging the four smaller matrices.
What is the best way to accomplish this?
EDIT: This is my code
int[] first = myArray.Take(myArray.Length / 2).ToArray();
int[] second = myArray.Skip(myArray.Length / 2).ToArray();
int[,] matrice0 = MatrixCalc(first, first);
int[,] matrice1 = MatrixCalc(first, second);
int[,] matrice2 = MatrixCalc(second, first);
int[,] matrice3 = MatrixCalc(second, second);
// Need to join these four matrices here like this: [[0 1][2 3]]
Quickly put together a simple non-scalable solution (only for 4 matrices, if you need a scalable solution you can look at having the matrix as a list of lists and concatenate them) that supposes the matrix lenght is the same. Haven't compiled it so sorry for any bugs
int[,] joinedMatrice = new int[matrice0.GetLength(0) + matrice1.GetLength(0), matrice0.GetLength(1) + matrice2.GetLength(1)];
for (int i = 0; i < matrice0.GetLength(0) + matrice1.GetLength(0); i++)
{
for (int j = 0; j < matrice0.GetLength(1) + matrice2.GetLength(1); j++)
{
int value = 0;
if (i < matrice0.GetLength(0) && j < matrice0.GetLength(1))
{
value = matrice0[i, j];
}
else if (i >= matrice0.GetLength(0) && j < matrice0.GetLength(1))
{
value = matrice1[i - matrice0.GetLength(0), j];
}
else if (i < matrice0.GetLength(0) && j >= matrice0.GetLength(1))
{
value = matrice2[i, j - matrice0.GetLength(1)];
}
else if (i >= matrice0.GetLength(0) && j >= matrice0.GetLength(1))
{
value = matrice3[i - matrice0.GetLength(0), j - matrice0.GetLength(1)];
}
joinedMatrice[i, j] = value;
}
}
You can do this:
// pre-arrange them in the form you want
List<List<int[,]>> sources = new List<List<int[,]>>() {
new List<int[,]>() {matrice0, matrice1},
new List<int[,]>() {matrice2, matrice3}
};
int[,] joint = new int[20, 20];
for (int i = 0; i < joint.GetLength(0); i++) {
for (int j = 0; j < joint.GetLength(1); j++) {
// select the matrix corresponding to value (i,j)
int[,] source = sources[i / matrice0.GetLength(0)][j / matrice0.GetLength(1)];
// and copy the value
joint[i, j] = source[i % matrice0.GetLength(0), j % matrice0.GetLength(1)];
}
}

How to output the shortest path in Floyd-Warshall algorithm?

I'm trying to implement Floyd-Warshall algorithm (all pairs shortest path). In the code below, when I enter some numbers, it gives the last number as input. I know the code is not complete.
Now what should I do to print shortest paths for each i and j? Or what do you suggest to me to do to complete this code. Thanks.
private void button10_Click(object sender, EventArgs e)
{
string ab = textBox11.Text;
int matrixDimention = Convert.ToInt32(ab);
int[,] intValues = new int[matrixDimention, matrixDimention];
string[] splitValues = textBox9.Text.Split(',');
for (int i = 0; i < splitValues.Length; i++)
intValues[i / (matrixDimention), i % (matrixDimention)] = Convert.ToInt32(splitValues[i]);
string displayString = "";
for (int inner = 0; inner < intValues.GetLength(0); inner++)
{
for (int outer = 0; outer < intValues.GetLength(0); outer++)
displayString += String.Format("{0}\t", intValues[inner, outer]);
displayString += Environment.NewLine;
}
int n = (int)Math.Pow(matrixDimention, 2);
string strn = n.ToString();
MessageBox.Show("matrix"+strn+ "in" + strn + "is\n\n\n" +displayString);
////before this line i wrote the codes to get the numbers that user enter in textbox and put it in an 2d array
for (int k = 1; k < n+1; k++)
for (int i = 1; i < n+1; i++)
for (int j = 1; j < n+1; j++)
if (intValues[i, j] > intValues[i, k] + intValues[k, j])
{
intValues[i, j] = intValues[i, k] + intValues[k, j];
string str_intvalues = intValues[i, j].ToString();
MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);
}
else
{
string str_intvalues = intValues[i, j].ToString();
MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);
}
}
To be on a same page, let me show you the Floyd-Warshall algorithm first:
Let us have a graph, described by matrix D, where D[i][j] is the length of edge (i -> j) (from graph's vertex with index i to the vertex with index j).
Matrix D has the size of N * N, where N is total number of vertices in graph, because we can reach the maximum of paths by connecting each graph's vertex to each other.
Also we'll need matrix R, where we will store shortest paths (R[i][j] contains the index of a next vertex in the shortest path, starting at vertex i and ending at vertex j).
Matrix R has the same size as D.
The Floyd-Warshall algorithm performs these steps:
initialize the matrix of all the paths between any two pairs or vertices in a graph with the edge's end vertex (this is important, since this value will be used for path reconstruction)
for each pair of connected vertices (read: for each edge (u -> v)), u and v, find the vertex, which forms shortest path between them: if the vertex k defines two valid edges (u -> k) and (k -> v) (if they are present in the graph), which are together shorter than path (u -> v), then assume the shortest path between u and v lies through k; set the shortest pivot point in matrix R for edge (u -> v) to be the corresponding pivot point for edge (u -> k)
Now that we are on a same page with definitions, algorithm can be implemented like this:
// Initialise the routes matrix R
for (int i = 0; i < N; i++) {
for (int t = 0; t < N; t++) {
R[i][t] = t;
}
}
// Floyd-Warshall algorithm:
for (int k = 0; k < N; k++) {
for (int u = 0; u < N; u++) {
for (int v = 0; v < N; v++) {
if (D[u, v] > D[u, k] + D[k, v]) {
D[u, v] = D[u, k] + D[k, v];
R[u, v] = R[u, k];
}
}
}
}
But how do we read the matrix D?
Let us have a graph:
In GraphViz it would be described as follows:
digraph G {
0->2 [label = "1"];
2->3 [label = "5"];
3->1 [label = "2"];
1->2 [label = "6"];
1->0 [label = "7"];
}
We first create a two-dimensional array of size 4 (since there are exactly 4 vertices in our graph).
We initialize its main diagonal (the items, whose indices are equal, for ex. G[0, 0], G[1, 1], etc.) with zeros, because
the shortest path from vertex to itself has the length 0 and the other elements with a very large number (to indicate there is no edge or an infinitely long edge between them). The defined elements, corresponding to graph's edges, we fill with edges' lengths:
int N = 4;
int[,] D = new int[N, N];
for (int i = 0; i < N; i++) {
for (int t = 0; t < N; t++) {
if (i == t) {
D[i, t] = 0;
} else {
D[i, t] = 9999;
}
}
}
D[0, 2] = 1;
D[1, 0] = 7;
D[1, 2] = 6;
D[2, 3] = 5;
D[3, 1] = 2;
After the algorithm run, the matrix R will be filled with vertices' indices, describing shortest paths between them. In order to reconstruct the path from vertex u to vertex v, you need follow the elements of matrix R:
List<Int32> Path = new List<Int32>();
while (start != end)
{
Path.Add(start);
start = R[start, end];
}
Path.Add(end);
The whole code could be wrapped in a couple of methods:
using System;
using System.Collections.Generic;
public class FloydWarshallPathFinder {
private int N;
private int[,] D;
private int[,] R;
public FloydWarshallPathFinder(int NumberOfVertices, int[,] EdgesLengths) {
N = NumberOfVertices;
D = EdgesLengths;
R = null;
}
public int[,] FindAllPaths() {
R = new int[N, N];
for (int i = 0; i < N; i++)
{
for (int t = 0; t < N; t++)
{
R[i, t] = t;
}
}
for (int k = 0; k < N; k++)
{
for (int v = 0; v < N; v++)
{
for (int u = 0; u < N; u++)
{
if (D[u, k] + D[k, v] < D[u, v])
{
D[u, v] = D[u, k] + D[k, v];
R[u, v] = R[u, k];
}
}
}
}
return R;
}
public List<Int32> FindShortestPath(int start, int end) {
if (R == null) {
FindAllPaths();
}
List<Int32> Path = new List<Int32>();
while (start != end)
{
Path.Add(start);
start = R[start, end];
}
Path.Add(end);
return Path;
}
}
public class MainClass
{
public static void Main()
{
int N = 4;
int[,] D = new int[N, N];
for (int i = 0; i < N; i++) {
for (int t = 0; t < N; t++) {
if (i == t) {
D[i, t] = 0;
} else {
D[i, t] = 9999;
}
}
}
D[0, 2] = 1;
D[1, 0] = 7;
D[1, 2] = 6;
D[2, 3] = 5;
D[3, 1] = 2;
FloydWarshallPathFinder pathFinder = new FloydWarshallPathFinder(N, D);
int start = 0;
int end = 1;
Console.WriteLine("Path: {0}", String.Join(" -> ", pathFinder.FindShortestPath(start, end).ToArray()));
}
}
You can read 'bout this algorithm on wikipedia and get some data structures generated automatically here
When you are using Floyd algorithm, it saves only the shortest distance from node i to node j of your graph. So, you can also save the path to nodes. How to do it?
one of the ways to implement it - is to save the parent (the node, which is a previous node for current node in the path) node. You are to make another matrix, which will contain paths. It could look like this:
int[,] pathS = new int[matrixDimention, matrixDimention];
for (int i = 0; i < splitValues.Length; i++){
intValues[i / (matrixDimention), i % (matrixDimention)] = Convert.ToInt32(splitValues[i]);
pathS[i / (matrixDimention), i % (matrixDimention)] = -1;
}
.....
for (int k = 1; k < n+1; k++)
for (int i = 1; i < n+1; i++)
for (int j = 1; j < n+1; j++)
if (intValues[i, j] > intValues[i, k] + intValues[k, j]){
intValues[i, j] = intValues[i, k] + intValues[k, j];
pathS[i,j] = k;
string str_intvalues = intValues[i, j].ToString();
MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);
}
else{
string str_intvalues = intValues[i, j].ToString();
MessageBox.Show("Shortest Path from i to j is: " + str_intvalues);
}
Now you have additional pathS array, which contains intermidiate paths between nodes i and j. For better understandning you should consider, that pathS[i,j] is a node between this two nodes (e.g. i -> [k] -> j). But your path could be longer, than 3 nodes (that's why I wrote node k in [] braces). So, now you have to check path between i and k - pathS[i,k] and path between k and j - pathS[k,j]. And do the same recursively, until pathS between some i and j equals to "-1".

Categories