I have a matrix of 50 rows and 2 columns and I want to sort them based on the comparison of the value of the second column filed. Here what I mean, if my matrix as:
[00][01]
[10][11]
[20][21]
[30][31]
[40][41]
[50][51]
I want to compare [01] and [11] and if [01] lesser than [11] I want to exchange the entire second row with the first row, to be like this (for example):
[10][11]
[00][01]
[20][21]
[30][31]
[40][41]
[50][51]
I tried using C# and came up with this algorithm but it didn't work:
int temp1, temp2;
for (int i = 0; i < 50; i++)
{
for (int j = i + 1; j < 2; j++)
{
if (rating[i, j] < rating[i + 1, j])
{
temp1 = rating[i + 1, j - 1];
temp2 = rating[i + 1, j];
rating[i + 1, j - 1] = rating[i, j - 1];
rating[i + 1, j] = rating[i, j];
rating[i, j - 1] = temp1;
rating[i, j] = temp2;
}
}
}
Can someone tell me a key to workout this problem or if you have the answer in c,c++ or another language please share it with us.
Thank you.
I believe you are trying to sort the matrix in descending order of second column. Give this code a try.
int[][] mat = new[] { new[] { 4, 4 }, new[] { 5, 1 }, new[] { 3, 2 }, new[] { 6, 1 } };
var ordered = mat.OrderByDescending(i => i[1]);
Your implementation of sort algorithm is wrong. The inner loop should not run from i+1 to 1.
Try implementing the simple bubble sort:
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 49-i; j++)
{
if (rating[j, 1] < rating[j + 1, 1]) // column 1 entry comparison
{
temp1 = rating[j, 0]; // swap both column 0 and column 1
temp2 = rating[j, 1];
rating[j, 0] = rating[j+1, 0];
rating[j, 1] = rating[j+1, 1];
rating[j+1, 0] = temp1;
rating[j+1, 1] = temp2;
}
}
}
Related
I don't know what to do, my program is not working
I need to sort a two-dimensional array by the first elements of a row in descending order by rearranging the rows
(need to sort string without sort item)
Let's say I'm given an array:
1 2 3
4 5 6
7 8 9
As a result of the program, I need to get:
7 8 9
4 5 6
1 2 3
`
using System;
namespace BubbleSort
{
internal class Program
{
static void Main(string[] args)
{
//Объявление массива и его размерности
const int n = 3;
int bubble;
int[,] A =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
};
//Алгоритм пузырьковой сортировки
for (int i = 0; i < n; i++)
{
for(int j = 0; j < n - 1; j++)
{
if (A[i, 0] < A[i++, 0])
{
for(j = 0; j < n-1; j++)
{
bubble = A[i, j];
A[i, j] = A[i, j+1];
A[i, j+1] = bubble;
}
}
}
}
//Вывод массива
for (int y = 0; y < n; y++)
{
for (int x = 0; x < n; x++)
{
Console.Write(A[y, x] + " ");
}
Console.WriteLine();
}
}
}
}
`
From the code in your comments, I'm not sure why you have a nested loop for swapping the values since a single loop will do. I've removed that here.
If you refer to the pseudocode implementation on Wikipedia, you'll see that you need to keep running multiple passes across the array until everything is sorted. You can do this like so:
bool swapped;
do
{
swapped = false; // reset swapped
for (int i = 0; i < n - 1; i++) // loop through all but the last row
{
if (A[i, 0] < A[i + 1, 0]) // determine if this row needs to be swapped with the next row
{
swapped = true; // mark swapped
for (int j = 0; j < n; j++) // swap each item in row i with each item in row i+1
{
int tmp = A[i, j];
A[i, j] = A[i + 1, j];
A[i + 1, j] = tmp;
}
}
}
}
while (swapped); // if we swapped anything, we need to make another pass to ensure the array is sorted
We can also do away with the need for n by using .GetUpperBound(dimension) which returns a value between 0 and n - 1 (where n is the count of items in the array in that dimension). Because the result is effectively n - 1, I've modified the loop conditions slightly:
bool swapped;
do
{
swapped = false;
for (int i = 0; i < A.GetUpperBound(0); i++)
{
if (A[i, 0] < A[i + 1, 0])
{
swapped = true;
for (int j = 0; j <= A.GetUpperBound(1); j++)
{
int tmp = A[i, j];
A[i, j] = A[i + 1, j];
A[i + 1, j] = tmp;
}
}
}
}
while (swapped);
We can also refer to the "Optimizing bubble sort" section of the Wikipedia page and implement that instead, which will make our code run more optimally:
int n = A.GetUpperBound(0); // get the initial value of n
do
{
int newn = 0; // default newn to 0, so if no items are visited, it will remain 0 and the loop will exit
for (int i = 0; i < n; i++)
{
if (A[i, 0] < A[i + 1, 0])
{
for (int j = 0; j <= A.GetUpperBound(1); j++)
{
int tmp = A[i, j];
A[i, j] = A[i + 1, j];
A[i + 1, j] = tmp;
}
newn = i; // store the current (highest) value of i swapped
}
}
n = newn; // set the value of n to the highest value of i swapped
}
while (n > 0); // loop until n == 0
The logic here (as explained on Wikipedia) is that by the end of the first pass, the last item is in the correct position. By the end of the second pass, the second-to-last and last items are in the correct position, and so on. So each time, we can visit one less item. When we have 0 items to visit, we have 0 items to swap, and the sort is complete.
You can see this optimised version in this YouTube visualisation.
I think the line
if (A[i, 0] < A[i++, 0])
should read
if (A[i, 0] < A[i+ 1, 0])
Im having trouble with code, I get
System.IndexOutOfRangeException
in the first loop in the find() method. Could you guys help me? I cant figure out whats wrong.
I've found this code for java and changed a little bit for C#. In java code there was int[][] A, Ive changed it to int[,]. P.S on java, code works.
class Program
{
static void Main(string[] args)
{
int[,] A = { { 1, 7, 9, 2 }, { 8, 6, 3, 2 }, { 1, 6, 7, 8 },
{ 2, 9, 8, 2 } };
Console.WriteLine("{0}", find(A));
}
public static int find(int[,] A)
{
int[,] solution = new int[A.Length + 1, A.Length + 1];
solution[0, 0] = A[0, 0];
for(int i = 1; i < A.Length; i++)
{
solution[0, i] = A[0, i] + solution[0, i - 1]; //IndexOutOfRangeException
}
for(int i = 1; i < A.Length; i++)
{
solution[i, 0] = A[i, 0] + solution[i - 1, 0];
}
for(int i = 1; i < A.Length; i++)
{
for(int j = 1; j < A.Length; j++)
{
solution[i, j] = A[i, j]
+ Math.Min(solution[i - 1, j], solution[i, j - 1]);
}
}
return solution[A.Length - 1, A.Length - 1];
}
}
The problem is that in a jagged array ([,]) the property Length will give you the overall amount of elements, in your case A.Length == 16 but you want only one dimension. The solution would be to use GetLength.
for (int i = 1; i < A.GetLength(1); i++)
you need to use 0 for the X-Dimension and 1 for the Y-Dimenstion ( [X,Y]) see the documenation for details.
This is how your method should look like:
public static int find(int[,] A)
{
int[,] solution = new int[A.GetLength(0) + 1, A.GetLength(1)+ 1];
solution[0, 0] = A[0, 0];
for (int i = 1; i < A.GetLength(1); i++)
{
solution[0, i] = A[0, i] + solution[0, i - 1];
}
for (int i = 1; i < A.GetLength(0); i++)
{
solution[i, 0] = A[i, 0] + solution[i - 1, 0];
}
for (int i = 1; i < A.GetLength(0); i++)
{
for (int j = 1; j < A.GetLength(1); j++)
{
solution[i, j] = A[i, j]
+ Math.Min(solution[i - 1, j], solution[i, j - 1]);
}
}
return solution[A.GetLength(0) - 1, A.GetLength(1) - 1];
}
Well, this is giving me a real headache. I'm building a matrix determinant function to compute NxN determinant, and I'm using recursion.
The logic is working right but I'm not able to get the final value computed correctly.
Here is my code for Matrix Determinant:
public static double determinant(double[,]array){
double det=0;
double total = 0;
double[,] tempArr = new double[array.GetLength(0) - 1, array.GetLength(1) - 1];
if(array.GetLength(0)==2)
{
det = array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0];
}
else {
for (int i = 0; i <1; i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
if (j % 2 != 0) array[i, j] = array[i, j] * -1;
tempArr= fillNewArr(array, i, j);
det+=determinant(tempArr);
total =total + (det * array[i, j]);
}
}
}
return det;
}
and about fillNewArr method it's just a method to trim the array, method is as follow:
p
ublic static double[,] fillNewArr(double[,] originalArr, int row, int col)
{
double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];
for (int i = 0, newRow = 0; i < originalArr.GetLength(0); i++)
{
if (i == row)
continue;
for (int j = 0, newCol=0; j < originalArr.GetLength(1); j++)
{
if ( j == col) continue;
tempArray[newRow, newCol] = originalArr[i, j];
newCol++;
}
newRow++;
}
return tempArray;
}
The method is working as it supposed to "I assume" but the final result is not computed in the right way, why would that be?!
4x4 Array Example:
{2 6 6 2}
{2 7 3 6}
{1 5 0 1}
{3 7 0 7}
Final result should be -168, while mine is 104!
This bit
if (j % 2 != 0) array[i, j] = array[i, j] * -1;
tempArr= fillNewArr(array, i, j);
det+=determinant(tempArr);
total =total + (det * array[i, j]);
uses a variable total that is never used again. It should probably be something like
double subdet = determinant(fillNewArr(array, i, j));
if (j % 2 != 0) subdet *= -1;
det += array[i, j] * subdet;
I was just asking if there is a simple way of doing this.
i.e. Replacing two consecutive cell with one cell having different value.
For ex: - if my array =[0,3,1,2,3,4], and i want to replace index 0,and 1 with the value 5
to become like this array=[5,1,2,3,4]
Can you guys suggest some simple way for doing this.
i do this code but there is something wrong:
int J = 0;
if (max != 1)
{
for (int iii = 0; iii < output.Length -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
temp = temp + 1;
output[J] = Convert.ToByte(temp);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
output[J] = output[iii + 1];
}
}
}
because when i want to check the 2 consecutive index ,i want to pass them to the anther 2 index
If you care about performance you want to do as little operations that can harm performance. Try this extension method:
public static int[] ReplaceConsecutiveCells(this int[] array, int startIndex, int replaceWith)
{
int[] targetArray = new int[array.Length - 1];
for (int i = 0; i < array.Length; i++)
{
if (i < startIndex)
{
targetArray[i] = array[i];
}
else if (i == startIndex)
{
targetArray[i] = replaceWith;
}
else if (i == startIndex + 1)
{
// no action
}
else
{
targetArray[i - 1] = array[i];
}
}
return targetArray;
}
Use it like this:
array = array.ReplaceConsecutiveCells(0, 5);
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
List<int> list = array.ToList();
list.RemoveRange(0,2);
list.Insert(0, 5);
array = list.ToArray();
Yet another variant
int[] array = new int[] { 0, 3, 1, 2, 3, 4 };
Array.Reverse(array);
Array.Resize(ref array, 5);
Array.Reverse(array);
array[0] = 5;
do
{
RNG_NXT =RNG +1;
for (int iii = 0; iii <Nold -1; iii++)
{
if ((output[iii] == imax) && (output[iii + 1] == jmax))
{
output[J] = Convert.ToByte(RNG_NXT);
J = J + 1;
iii = iii + 1;
}
else
{
output[J] = output[iii];
J = J + 1;
}
}
RNG++;
}
while( RNG < RNG_MAX) ;
Hi i'm using the levenshtein algorithm to calculate the difference between two strings, using the below code. It currently provides the total number of changes which need to be made to get from 'answer' to 'target', but i'd like to split these up into the types of errors being made. So classifying an error as a deletion, substitution or insertion.
I've tried adding a simple count but i'm new at this and don't really understand how the code works so not sure how to go about it.
static class LevenshteinDistance
{
/// <summary>
/// Compute the distance between two strings.
/// </summary>
public static int Compute(string s, string t)
{
int n = s.Length;
int m = t.Length;
int[,] d = new int[n + 1, m + 1];
// Step 1
if (n == 0)
{
return m;
}
if (m == 0)
{
return n;
}
// Step 2
for (int i = 0; i <= n; d[i, 0] = i++)
{
}
for (int j = 0; j <= m; d[0, j] = j++)
{
}
// Step 3
for (int i = 1; i <= n; i++)
{
//Step 4
for (int j = 1; j <= m; j++)
{
// Step 5
int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
// Step 6
d[i, j] = Math.Min(
Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
}
Thanks in advance.