Sequence of marching chars in 2 strings - c#

I have to write searching algorithm, For example I have to compare str="giorgi" to str2="grigol". I'm trying to find longest matching sequence of chars, so that the order of chars is the same and string which I should get is "grg"... with this c# code I'm getting "grig".
int k=0;
string s="";
string str = "giorgi";
string str2 = "grigol";
for(int i=0;i<str.Length;i++)
{
for (int j = k; j < str2.Length; j++)
{
if (str[i] == str2[j])
{
s += str2[k];
k++;
goto endofloop;
}
}
endofloop:;
}
Console.WriteLine(s);

The solution:
using System;
class GFG
{
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
static int lcs( char[] X, char[] Y, int m, int n )
{
int [,]L = new int[m+1,n+1];
/* Following steps build L[m+1][n+1]
in bottom up fashion. Note
that L[i][j] contains length of
LCS of X[0..i-1] and Y[0..j-1] */
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i, j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i, j] = L[i - 1, j - 1] + 1;
else
L[i, j] = GFG.max(L[i - 1, j], L[i, j - 1]);
}
}
return L[m, n];
}
static int max(int a, int b)
{
return (a > b)? a : b;
}
}
And now the program to test it:
public static void Main()
{
String s1 = "giorgi";
String s2 = "grigol";
char[] X=s1.ToCharArray();
char[] Y=s2.ToCharArray();
int m = X.Length;
int n = Y.Length;
Console.Write("Length of LCS is" + " " +lcs( X, Y, m, n ) );
}
}

Related

Simple spell checker using Levenshtein distance

I have to implement a simple spell checker. Basically I have to user input an incorrect sentence or a word, then a number N, and then N correct words each on new line. The program has to output "incorrect word: suggestion". If there is no suggestions available it should output "incorrect word: no suggestions" and if all the words from sentence are correct it should display "Correct text!". The typos can be:
Misspeled word.
Swapped letters.
Extra letter.
Missing letter.
To do this I implemented Levensthein minumim distance algorithm, which calculates the minimum number of modifications that a string has to take to be transformed into another string. All the test cases are fine but I want to reduce the cyclomatic complexity of the main method from 27 to below 26. Any suggestion would be helpful. For the example:
Thsi is an texzt fr tet
5
This
an
text
for
test
It displays:
Thsi: This
an: no suggestions
texzt: text
fr: for
tet: text test
using System;
using System.Collections.Generic;
namespace MisspelledWords
{
class Program
{
static void Main(string[] args)
{
string sentence = Console.ReadLine();
sentence = sentence.ToLower();
int numWords = int.Parse(Console.ReadLine());
const int doi = 2;
const int doi2 = 3;
int index = 0;
int index1 = 0;
string[] correctWords = new string[numWords];
for (int i = 0; i < numWords; i++)
{
correctWords[i] = Console.ReadLine();
}
foreach (string word in sentence.Split(' '))
{
index++;
int minDistance = int.MaxValue;
string closestWord = "";
foreach (string correctWord in correctWords)
{
int distance = GetLevenshteinDistance(word, correctWord);
if (distance < minDistance)
{
minDistance = distance;
closestWord = correctWord;
}
}
Message(minDistance, closestWord, word, index, ref index1, correctWords);
if (index1 != 0)
{
return;
}
}
static void Message(int minDistance, string closestWord, string word, int index, ref int index1, string[] correctWords)
{
if (minDistance >= doi)
{
// Print the misspelled word followed by "no suggestions"
Console.WriteLine(word + ": (no suggestion)");
}
else if (minDistance < doi && closestWord != word || minDistance >= doi2)
{
// Find all correct words that have the same minimum distance
List<string> suggestions = new List<string>();
foreach (string correctWord in correctWords)
{
int distance = GetLevenshteinDistance(word, correctWord);
if (distance == minDistance)
{
suggestions.Add(correctWord);
}
}
// Print the misspelled word followed by the suggestions
Console.Write(word + ": ");
Console.WriteLine(string.Join(" ", suggestions));
}
else if (minDistance == 0 && index > 1)
{
Console.WriteLine("Text corect!");
index1++;
}
}
static int Min(int value1, int value2, int value3)
{
return Math.Min(Math.Min(value1, value2), value3);
}
static int GetLevenshteinDistance(string word1, string word2)
{
int[,] distance = new int[word1.Length + 1, word2.Length + 1];
InitializeDistanceMatrix(distance, word1, word2);
CalculateLevenshteinDistance(distance, word1, word2);
return distance[word1.Length, word2.Length];
}
static void InitializeDistanceMatrix(int[,] distance, string word1, string word2)
{
for (int i = 0; i <= word1.Length; i++)
{
for (int j = 0; j <= word2.Length; j++)
{
if (i == 0)
{
distance[i, j] = j;
}
else if (j == 0)
{
distance[i, j] = i;
}
}
}
}
static void CalculateLevenshteinDistance(int[,] distance, string word1, string word2)
{
for (int i = 0; i <= word1.Length; i++)
{
for (int j = 0; j <= word2.Length; j++)
{
CLD(i, j, distance, word1, word2);
}
}
}
static void CLD(int i, int j, int[,] distance, string word1, string word2)
{
const int v = 2;
if (i <= 0 || j <= 0)
{
return;
}
distance[i, j] = Min(
distance[i - 1, j] + 1,
distance[i, j - 1] + 1,
distance[i - 1, j - 1] + (word1[i - 1] == word2[j - 1] ? 0 : 1));
// Check if swapping the characters at positions i and j results in a new minimum distance
if (i <= 1 || j <= 1 || word1[i - 1] != word2[j - v] || word1[i - v] != word2[j - 1])
{
return;
}
distance[i, j] = Math.Min(distance[i, j], distance[i - v, j - v] + 1);
}
Console.ReadLine();
}
}
}

longest common subsequence in c#

I want to allow users to input their own characters to find the lowest common subsequence, this code is mostly a skeleton of somebody else's work- and the characters used are AGGTAB and GXTXYAB which is GTAB however I want users to implement their own characters
code for longest common subsequence:
class GFG
{
public static void Main()
{
int m = X.Length;
int n = Y.Length;
Console.WriteLine("Write down characters for string A");
string A = Console.ReadLine();
Console.WriteLine("Write down characters for string B");
string B = Console.ReadLine();
int[,] L = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i, j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i, j] = L[i - 1, j - 1] + 1;
else
L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]);
}
}
}
}

Count Number of Changes Comparing two string 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 7 years ago.
Improve this question
I want to find out Number of changes comparing two string.
Example:
String 1:
I hope to do something good from this chance.I think my Test form will
help me in ODI. Scoring runs in international cricket, regardless of
the format, gives a player confidence.
string 2:
"I hope to do something good this chance. I think my Testing form will
help me in ODI Format. Scoring runs in latest international cricket,
regardless of the format, gives a playing confidence."
Expected Output: 5.(ignoring space & newline)
Changes are:
from(delete from string 2),
Testing(modified in string 2),
Format(extra addition in string 2),
latest(extra addition in string 2),
playing(modified in string 2).
Have any algorithm for count the number of changes?
You problem is quite similar to comparing two files.. Difference is In file comparison files are compared by comparing text in a single line. In your case it white space would be a separator instead of Newline.
Typically this is accomplished by finding the Longest Common Subsequence. Here is a related document which explains it: https://nanohub.org/infrastructure/rappture/export/2719/trunk/gui/src/diff.pdf
For finding LCS:
public static int GetLCS(string str1, string str2)
{
int[,] table;
return GetLCSInternal(str1, str2, out table);
}
private static int GetLCSInternal(string str1, string str2, out int[,] matrix)
{
matrix = null;
if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))
{
return 0;
}
int[,] table = new int[str1.Length + 1, str2.Length + 1];
for (int i = 0; i < table.GetLength(0); i++)
{
table[i, 0] = 0;
}
for(int j= 0;j<table.GetLength(1); j++)
{
table[0,j] = 0;
}
for (int i = 1; i < table.GetLength(0); i++)
{
for (int j = 1; j < table.GetLength(1); j++)
{
if (str1[i-1] == str2[j-1])
table[i, j] = table[i - 1, j - 1] + 1;
else
{
if (table[i, j - 1] > table[i - 1, j])
table[i, j] = table[i, j - 1];
else
table[i, j] = table[i - 1, j];
}
}
}
matrix = table;
return table[str1.Length, str2.Length];
}
//Reading Out All LCS sorted in lexicographic order
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace LambdaPractice
{
class Program
{
static int[,] c;
static int max(int a, int b)
{
return (a > b) ? a : b;
}
static int LCS(string s1, string s2)
{
for (int i = 1; i <= s1.Length; i++)
c[i,0] = 0;
for (int i = 1; i <= s2.Length; i++)
c[0, i] = 0;
for (int i=1;i<=s1.Length;i++)
for (int j = 1; j <= s2.Length; j++)
{
if (s1[i-1] == s2[j-1])
c[i, j] = c[i - 1, j - 1] + 1;
else
{
c[i, j] = max(c[i - 1, j], c[i, j - 1]);
}
}
return c[s1.Length, s2.Length];
}
/* Prints one LCS
static string BackTrack(string s1, string s2, int i, int j)
{
if (i == 0 || j == 0)
return "";
if (s1[i - 1] == s2[j - 1])
return BackTrack(s1, s2, i - 1, j - 1) + s1[i - 1];
else if (c[i - 1, j] > c[i, j - 1])
return BackTrack(s1, s2, i - 1, j);
else
return BackTrack(s1, s2, i, j - 1);
}*/
static SortedSet<string> backtrack(string s1, string s2, int i, int j)
{
if (i == 0 || j == 0)
return new SortedSet<string>(){""} ;
else if (s1[i - 1] == s2[j - 1])
{
SortedSet<string> temp = new SortedSet<string>();
SortedSet<string> holder = backtrack(s1, s2, i - 1, j - 1);
if (holder.Count == 0)
{
temp.Add(s1[i - 1]);
}
foreach (string str in holder)
temp.Add(str + s1[i - 1]);
return temp;
}
else
{
SortedSet<string> Result = new SortedSet<string>() ;
if (c[i - 1, j] >= c[i, j - 1])
{
SortedSet<string> holder = backtrack(s1, s2, i - 1, j);
foreach (string s in holder)
Result.Add(s);
}
if (c[i, j - 1] >= c[i - 1, j])
{
SortedSet<string> holder = backtrack(s1, s2, i, j - 1);
foreach (string s in holder)
Result.Add(s);
}
return Result;
}
}
static void Main(string[] args)
{
string s1, s2;
s1 = Console.ReadLine();
s2 = Console.ReadLine();
c = new int[s1.Length+1, s2.Length+1];
LCS(s1, s2);
// Console.WriteLine(BackTrack(s1, s2, s1.Length, s2.Length));
// Console.WriteLine(s1.Length);
SortedSet<string> st = backtrack(s1, s2, s1.Length, s2.Length);
foreach (string str in st)
Console.WriteLine(str);
GC.Collect();
Console.ReadLine();
}
}
}
could you check this might be useful somehow, I would say you'll use a lot of control statements (if/else or switch) for result sets.
You can do it relatively easy, if you you consider a string as modified if it is starting with another string:
void Main()
{
var a = "I hope to do something good from this chance.I think my Test form will help me in ODI.Scoring runs in international cricket, regardless of the format, gives a player confidence.";
var b = "I hope to do something good this chance. I think my Testing form will help me in ODI Format. Scoring runs in latest international cricket, regardless of the format, gives a playing confidence.";
var d = new Difference(a,b);
Console.WriteLine("Number of differences: {0}", d.Count);
foreach (var diff in d.Differences)
{
Console.WriteLine("Different: {0}", diff);
}
}
class Difference
{
string a;
string b;
List<string> notInA;
List<string> notInB;
public int Count
{
get { return notInA.Count + notInB.Count; }
}
public IEnumerable<string> Differences
{
get { return notInA.Concat(notInB); }
}
public Difference(string a, string b)
{
this.a = a;
this.b = b;
var itemsA = Split(a);
var itemsB = Split(b);
var changedPairs =
from x in itemsA
from y in itemsB
where (x.StartsWith(y) || y.StartsWith(x)) && y != x
select new { x, y };
var softChanged = changedPairs.SelectMany(p => new[] {p.x, p.y}).Distinct().ToList();
notInA = itemsA.Except(itemsB).Except(softChanged).ToList();
notInB = itemsB.Except(itemsA).Except(softChanged).ToList();
}
IEnumerable<string> Split(string x)
{
return x.Split(new[] { " ", ".", ","}, StringSplitOptions.RemoveEmptyEntries);
}
}
Output:
Number of differences: 5
Different: from
Different: player
Different: Format
Different: latest
Different: playing

What am I doing wrong in this C# mergesort algorithm?

For a school assignment, I have to implement mergesort.
I've used this code to do the trick:
static int[] MergeSort(int[] C)
{
int left = 0;
int right = C.Length;
int middle = (left + right) / 2;
int[] A, B;
A = new int[middle];
B = new int[middle];
if (C.Length == 0 || C.Length == 1)
{
return C;
}
else
{
for (int i = left; i < middle; i++)
{
A[i] = C[i];
B[i] = C[middle + i];
}
MergeSort(A);
MergeSort(B);
return Merge(A, B, C);
}
}
static int[] Merge(int[] A, int[] B, int[] C)
{
int i, j, k;
i = j = k = 0;
int n = A.Length;
int m = B.Length;
int c = C.Length;
int middle = C.Length / 2;
while (i < n && j < m)
{
if (A[i] < B[j])
{
C[k] = A[i];
i++;
}
else
{
C[k] = B[j];
j++;
}
k++;
if (i == n)
{
for (int b = i; b < B.Length; b++)
{
C[middle + b] = B[b];
}
}
else
{
for (int a = i; a < A.Length; a++)
{
C[middle + a] = A[a];
}
}
}
return C;
}
It does not work for a lot of different rows though. I've already debugged and checked if there was something wrong with constraints, but I can't seem to find the problem.
Thanks in advance!
The first thing I spot is how you split the array into two:
A = new int[middle];
B = new int[middle];
If the length is not even, you will be leaving out the last item. You should have:
A = new int[middle];
B = new int[right - middle];
Then you would use separate loops for them, as they can be different in length:
for (int i = left; i < middle; i++) {
A[i - left] = C[i];
}
for (int i = middle; i < right; i++) {
B[i - middle] = C[i];
}
In addition to Guffa answer, you should edit the code of the Merge method like this:
while (i < n && j < m)
{
if (A[i] < B[j])
{
C[k] = A[i];
i++;
}
else
{
C[k] = B[j];
j++;
}
k++;
}
if (i == n)
{
for (int b = j; b < B.Length; b++)
{
C[k++] = B[b];
}
}
else
{
for (int a = i; a < A.Length; a++)
{
C[k++] = A[a];
}
}
While loop block should end right after k++ and in first for loop you should initialize b with j instead of i. Also, watch out for the index of the next element of the C array, it is k, not necessarily middle + a or b.

Insertion Sort on an array of strings in C#

If I have an array of strings, such as
string[] names = {"John Doe", "Doe John", "Another Name", "Name Another"};
How do I sort this array, using insertion sort?
Wikipedia has some examples: https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = value;
}
}
and
static void InsertSort<T>(IList<T> list) where T : IComparable<T>
{
int i, j;
for (i = 1; i < list.Count; i++)
{
T value = list[i];
j = i - 1;
while ((j >= 0) && (list[j].CompareTo(value) > 0))
{
list[j + 1] = list[j];
j--;
}
list[j + 1] = value;
}
}
but it doesn't seem to work on my array of strings, unless I'm doing something wrong.
Would I not run
InsertSort(names); // like so?
Works fine for me:
class Program
{
static void Main()
{
string[] names = { "John Doe", "Doe John", "Another Name", "Name Another" };
InsertSort(names);
foreach (var item in names)
{
Console.WriteLine(item);
}
}
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j--;
}
array[j + 1] = value;
}
}
}
As expected it prints:
Another Name
Doe John
John Doe
Name Another
Here's my implementation:
public static void Swap<T>(ref T a, ref T b)
{
T t = a;
a = b;
b = t;
}
public static void InsertionSort<T>(this T[] a) where T : IComparable<T>
{
a.InsertionSort(Comparer<T>.Default.Compare);
}
public static void InsertionSort<T>(this T[] a, Comparison<T> c)
{
int n = a.Length;
for (int i = 1; i < n; ++i)
for (int k = i; k > 0 && c(a[k], a[k - 1]) < 0; --k)
Swap(ref a[k], ref a[k - 1]);
}
I do some class to do this:
public static class InsertionSort<T> where T : System.IComparable<T>
{
public static void Sort(ref T[] array)
{
T[] tmp = new T[array.Length];
tmp[0] = array[0];
for (int i = 1; i < array.Length; i++)
{
int place = FindProperPlace(tmp, array[i]);
ExpandArray(ref tmp, place);
tmp[place] = array[i];
}
array = tmp;
}
private static int FindProperPlace(T[] numbersArray, T number)
{
int j;
for (j = 0; j < numbersArray.Length; j++)
{
if (number.CompareTo(numbersArray[j]) < 0)
{
break;
}
}
return j;
}
private static void ExpandArray(ref T[] tmp, int place)
{
for (int i = tmp.Length - 1; i > place; i--)
{
tmp[i] = tmp[i - 1];
}
}
}

Categories

Resources