I have an assignment for school and i got a bit stuck in the process.
The idea is to make a program in C# where you can visualize how the insertion sorting algorithm works and for that I'm using an array of buttons with random generated numbers.
It colours green for comparison and red for swapping.
Why do the buttons remain coloured?
public partial class Form1 : Form
{
Button[] but;
int[] A;
int nr_den = 0;
int s1 = 0;
int s2 = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
nr_den = Convert.ToInt16(textBox1.Text);
s1 = Convert.ToInt16(textBox2.Text);
s2= Convert.ToInt16(textBox3.Text);
A = new int[nr_den+1];
Random r = new Random();
for (int i = 1; i <= nr_den; i++)
{
A[i] = r.Next(s1, s2);
}
but = new Button[nr_den + 1];
for (int i = 1; i <= nr_den; i++)
{
but[i] = new Button();
but[i].Text = A[i].ToString();
but[i].Width = 40;
but[i].Height = 40;
flowLayoutPanel1.Controls.Add(but[i]);
}
}
public void exchange(int[] A, int m, int n)
{
string s;
int temp;
but[m].BackColor = Color.Red;
System.Threading.Thread.Sleep(400);
but[n].BackColor = Color.Pink;
System.Threading.Thread.Sleep(400);
temp = A[m];
s = but[m].Text;
A[m] = A[n];
but[m].Text = but[n].Text;
A[n] = temp;
but[n].Text = s;
but[m].Refresh();
but[n].Refresh();
}
public void sort(int[] A)
{
int i, j;
int N = A.Length;
for (j = 1; j < N; j++)
{
for (i = j; i > 0 && A[i] < A[i - 1]; i--)
{
but[i-1].BackColor = Color.Green;
System.Threading.Thread.Sleep(400);
but[i].BackColor = Color.GreenYellow;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
exchange(A, i, i - 1);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
for (int i=1;i<=nr_den;i++)
richTextBox1.Text += A[i]+ " ";
richTextBox1.Text += " \n";
sort(A);
}
private void button3_Click(object sender, EventArgs e)
{
flowLayoutPanel1.Controls.Clear();
}
}
form
restore color after completion
public void sort(int[] A)
{
int i, j;
int N = A.Length;
for (j = 1; j < N; j++)
{
for (i = j; i > 0 && A[i] < A[i - 1]; i--)
{
but[i - 1].BackColor = Color.Green;
System.Threading.Thread.Sleep(400);
but[i].BackColor = Color.GreenYellow;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
exchange(A, i, i - 1);
but[i-1].BackColor = SystemColors.Control;
but[i].BackColor = SystemColors.Control;
}
}
}
restore color during process
public void sort(int[] A)
{
int i, j;
int N = A.Length;
for (j = 1; j < N; j++)
{
for (i = j; i > 0 && A[i] < A[i - 1]; i--)
{
but[i - 1].BackColor = Color.Green;
System.Threading.Thread.Sleep(400);
but[i].BackColor = Color.GreenYellow;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
exchange(A, i, i - 1);
but[i-1].BackColor = SystemColors.Control;
but[i].BackColor = SystemColors.Control;
System.Threading.Thread.Sleep(400);
but[i].Refresh();
but[i - 1].Refresh();
}
}
}
Related
I have a problem. I need to count cells that I activate, they are yellow, but I dont know how i can do it. In geniral I need to select only maximum 15 cells, so i need to count them, but all my tries seems so far away. I tried to cteate a counter, but it doest work. Please, help.
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
//выделение только ячеек
// создаём массив
int[,] Array = new int[8, 10];
byte numbers = 1;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
Array[i, j] = numbers;
numbers++;
}
}
dataGridView1.RowCount = 8;
dataGridView1.ColumnCount = 10;
// программно записываем массив и задаём стиль ячеек
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
dataGridView1.Columns[j].Width = 30;
dataGridView1.Rows[i].Height = 30;
dataGridView1.Rows[i].Cells[j].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Rows[i].Cells[j].Style.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
dataGridView1.Rows[i].Cells[j].Value = Array[i, j].ToString();
}
}
}
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) // выделение ячеек
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (dataGridView1.SelectedCells[i].Style.BackColor == Color.Yellow)
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.White;
}
else
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.Yellow;
}
dataGridView1.CurrentCell = null;
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
byte _selected = 0;
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
counter(_selected);
}
}
public void counter(int count)
{
count++;enter code here
MessageBox.Show(count.ToString());
}
Here is how form look.
form
The name of the game is Keno and i try to create it. Maybe i have some mistakes, sorry.
Here's my spin on your code. In this snippet I am using int yellowed to keep track of how many cells are yellow. When a user clicks on a cell, the cell counter sets the yellow count. When the mouse button is up(dataGridView1_CellMouseUp), then only the appropriate number of cells are allowed to be made yellow.
using System.Drawing;
using System.Windows.Forms;
namespace DataGridView_47478857
{
public partial class Form1 : Form
{
DataGridView dataGridView1 = new DataGridView();
int yellowed = 0;
int maxYellowed = 15;
public Form1()
{
InitializeComponent();
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.CellMouseUp += dataGridView1_CellMouseUp;
dataGridView1.CellClick += dataGridView1_CellClick;
this.Controls.Add(dataGridView1);
dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
//выделение только ячеек
// создаём массив
int[,] Array = new int[8, 10];
byte numbers = 1;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
Array[i, j] = numbers;
numbers++;
}
}
dataGridView1.RowCount = 8;
dataGridView1.ColumnCount = 10;
// программно записываем массив и задаём стиль ячеек
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 10; j++)
{
dataGridView1.Columns[j].Width = 30;
dataGridView1.Rows[i].Height = 30;
dataGridView1.Rows[i].Cells[j].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Rows[i].Cells[j].Style.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Bold);
dataGridView1.Rows[i].Cells[j].Value = Array[i, j].ToString();
}
}
}
private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e) // выделение ячеек
{
for (int i = 0; i < dataGridView1.SelectedCells.Count; i++)
{
if (dataGridView1.SelectedCells[i].Style.BackColor == Color.Yellow)
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.White;
}
else
{
if (yellowed < maxYellowed)//only color code this cell if the yellow cell count has not been exceeded
{
dataGridView1.SelectedCells[i].Style.BackColor = Color.Yellow;
yellowed++;
}
}
}
dataGridView1.ClearSelection();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
yellowed = 0;
foreach (DataGridViewRow currentRow in dataGridView1.Rows)
{
foreach (DataGridViewCell currentCell in currentRow.Cells)
{
if (currentCell.Style.BackColor == Color.Yellow)
{
yellowed++;
}
}
}
}
}
}
You can use this link to count cell, but you can use another components or WPF to this game.
https://msdn.microsoft.com/en-us/library/x8x9zk5a(v=vs.85).aspx
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++)
{
}
}
I'm trying to create a basic weather app where you can enter readings for a city and it will display the average, lowest temperature and highest temperature.
I created a 2d array (intTemps) with 5 rows (citys) and 4 columns (4 readings). Whenever I add a temperature to the listbox, it always displays in the upper left. When I add another temperature, it displays the same temperature that was just displayed and the current temperature.
The code is based on an example my professor wrote, so I'm not sure why its not displaying right.
public partial class Form1 : Form
{
string[] strNames = { "Livonia",
"Redford" ,
"Novi" ,
"Westland",
"Northville" };
int[,] intTemps = new int[5, 4];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 4; i++)
{
cobNames.Items.Add(strNames[i]);
lstNames.Items.Add(strNames[i]);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (cobNames.SelectedIndex >= 0 && cobNames.SelectedIndex <= 4)
{
if (intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] == 0)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
else
{
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
result = MessageBox.Show("Do you want to change temps?", "Temps already exist!", buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
intTemps[cobNames.SelectedIndex, (int)nudTemp.Value - 1] = Int32.Parse(txtTemp.Text);
}
}
displayTemps();
}
else
{
MessageBox.Show("You must select a valid name!");
}
}
catch (FormatException)
{
MessageBox.Show("Temps must be integers");
}
}
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
}
for (int l = 0; l <= 4; l++)
{
strLine = " ";
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] == 0)
{
strLine += " ";
}
else
{
if (intTemps[l, c] == 120)
{
strLine += intTemps[l, c] + " ";
}
else
{
strLine += intTemps[l, c] + " ";
}
lstTemp.Items.Add(strLine);
}
}
}
}
}
I rewrite your displayTemps() procedure. This wil add to lstTemp all information you need:
private void displayTemps()
{
string strLine;
lstTemp.Items.Clear();
double[] dblAverages = new double[5];
int intNonBlank = 0;
for (int l = 0; l <= 4; l++)
{
intNonBlank = 0;
for (int c = 0; c <= 3; c++)
{
if (intTemps[l, c] != 0)
{
dblAverages[l] += intTemps[l, c];
intNonBlank++;
}
}
if (intNonBlank != 0)
{
dblAverages[l] /= intNonBlank;
}
int min_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Min();
int max_temp = System.Linq.Enumerable.Range(0, 4).
Select(i => intTemps[l, i]).Max();
lstTemp.Items.Add(
"Average temp for city "+ l +": " + dblAverages[l] + " " +
"Minimum " + min_temp + " " +
"Maximum " + max_temp);
}
}
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
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);
}