Change 2d array bubble sort to counting sort - c#

The following code sorts rows by the first element using bubble method.
I can't change it to counting sort.
public void SortStack(double[,] n)
{
for (int i = 0; i < n.GetLength(0) - 1; i++)
{
for (int j = i; j < n.GetLength(0); j++)
{
if (n[i, 0] > n[j, 0])
{
for (int k = 0; k < n.GetLength(1); k++)
{
var temp = n[i, k];
n[i, k] = n[j, k];
n[j, k] = temp;
}
}
}
}
}
Please help.

As you do bubble sort based on first element of each row. you should do counting sort like that too. so you just need to count first item of each row.
private static int[,] CountingSort2D(int[,] arr)
{
// find the max number by first item of each row
int max = arr[0, 0];
for (int i = 0; i < arr.GetLength(0); i++)
{
if (arr[i, 0] > max) max = arr[i, 0];
}
// we want to get count of first items of each row. thus we need 1d array.
int[] counts = new int[max + 1];
// do the counting. again on first index of each row
for (int i = 0; i < arr.GetLength(0); i++)
{
counts[arr[i, 0]]++;
}
for (int i = 1; i < counts.Length; i++)
{
counts[i] += counts[i - 1];
}
// result is sorted array
int[,] result = new int[arr.GetLength(0), arr.GetLength(1)];
for (int i = arr.GetLength(0) - 1; i >= 0; i--)
{
counts[arr[i, 0]]--;
// now we need to copy columns too. thus we need another loop
for (int j = 0; j < arr.GetLength(1); j++)
{
result[counts[arr[i, 0]], j] = arr[i, j];
}
}
return result;
}
Here is the test.
static void Main()
{
Random rand = new Random();
int[,] arr = new int[3,3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
arr[i, j] = rand.Next(0, 100);
}
}
int[,] newarr = CountingSort2D(arr);
for (int i = 0; i < arr.GetLength(0); i++)
{
Console.Write("{ ");
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ,");
}
Console.Write("} ,");
}
Console.WriteLine();
for (int i = 0; i < newarr.GetLength(0); i++)
{
Console.Write("{ ");
for (int j = 0; j < newarr.GetLength(1); j++)
{
Console.Write(newarr[i, j] + " ,");
}
Console.Write("} ,");
}
Console.WriteLine();
}
Example Output:
{ 49,66,8 },{ 33,39,64 },{ 65,52,76 } // Original array
{ 33,39,64 },{ 49,66,8 },{ 65,52,76 } // Sorted array

Related

Check common elements of two-dimensional arrays of integers, considering the positions they are on

at the beginning I want to mention that I am a beginner in programming. So, I want to write a program that checks the similarity of two-dimensional arrays of integers. The similarity is to be determined by the amount of numbers that are in the same positions in both tables. The user gives the number of columns in the table and the elements themselves, number of rows is the same all the time.The similarity result is displayed as a percentage and the similarity itself should be calculated taking into account the number of elements of the larger array. My problem is: When the two arrays are the same size, the program throws the exception and it doesn't check all the numbers in the column.(I wrote before program for one dimensional array and it works perfectly) So far I have managed to write something like this:
This is what I want to do In the picture, the similarity between the arrays is 20%
{
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int z = 2;
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < z; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int rowLength = tab1.GetLength(0);
int colLength = tab1.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int b = 2;
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < b; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
int Len4gth = tab2.GetLength(0);
int Len2gth = tab2.GetLength(1);
for (int i = 0; i < Len4gth; i++)
{
for (int j = 0; j < Len2gth; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
double similarity= 0;
if (tab1.GetLength(1) > tab2.GetLength(1))
{
for (int i = 0; i < tab2.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) < tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab2[i, j] == tab1[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.GetLength(1) == tab2.GetLength(1))
{
for (int i = 0; i < tab1.GetLength(1); i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity+= 1;
}
}
}
}
if (tab1.Length < tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
if (tab1.Length > tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab1.Length) * 100 + "%");
}
if (tab1.Length == tab2.Length)
{
Console.WriteLine("The similarity of the arrays is: " + (similarity/ tab2.Length) * 100 + "%");
}
Console.ReadKey();
You must compare each element of the first array with the elements of the second array.
use this code :
//get first array items
Console.WriteLine("How extensive is the first table supposed to be?");
int n = int.Parse(Console.ReadLine());
int[,] tab1 = new int[2, n];
Console.WriteLine("Enter the numbers into the first array:");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
tab1[i, j] = int.Parse(Console.ReadLine());
}
}
Console.WriteLine("\n");
//write first array items
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(string.Format("{0} ", tab1[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//get second array items
Console.WriteLine("How extensive is the second table supposed to be?");
int m = int.Parse(Console.ReadLine());
int[,] tab2 = new int[2, m];
Console.WriteLine("Enter the numbers into the second array: ");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
tab2[i, j] = int.Parse(Console.ReadLine());
}
}
//write second array items
Console.WriteLine("\n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < m; j++)
{
Console.Write(string.Format("{0} ", tab2[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
//find similarity items
double similarity = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < n; j++)
{
int firstValue = tab1[i, j];
for (int k = 0; k < 2; k++)
{
for (int d = 0; d < m; d++)
{
if (firstValue == tab2[k, d])
{
similarity += 1;
}
}
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();
this code work without error and It does not matter which array is larger.
If you want similar elements like this example enter link description here, use this code snippet to find similar elements
//find similarity items
double similarity = 0;
int z = n > m ? m : n;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < z; j++)
{
if (tab1[i, j] == tab2[i, j])
{
similarity += 1;
}
}
}
double percentage = n > m ? ((similarity / tab1.Length) * 100) : ((similarity / tab2.Length) * 100);
Console.WriteLine("The similarity of the arrays is: " + percentage + "%");
Console.ReadKey();

How to get all possible 2x2 sub matrices in a 3x3 matrix in C#?

If matrix A of size (3x3), then should i use the method of finding determinants, like grabbing the rows and column of first element and removing it from the array 2D array to get the remaining elements and then moving to the next element and repeating the same steps ?
[{1,2,3},
{4,5,6},
{7,8,9}]
I finally was able to do it, here's what I did :
enter image description here
class program
{
public static void Main()
{
int[,] arr = new int[3, 3];
Console.WriteLine("Enter elements of " + (arr.GetUpperBound(0) + 1) + "x" + (arr.GetUpperBound(1) + 1) + " matrix:");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix entered: ");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
Console.Write("\t" + arr[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("Possible sub-matrices: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j< 3; j++)
{
TrimArray(i,j,arr);
}
}
}
public static int[,] TrimArray(int row, int column, int[,] original)
{
int[,] resultant = new int[original.GetLength(0) - 1, original.GetLength(1) - 1];
for (int i = 0, j = 0; i < original.GetLength(0); i++)
{
if (i == row)
continue;
for (int k = 0, u = 0; k < original.GetLength(1); k++)
{
if (k == column)
continue;
resultant[j, u] = original[i, k];
u++;
}
j++;
}
Console.WriteLine();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j< 2; j++)
{
Console.Write("\t"+resultant[i,j]);
}
Console.WriteLine();
}
return resultant;
}
}
I did this for you yesterday, I created a method that will return a square matrix, given a parent matrix and the length.
static void Main(string[] args)
{
int[][] parentMatrix = new int[][]
{
new int [] { 1, 2, 3 },
new int [] { 4, 5, 6 },
new int [] { 7, 8, 9 }
};
var chunks = GetSubMatrices(parentMatrix, 2);
Console.WriteLine(chunks);
}
static List<int[][]> GetSubMatrices(int[][] parentMatrix, int m)
{
int n = parentMatrix.Length > m ? parentMatrix.Length : throw new InvalidOperationException("You can't use a matrix smaller than the chunk size");
var chunks = new List<int[][]>();
int movLimit = n - m + 1;
var allCount = Math.Pow(movLimit, 2);
for (int selRow = 0; selRow < movLimit; selRow ++)
{
for (int selCol = 0; selCol < movLimit; selCol ++)
{
// this is start position of the chunk
var chunk = new int[m][];
for (int row = 0; row < m; row++)
{
chunk[row] = new int[m];
for (int col = 0; col < m; col++)
{
chunk[row][col] = parentMatrix[selRow + row][selCol + col];
}
}
chunks.Add(chunk);
}
}
return chunks;
}
If you have any problems using it, you can simply comment below.
I needed to solve a problem like and came up with this answer. Hope it adds to your library of answers. If the submatrix specified is not greater than 1, do nothing.
public static void GetSubMatrixes(int[,] arr, int size)
{
int parentMatrixRowLength = arr.GetLength(0);
int parentMatrixColLength = arr.GetLength(1);
var overall = new List<object>();
if(size > 1)
{
for (int i = 0; i < parentMatrixRowLength; i++)
{
//get the columns
for (int j = 0; j < parentMatrixColLength; j++)
{
var subMatrix = new int[size, size];
/*if the new matrix starts from second to the last value in either the row(horizontal or column)
* do not proceed, go to the row or column in the parent matrix
* */
if (j < parentMatrixColLength - (size - 1) && i < parentMatrixRowLength - (size - 1))
{
//add
for (int m = 0; m < subMatrix.GetLength(0); m++)
{
for (int n = 0; n < subMatrix.GetLength(1); n++)
{
/*check the sum of current column value and the sum of the current row value
* of the parent column length and row length if it goes out of bounds
*/
var row = i + m; var col = j + n;
//actual check here
if (row < parentMatrixRowLength && col < parentMatrixColLength)
{
subMatrix[m, n] = arr[i + m, j + n];
}
}
}
overall.Add(subMatrix);
}
}
}
//display the sub matrixes here
for (int i = 0; i < overall.Count; i++)
{
var matrix = overall[i] as int[,];
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
Console.Write(string.Format("{0} ", matrix[y, x]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine();
}
}
}

I am making a sudoku on c#

enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testing_random
{
class Program
{
static void Main(string[] args)
{
int n = 4;
int[,] a = new int[n,n];//declaring the matrix
Random o = new Random();
a[0,0] = o.Next(n);
for (int i = 1; i < n; i++)//filling the first line
{
int d = 1;
while (d != 0)
{
a[i,0] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[i,0] == a[j,0])
d++;
}
}
for (int i = 1; i < n; i++)//filing the first column
{
int d = 1;
while (d != 0)
{
a[0, i] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[0, i] == a[0, j])
d++;
}
}
for (int k = 1; k < n; k++)//filling the rest of the matrix
for (int i = 1; i < n; i++)
{
int d = 1;
while (d != 0)
{
a[i, k] = o.Next(n);
d = 0;
for (int j = 0; j < i; j++)
if (a[i, k] == a[j, k])
d++;
for (int j = 0; j < k; j++)
if (a[i, k] == a[i, j])
d++;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write("{0} ", a[i, j]);
Console.WriteLine();
}
Console.ReadLine();
}
}
}
The output should be a matrix of 4*4 where each column and each line contains each number once.
The problem is when i run the code, not every time i get an output, i think the problem is not every set of first line and column can give a matrix as required the i get into an unending loop.
what i want to do is limit the running time of the application to 100 ms per example,so if the matrix is not filled,the program restarts
What piece of code am i missing?
replace the while( d != 0 ) with a loop which counts up to a certain very large maximum number of iterations. (Try 1000, 100000, whatever.)
Are you trying to randomly insert numbers between 1-4 in the first line of the array? If so there is a much easier way to do it.
You can generate the 4 numbers to be inserted into the array and then just look through the first line of the array and set each value.
Random rnd = new Random();
var randomNumbers = Enumerable.Range(1, 4).OrderBy(i => rnd.Next()).ToArray();
for (int i = 0; i < n; i++)
{
a[i, 0] = randomNumbers[i];
}

How to improve nested loop in C#?

I have a function to calculate the costMatrix like this code below.
public double[,] makeCostMatrixClassic(List<PointD> firstSeq, List<PointD> secondSeq)
{
double[,] costMatrix = new double[firstSeq.Count, secondSeq.Count];
costMatrix[0, 0] = Math.Round(this.getEuclideanDistance(firstSeq[0], secondSeq[0]), 3);
// For D(n,1)
for (int i = 0; i < firstSeq.Count; i++)
{
for (int j = 0; j <= i; j++)
{
costMatrix[i, 0] += Math.Round(this.getEuclideanDistance(firstSeq[j], secondSeq[0]), 3);
}
}
// For D(1,m)
for (int i = 0; i < secondSeq.Count; i++)
{
for (int j = 0; j <= i; j++)
{
costMatrix[0, i] += Math.Round(this.getEuclideanDistance(firstSeq[0], secondSeq[j]), 3);
}
}
// For D(n,m)
for (int i = 1; i < firstSeq.Count; i++)
{
for (int j = 1; j < secondSeq.Count; j++)
{
double min = this.findMin(costMatrix[i - 1, j - 1], costMatrix[i - 1, j], costMatrix[i, j - 1]);
costMatrix[i, j] = min + Math.Round(this.getEuclideanDistance(firstSeq[i], secondSeq[j]), 3);
}
}
return costMatrix;
}
For the 3rd loop (n,m), how could i improve its performance if the "count" of each Sequence is 1 million points.

Index was outside the bounds of the array confusion

I am trying to learn two dimensional array and I wrote some basic code, but I am getting this exception. Could you tell me what am I doing wrong?
static void Main(string[] args)
{
Random rnd = new Random();
int[,] array = new int[2, 2];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; i++)
{
array[i, j] = rnd.Next(0, 100);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
Console.WriteLine(array[i, 0] + "---" + array[i, 1]);
}
Console.ReadLine();
}
The problem is in your inner for-loop. In the iterator section, you're incrementing the i variable, but it should be j. Try this:
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
array[i, j] = rnd.Next(0, 100);
}
}

Categories