Counting Sort Implementation in C# - c#

I am implementing counting sort But some thing is wrong with my code
I am new in Programming Please help me to find an error.
I am implenting it step by step .
namespace ConsoleApplication1
{
class Program
{
public static int[] a = { 0,0,0,5,4,8,9,9,7,3, 3, 2, 1 };
public static void Sorting()
{
int j = 0, i = 0, smallestvalue = 0, largestvalue = 0, n = a.Length, lengthof_B = 0, temp = 0, anothersmallestvalue;
smallestvalue = largestvalue = a[0];
for (i = 0; i < n; i++)
{
if (smallestvalue > a[i])
{
smallestvalue = a[i];
}
else if (largestvalue < a[i])
{
largestvalue = a[i];
}
}
int x = anothersmallestvalue = smallestvalue;
lengthof_B = largestvalue - smallestvalue + 1;
int[] b = new int[lengthof_B];
for (i = 0; i < lengthof_B && smallestvalue <= largestvalue; i++)
{
for (j = 0; j < n; j++)
{
if (smallestvalue == a[j])
{
b[i] = b[i] + 1;
}
}
b[i] = temp + b[i];
temp = b[i];
smallestvalue++;
}
int[] c = new int[a.Length];
// I think error here
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j];
}
anothersmallestvalue++;
}
}
for (i = 0; i < c.Length; i++)
{
Console.WriteLine("c[i] : " + c[i]);
}
}
}
class Demo
{
static void Main(string[] args)
{
Program.Sorting();
Console.ReadLine();
}
}
}
Desired Output is
000123457899
But output of my program is
000120457809

This Is Your Code Here I found a mistake.
And your Code is too complex Please Go through your code Once more.
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j] -1 ;// Possible Mistake I think here
}
anothersmallestvalue++;
}
}
the very simple and stylish way is described and shown here.
en.wikipedia.org/wiki/Counting_sort#The_algorithm

Normal sorting your two loops should look like this
for (i = 0; i < lengthof_B - 1; i++)
{
for (j = i + 1; j < lengthof_B; j++)
{
}
}​

Related

MiniMax algorithm for 4 in a row

I'm trying to implement minimax algorithm, but it isn't working, the computer is just making moves randomly. Here is the method Minimax and ComputerLogic.
static int MiniMax(int[,] board, int depth, bool isMax)
{
int len = 0;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0) len++;
}
}
int best_score, score;
if (WinVariants(board, 1))
{
best_score = -10;
return best_score;
}
else if (WinVariants(board, 2))
{
best_score = 10;
return best_score;
}
else if (len == 0)
{
best_score = 0;
return best_score;
}
if (isMax)
{
best_score = -int.MaxValue;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0)
{
board[i, j] = 1;
score = MiniMax(board, depth + 1, false);
board[i, j] = 0;
best_score = Math.Max(best_score, score);
}
}
}
}
else
{
best_score = int.MaxValue;
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0)
{
board[i, j] = 2;
score = MiniMax(board, depth + 1, true);
board[i, j] = 0;
best_score = Math.Min(best_score, score);
}
}
}
}
return best_score;
}
static void ComputerLogic(int[,] grid, int VariantMove)
{
int[,] board = Copy(grid);
int bestScore = -int.MaxValue, score;
int len = 0;
Random rnd = new Random();
if (len <= 2)
{
while (true)
{
int x = rnd.Next(0, 7);
int y = rnd.Next(0, 7);
len++;
if (grid[x, y] == 0)
{
grid[x, y] = 1;
break;
}
}
}
else
{
while (true)
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (board[i, j] == 0)
{
board[i, j] = 1;
score = MiniMax(board, 0, false);
board[i, j] = 0;
if (score > bestScore)
{
bestScore = score;
grid[i, j] = 1;
break;
}
}
}
}
}
}
}
Too, i have method for Drawing my grid view 2d array.
If I choose the PC to go first, then it goes randomly. Otherwise, my mesh just isn't drawing.
I am guessing that I am not filling my main grid array correctly. Its copy is used for verification - board.
Can please help me with this problem?

how I can create a list of rows of double[,]

I have a double[,] and I want to create a list of each row of this double[,] and then create a list of this lists. I tried this code but get an exception out of range for: lQC[j].Add(new double());
double[,] disQC = new double[42, TTools.Depth.Count];
List<double> mQC = new List<double>();
mQC.Add(new double());
for (int j = 0; j < Example.Count; j++)
{
mQC.Add(100);
for (int i = 0; i < 42; i++)
{
if (XQuartz[i] < TPorosity.Neutron[j] && TPorosity.Neutron[j] < XCalcite[i] && YQuartz[i] < TPorosity.BulkDensity[j] && TPorosity.BulkDensity[j] < YCalcite[i])
{
mQC[i] = (YCalcite[i] - YQuartz[i]) / (XCalcite[i] - XQuartz[i]);
disQC[i, j] = (Math.Abs((TPorosity.BulkDensity[j] - YQuartz[i] - (mQC[i] * TPorosity.Neutron[j]) + (mQC[i] * XQuartz[i])) / Math.Sqrt(Math.Pow(mQC[i], 2) + 1)));
}
else
{
disQC[i, j] = 100;
}
List<List<double>> lQC = new List<List<double>>();
lQC.Add(new List<double>());
lQC[j].Add(new double());
lQC[j].Add(disQC[i, j]);
List<int> MinimumIndexQC = new List<int>();
MinimumIndexQC.Add(80000);
MinimumIndexQC[j] = lQC[j].IndexOf(lQC[j].Min());
}
}
Hope anyone can help me!
At every iteration of the for statement you create a new lQC. Move it before the for.
Here is the correct solution. Demo
public class Program {
public static void Main()
{
double[,] disQC = new double[5, 5];
List<List<double>> lQC = new List<List<double>>();
for (int j = 0; j < 5; j++) {
lQC.Add(new List<double>());
for (int i = 0; i < 5; i++) {
if (i % 2 == 0){
disQC[i, j] =i + 1 ;
}
else{
disQC[i, j] = j + 1;
}
lQC[j].Add(disQC[i, j]);
}
}
lQC.ForEach(l => { l.ForEach(t => Console.Write(t)); Console.WriteLine(""); });
}
}

Sorting string values without using any method/function

I trying to do sorting without use of any method or function
My Code :
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length; i++)
{
for (int j = i + 1; j < names.Length; j++)
{
for (int c = 0; c < names.Length; c++)
{
if (names[i][c] > names[j][c])
{
name = names[i];
names[i] = names[j];
names[j] = name;
}
}
}
Console.WriteLine(names[i]);
}
Please let me bring any solution for this code ?
In this code i am getting "Index was outside the bounds of the array" exception
int temp = 0;
int[] arr = new int[] { 20, 65, 98, 71, 64, 11, 2, 80, 5, 6, 100, 50, 13, 9, 80, 454 };
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[i] > arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.WriteLine(arr[i]);
}
Console.ReadKey();
You need to implement a sorting algorithm.
A very simple algorithm you can implement is the insertion sort:
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
for (int i = 0; i < names.Length; i++)
{
var x = names[i];
var j = i;
while(j > 0 && names[j-1].CompareTo(x) > 0)
{
names[j] = names[j-1];
j = j-1;
}
names[j] = x;
}
string[] names = { "Flag", "Next", "Cup", "Burg", "Yatch", "Nest" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length; i++)
{
int c = 0;
for (int j = 1; j < names.Length; j++)
{
if (j > i)
{
Sort:
if (names[i][c] != names[j][c])
{
if (names[i][c] > names[j][c])
{
name = names[i];
names[i] = names[j];
names[j] = name;
}
}
else
{
c = c + 1;
goto Sort;
}
}
}
Console.WriteLine(names[i]);
}
I you were conflicting in length of names array and comparing string. Below is the working solution . I have tested it it's working now
static void Main(string[] args)
{
int min=0;
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string name = string.Empty;
Console.WriteLine("Sorted Strings : ");
for (int i = 0; i < names.Length-1; i++)
{
for (int j = i + 1; j < names.Length;j++ )
{
if(names[i].Length < names[j].Length)
min =names[i].Length;
else
min =names[j].Length;
for(int k=0; k<min;k++)
{
if (names[i][k] > names[j][k])
{
name = names[i].ToString();
names[i] = names[j];
names[j] = name;
break;
}
else if(names[i][k] == names[j][k])
{
continue;
}
else
{
break;
}
}
}
}
for(int i= 0;i<names.Length;i++)
{
Console.WriteLine(names[i]);
Console.ReadLine();
}
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] {9,1,6,3,7,2,4};
int temp = 0;
for (int i = 0; i < arr.Length; i++)
{
for (int j = i + 1; j < arr.Length;j++)
{
if(arr[i]>arr[j])
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
Console.Write(arr[i]+",");
}
Console.ReadLine();
}
for (int i = 0; i < names.Length; i++)
{
string temp = "";
for (int j = i + 1; j < names.Length; j++)
{
if (names[i].CompareTo(names[j]) > 0)
{
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
public int compareing(string a, string b)
{
char[] one = a.ToLower().ToCharArray();
char[] two = b.ToLower().ToCharArray();
int ret = 0;
for (int i = 0; i < one.Length; i++)
{
for (int j = 0; j < two.Length; j++)
{
Loop:
int val = 0;
int val2 = 0;
string c = one[i].ToString();
char[] c1 = c.ToCharArray();
byte[] b1 = ASCIIEncoding.ASCII.GetBytes(c1);
string A = two[j].ToString();
char[] a1 = A.ToCharArray();
byte[] d1 = ASCIIEncoding.ASCII.GetBytes(a1);
int sec = d1[0];
int fir = b1[0];
if (fir > sec)
{
return ret = 1;
break;
}
else
{
if (fir == sec)
{
j = j + 1;
i = i + 1;
if (one.Length == i)
{
return ret = 0;
}
goto Loop;
}
else
{
return 0;
}
}
}
}
return ret;
}
public void stringcomparision(List<string> li)
{
string temp = "";
for(int i=0;i<li.Count;i++)
{
for(int j=i+1;j<li.Count;j++)
{
if(compareing(li[i],li[j])>0)
{
//if grater than it throw 1 else -1
temp = li[j];
li[j] = li[i];
li[i] = temp;
}
}
}
Console.WriteLine(li);
}
for (int i = 0; i < names.Length - 1; i++)
{
string temp = string.Empty;
for (int j = i + 1; j < names.Length; j++)
{
if (names[i][0] > names[j][0])
{
temp = names[i].ToString();
names[i] = names[j].ToString();
names[j] = temp;
}
}
}
for (int i = 0; i < names.Length - 1; i++)
{
int l = 0;
if (names[i][0] == names[i + 1][0])
{
string temp = string.Empty;
if (names[i].Length > names[i + 1].Length)
l = names[i + 1].Length;
else
l = names[i].Length;
for (int j = 0; j < l; j++)
{
if (names[i][j] != names[i + 1][j])
{
if (names[i][j] > names[i + 1][j])
{
temp = names[i].ToString();
names[i] = names[i + 1].ToString();
names[i + 1] = temp;
}
break;
}
}
}
}
foreach (var item in names)
{
Console.WriteLine(item.ToString());
}
string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };
string temp = "";
int tempX = 0, tempY = 0;
int tempX1 = 0, tempY1 = 0;
for (int i = 0; i<names.Length; i++)
{
for (int j = i+1; j<names.Length; j++)
{
if (((string)names[i])[0] > ((string)names[j])[0])
{
temp=(string)names[i];
names[i]=names[j];
names[j]=temp;
}
else if (((string)names[i])[0] == ((string)names[j])[0])
{
tempX=0; tempY=0;
tempX1=names[i].Length;
tempY1=names[j].Length;
while (tempX1 > 0 && tempY1 >0)
{
if (((string)names[i])[tempX] !=((string)names[j])[tempY])
{
if (((string)names[i])[tempX]>((string)names[j])[tempY])
{
temp=(string)names[i];
names[i]=names[j];
names[j]=temp;
break;
}
}
tempX++;
tempY++;
tempX1--;
tempY1--;
}
}
}
}
You can do it using bubble sort:
Assume you have the array of names called name
The tempName is just to not change the original array (You can use the original array instead)
void sortStudentsAlphabetically()
{
int nameIndex;
string temp;
string[] tempName = name;
bool swapped = true;
for(int i = 0; i < name.Length-1 && swapped ; i++)
{
swapped = false;
for(int j = 0; j < name.Length-1; j++)
{
nameIndex = 0;
recheck:
if (name[j][nameIndex]> name[j+1][nameIndex])
{
temp = tempName[j];
tempName[j] = tempName[j+1];
tempName[j+1] = temp;
swapped = true;
}
if (name[j][nameIndex] == name[j + 1][nameIndex])
{
nameIndex++;
goto recheck;
}
}
}
foreach(string x in tempName)
{
Console.WriteLine(x);
}
}
User Below code :
int[] arrayList = new int[] {2,9,4,3,5,1,7};
int temp = 0;
for (int i = 0; i <= arrayList.Length-1; i++)
{
for (int j = i+1; j < arrayList.Length; j++)
{
if (arrayList[i] > arrayList[j])
{
temp = arrayList[i];
arrayList[i] = arrayList[j];
arrayList[j] = temp;
}
}
}
Console.WriteLine("Sorting array in ascending order : ");
foreach (var item in arrayList)
{
Console.WriteLine(item);
}
Console.ReadLine();
Output:
Sorting array in ascending order : 1 2 3 4 5 7 9

Training ff nn using backpropagation

I have encountered some difficulties while training my nn. When I use, lets say, 10 training sets, at the end of training procces neural network is trained just for the last two. I'm entering same values that I have used to train network and I am getting wrong results save for the last two. It seems to me that new nn memory suppresses older memory. I'm using 64 input neurons, 42 neurons in hidden layer and one output neuron. Sigmoid function is used for activating neurons. Training inputs and expected outputs are in 0 to 1 range. Does anyone have any clue what might be causing the problem?
Neuron b = new Neuron();
Fft f = new Fft();
float e = 2.71828f;
float eta = 0.05f;
float alpha = 0.05f;
float[] saw = new float[42];
float[] dh = new float[42];
float error = 0;
float dto = 0;
Random broj = new Random();
TextReader br = new StreamReader("d:/trening.txt");
TextReader ir = new StreamReader("d:\\input.txt");
float NextFloat(Random rng, float min, float max)
{
return (float)(min + (rng.NextDouble() * (max - min)));
}
public void load()//load memory
{
int i, j;
byte[] floatBytes;
BinaryReader br = new BinaryReader(File.Open("d:/memorija.txt", FileMode.Open));
for (j = 0; j <= 41; j++)
{
for (i = 0; i <= 64; i++)
{
floatBytes = br.ReadBytes(4);
b.w12[i][j] = BitConverter.ToSingle(floatBytes, 0);
}
}
for (j = 0; j <= 1; j++)
{
for (i = 0; i <= 41; i++)
{
floatBytes = br.ReadBytes(4);
b.w23[i][j] = BitConverter.ToSingle(floatBytes, 0);
}
}
br.Close();
}
public void trening()//Get training inputs and expected outputs
{ //Calls process methode
int i, n,ct=0;
using (TextReader tr = new StreamReader("d:/trening.txt"))
{
do
{
ct++;
} while (tr.ReadLine() != null);
tr.Close();
}
for (n = 0; n < (ct-1)/65; n++)
{
for (i = 1; i <= 65; i++)
b.input[i] = Convert.ToSingle(br.ReadLine());
process(b.input[65]);
target.Text = ((b.input[65]).ToString());
}
}
public void process(double t)//Trains nn using backpropagation
{
error = 0;
do
{
int i, j, k;
BinaryWriter bw = new BinaryWriter(File.Open("d:\\memorija.txt", FileMode.Create));
i = k = j = 0;
for (j = 1; j <= 41; j++)
{
b.ulaz2[j] = b.w12[0][j];
for (i = 1; i <= 64; i++)
{
b.ulaz2[j] += b.input[i] * b.w12[i][j];
} b.izlaz2[j] = (float)(1.0 / (1.0 + Math.Pow(e, -b.ulaz2[j])));
if (b.izlaz2[j] < 0)
MessageBox.Show(b.izlaz2[j].ToString());
}
for (k = 1; k <= 1; k++)
{
b.ulaz3 = b.w23[0][k];
for (j = 1; j <= 41; j++)
{
b.ulaz3 += b.izlaz2[j] * b.w23[j][k];
} b.izlaz = (float)(1.0 / (1.0 + Math.Pow(e, -b.ulaz3)));
error += (float)(0.5 * (t - b.izlaz) * (t - b.izlaz));
dto = (float)(t - b.izlaz) * b.izlaz * (1 - b.izlaz);
}
for (j = 1; j <= 41; j++)
{
saw[j] = 0;
for (k = 1; k <= 1; k++)
{
saw[j] += dto * b.izlaz2[j];
} dh[j] = saw[j] * b.izlaz2[j] * (1 - b.izlaz2[j]);
}
for (j = 1; j <= 41; j++)
{
b.w12d[0][j] = eta * dh[j] + alpha * b.w12d[0][j];
b.w12[0][j] += b.w12d[0][j];
for (i = 1; i <= 64; i++)
{
b.w12d[i][j] = eta * b.input[i] * dh[j] + alpha * b.w12d[i][j];
b.w12[i][j] += b.w12d[i][j];
}
}
for (k = 1; k <= 1; k++)
{
b.w23d[0][k] = eta * dto + alpha * b.w23d[0][k];
b.w23[0][k] += b.w23d[0][k];
for (j = 1; j <= 41; j++)
{
b.w23d[j][k] = eta * b.izlaz2[j] * dto + alpha * b.w23d[j][k];
b.w23[j][k] += b.w23d[j][k];
}
}
for (j = 0; j <= 41; j++)
{
for (i = 0; i <= 64; i++)
bw.Write(b.w12[i][j]);
}
for (j = 0; j <= 1; j++)
{
for (i = 0; i <= 41; i++)
bw.Write(b.w23[i][j]);
}
bw.Close();
izlazb.Text = Convert.ToString(b.izlaz);
errorl.Text = Convert.ToString(Math.Abs(b.izlaz - b.input[64]));
} while (Math.Abs(b.izlaz - t) > 0.03);
}
public void test()//This methode gets input values and gives output based on previous training
{
int i = 0, j = 0, k = 0;
for (i = 1; i < 65; i++)
b.input[i] = (float)Convert.ToDouble(ir.ReadLine());
for (j = 1; j <= 41; j++)
{
b.ulaz2[j] = b.w12[0][j];
for (i = 1; i <= 64; i++)
{
b.ulaz2[j] += b.input[i] * b.w12[i][j];
} b.izlaz2[j] = (float)(1.0 / (1.0 + Math.Pow(e, -b.ulaz2[j])));
}
for (k = 1; k <= 1; k++)
{
b.ulaz3 = b.w23[0][k];
for (j = 1; j <= 41; j++)
{
b.ulaz3 += b.izlaz2[j] * b.w23[j][k];
} b.izlaz = (float)(1.0 / (1.0 + Math.Pow(e, -b.ulaz3)));
} izlazb.Text = Convert.ToString(b.izlaz);
target.Text = "/";
errorl.Text = "/";
}
public void reset()//Resets memory
{
BinaryWriter fw = new BinaryWriter(File.Open("d:\\memorija.txt", FileMode.Create));
int i = 0;
int j = 0;
Random broj = new Random();
for (j = 0; j <= 41; j++)
{
for (i = 0; i <= 64; i++)
{
b.w12[i][j] = 0;
b.w12[i][j] = 2 * (NextFloat(broj, -0.5f, 0.5f));
fw.Write(b.w12[i][j]);
}
}
for (j = 0; j <= 1; j++)
{
for (i = 0; i <= 41; i++)
{
b.w23[i][j] = 0;
b.w23[i][j] = 2 * (NextFloat(broj, -0.5f, 0.5f));
fw.Write(b.w23[i][j]);
}
}
fw.Close();
}
}
}
And neuron class
public class Neuron
{
public float[][] w12 = new float[65][];//(65, 42);
public float[][] w12d = new float[65][];//(65, 42);
public float[][] w23 = new float[42][];//(42,2);
public float[][] w23d = new float[42][];//(42, 2);
public float[] ulaz2 = new float[42];
public float[] izlaz2 = new float[42];
public float ulaz3;
public float[] input =new float[66];
public static float[] ioutput;
public float izlaz;
public void arrayInit()
{
int i, j;
for (i = 0; i <=64; i++)
{
w12[i] = new float[42];
w12d[i] = new float[42];
}
for (i = 0; i <42; i++)
{
w23[i] = new float[2];
w23d[i] = new float[2];
}
for (j = 0; j < 42; j++)
for (i = 0; i <=64; i++)
{
w12[i][j] = 0;
w12d[i][j] = 0;
}
for (j = 0; j < 2; j++)
for (i = 0; i < 42; i++)
{
w23[i][j] = 0;
w23d[i][j] = 0;
}
}
}
I found out what the problem was. I didn't mix training arrays, I was introducing one array to nn until it was trained for it, instead of introducing all arrays in cyclic manner. I hope this will be useful for someone.

How to find the longest palindrome in a given string? [duplicate]

This question already has answers here:
Write a function that returns the longest palindrome in a given string
(23 answers)
Closed 9 years ago.
Possible Duplicate:
Write a function that returns the longest palindrome in a given string
I know how to do this in O(n^2). But it seems like there exist a better solution.
I've found this, and there is a link to O(n) answer, but it's written in Haskell and not clear for me.
It would be great to get an answer in c# or similar.
I've found clear explanation of the solution here. Thanks to Justin for this link.
There you can find Python and Java implementations of the algorithm (C++ implementation contains errors).
And here is C# implementation that is just a translation of those algorithms.
public static int LongestPalindrome(string seq)
{
int Longest = 0;
List<int> l = new List<int>();
int i = 0;
int palLen = 0;
int s = 0;
int e = 0;
while (i<seq.Length)
{
if (i > palLen && seq[i-palLen-1] == seq[i])
{
palLen += 2;
i += 1;
continue;
}
l.Add(palLen);
Longest = Math.Max(Longest, palLen);
s = l.Count - 2;
e = s - palLen;
bool found = false;
for (int j = s; j > e; j--)
{
int d = j - e - 1;
if (l[j] == d)
{
palLen = d;
found = true;
break;
}
l.Add(Math.Min(d, l[j]));
}
if (!found)
{
palLen = 1;
i += 1;
}
}
l.Add(palLen);
Longest = Math.Max(Longest, palLen);
return Longest;
}
And this is its java version:
public static int LongestPalindrome(String seq) {
int Longest = 0;
List<Integer> l = new ArrayList<Integer>();
int i = 0;
int palLen = 0;
int s = 0;
int e = 0;
while (i < seq.length()) {
if (i > palLen && seq.charAt(i - palLen - 1) == seq.charAt(i)) {
palLen += 2;
i += 1;
continue;
}
l.add(palLen);
Longest = Math.max(Longest, palLen);
s = l.size() - 2;
e = s - palLen;
boolean found = false;
for (int j = s; j > e; j--) {
int d = j - e - 1;
if (l.get(j) == d) {
palLen = d;
found = true;
break;
}
l.add(Math.min(d, l.get(j)));
}
if (!found) {
palLen = 1;
i += 1;
}
}
l.add(palLen);
Longest = Math.max(Longest, palLen);
return Longest;
}
public static string GetMaxPalindromeString(string testingString)
{
int stringLength = testingString.Length;
int maxPalindromeStringLength = 0;
int maxPalindromeStringStartIndex = 0;
for (int i = 0; i < stringLength; i++)
{
int currentCharIndex = i;
for (int lastCharIndex = stringLength - 1; lastCharIndex > currentCharIndex; lastCharIndex--)
{
if (lastCharIndex - currentCharIndex + 1 < maxPalindromeStringLength)
{
break;
}
bool isPalindrome = true;
if (testingString[currentCharIndex] != testingString[lastCharIndex])
{
continue;
}
else
{
int matchedCharIndexFromEnd = lastCharIndex - 1;
for (int nextCharIndex = currentCharIndex + 1; nextCharIndex < matchedCharIndexFromEnd; nextCharIndex++)
{
if (testingString[nextCharIndex] != testingString[matchedCharIndexFromEnd])
{
isPalindrome = false;
break;
}
matchedCharIndexFromEnd--;
}
}
if (isPalindrome)
{
if (lastCharIndex + 1 - currentCharIndex > maxPalindromeStringLength)
{
maxPalindromeStringStartIndex = currentCharIndex;
maxPalindromeStringLength = lastCharIndex + 1 - currentCharIndex;
}
break;
}
}
}
if(maxPalindromeStringLength>0)
{
return testingString.Substring(maxPalindromeStringStartIndex, maxPalindromeStringLength);
}
return null;
}
C#
First I search for even length palindromes. Then I search for odd length palindromes. When it finds a palindrome, it determines the length and sets the max length accordingly. The average case complexity for this is linear.
protected static int LongestPalindrome(string str)
{
int i = 0;
int j = 1;
int oldJ = 1;
int intMax = 1;
int intCount = 0;
if (str.Length == 0) return 0;
if (str.Length == 1) return 1;
int[] intDistance = new int[2] {0,1};
for( int k = 0; k < intDistance.Length; k++ ){
j = 1 + intDistance[k];
oldJ = j;
intCount = 0;
i = 0;
while (j < str.Length)
{
if (str[i].Equals(str[j]))
{
oldJ = j;
intCount = 2 + intDistance[k];
i--;
j++;
while (i >= 0 && j < str.Length)
{
if (str[i].Equals(str[j]))
{
intCount += 2;
i--;
j++;
continue;
}
else
{
break;
}
}
intMax = getMax(intMax, intCount);
j = oldJ + 1;
i = j - 1 - intDistance[k];
}
else
{
i++;
j++;
}
}
}
return intMax;
}
protected static int getMax(int a, int b)
{
if (a > b) return a; return b;
}
Recently I wrote following code during interview...
public string FindMaxLengthPalindrome(string s)
{
string maxLengthPalindrome = "";
if (s == null) return s;
int len = s.Length;
for(int i = 0; i < len; i++)
{
for (int j = 0; j < len - i; j++)
{
bool found = true;
for (int k = j; k < (len - j) / 2; k++)
{
if (s[k] != s[len - (k - j + 1)])
{
found = false;
break;
}
}
if (found)
{
if (len - j > maxLengthPalindrome.Length)
maxLengthPalindrome = s.Substring(j, len - j);
}
if(maxLengthPalindrome.Length >= (len - (i + j)))
break;
}
if (maxLengthPalindrome.Length >= (len - i))
break;
}
return maxLengthPalindrome;
}
I got this question when i took an interview.
I found out when i was back home, unfortunately.
public static string GetMaxPalindromeString(string testingString)
{
int stringLength = testingString.Length;
int maxPalindromeStringLength = 0;
int maxPalindromeStringStartIndex = 0;
for (int i = 0; i < testingString.Length; i++)
{
int currentCharIndex = i;
for (int lastCharIndex = stringLength - 1; lastCharIndex > currentCharIndex; lastCharIndex--)
{
bool isPalindrome = true;
if (testingString[currentCharIndex] != testingString[lastCharIndex])
{
continue;
}
for (int nextCharIndex = currentCharIndex + 1; nextCharIndex < lastCharIndex / 2; nextCharIndex++)
{
if (testingString[nextCharIndex] != testingString[lastCharIndex - 1])
{
isPalindrome = false;
break;
}
}
if (isPalindrome)
{
if (lastCharIndex + 1 - currentCharIndex > maxPalindromeStringLength)
{
maxPalindromeStringStartIndex = currentCharIndex;
maxPalindromeStringLength = lastCharIndex + 1 - currentCharIndex;
}
}
break;
}
}
return testingString.Substring(maxPalindromeStringStartIndex, maxPalindromeStringLength);
}

Categories