I am trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). The subroutine 'ComputerMove();' does not execute for some reason, why is that? I am yet to finish but it is the ComputerMove subroutine that I am confused with. Apologies in advance if I am missing something obvious.
(Edit: There is no error message, just a blank console)
using System;
using System.Threading;
namespace THE_NIM
{
class Program
{
static char[,] Board = new char[7, 12];
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static bool GameStatus = false;
static string firstMove;
static void Introduction()
{
Console.WriteLine("\t\t\t\t\t" + underline + "Welcome to NIM!\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(underline + "The rules are as follows:\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Thread.Sleep(1500);
}
static void PrintBoard()
{
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i <= 6; i++)
{
Console.Write(" ");
for (int j = 0; j <= 11; j++)
{
Console.Write(Board[i, j]);
}
Console.WriteLine();
Console.WriteLine();
}
}
static void WhoGoesFirst()
{
string[] PossibleChoices = { "Computer", "You" };
Random WhoGoesFirst = new Random();
int WGFIndex = WhoGoesFirst.Next(0, 2);
firstMove = PossibleChoices[WGFIndex];
Console.WriteLine("Randomly selecting who goes first...");
Thread.Sleep(1000);
Console.WriteLine("{0} will go first!\n", firstMove);
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
switch (PlayerStackSelection)
{
case(1):
PlayerStackSelection = 0;
break;
case (2):
PlayerStackSelection = 2;
break;
case (3):
PlayerStackSelection = 4;
break;
case (4):
PlayerStackSelection = 6;
break;
case (5):
PlayerStackSelection = 8;
break;
case (6):
PlayerStackSelection = 10;
break;
}
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == ' ')
{
spaces += 1;
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + PlayerRemovedSelection); i++)
{
Board[i, PlayerStackSelection] = ' ';
}
}
PrintBoard();
CheckIfBoardEmpty();
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 7);
int PreChangeStack = CompStackSelection;
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 7);
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
while (spaces == 7)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
CompStackSelection = CompStack.Next(1, 7);
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if ((nearestBlock + CompRemovedSelection) !< 8)
{
while ((nearestBlock + CompRemovedSelection) !< 8)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + CompRemovedSelection); i++)
{
Board[i, CompStackSelection] = ' ';
}
}
Console.WriteLine("Computer is making its move... ");
Thread.Sleep(1000);
Console.WriteLine("Computer has decided to remove {0} blocks from stack number {1}.\n", CompRemovedSelection, PreChangeStack);
Thread.Sleep(1000);
PrintBoard();
CheckIfBoardEmpty();
}
static void CheckIfBoardEmpty()
{
bool keepGoing = false;
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (Board[i,j] == '█')
{
GameStatus = false;
keepGoing = true;
break;
}
}
}
if (keepGoing != true)
{
Console.Write("BOARD EMPTY");
GameStatus = true;
}
}
static void Main(string[] args)
{
Introduction();
WhoGoesFirst();
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (j % 2 == 0)
{
Board[i, j] = '█';
}
else
{
Board[i, j] = ' ';
}
}
}
if (firstMove == "You")
{
while (GameStatus == false)
{
PlayerMove();
ComputerMove();
}
}
else
{
while (GameStatus == false)
{
ComputerMove();
PlayerMove();
}
}
}
}
}
Related
I make this little Escape Room game where the player needs to collect a key for getting out of the room. How can I make the Key disappear whenever the player steps on it? This is my code so far. I know I haven't used any methods because I haven't learned it in university so far.. So it would be great if anyone has a simple solution or help for me. Thanks in advance! <3
static void Main(string[] args)
{
ConsoleKeyInfo consoleKey;
int XPositionCursor = 5;
int YPositionCursor = 5;
int MapWidth = 20;
int MapHeight = 20;
char Wall = '█';
bool GameOver = true;
char Key = '#';
char Character = 'H';
int[,] MapGenerationArray = new int[MapWidth, MapHeight];
Random RandomKeyCoordinate = new Random();
Random RandomDoorCoordinate = new Random();
#region Instructions
Console.WriteLine("Wähle eine Breite für dein Spielfeld:");
string MapWidthString = Console.ReadLine();
MapWidth = int.Parse(MapWidthString);
Console.Clear();
Console.WriteLine("Wähle eine Höhe für dein Spielfeld:");
string MapHeightString = Console.ReadLine();
MapHeight = int.Parse(MapHeightString);
Console.Clear();
Console.WriteLine($"Dein Spielfeld wird {MapWidth} x {MapHeight} groß sein!");
Console.ReadLine();
#endregion
Vector2 KeyCoordinate = new Vector2();
KeyCoordinate.X = RandomKeyCoordinate.Next(1, MapWidth - 1);
KeyCoordinate.Y = RandomKeyCoordinate.Next(1, MapHeight - 1);
Vector2 DoorCoordinate1 = new Vector2();
DoorCoordinate1.X = RandomDoorCoordinate.Next(0, MapWidth);
DoorCoordinate1.Y = RandomDoorCoordinate.Next(0, 0);
bool PlayerIsOnKeyPosition = XPositionCursor == KeyCoordinate.X && YPositionCursor == KeyCoordinate.Y;
bool PlayerCarryingKey = false;
do
{
#region Map
Console.Clear();
for (int i = 0; i < MapWidth; i++)
{
Console.SetCursorPosition(i, 0);
Console.Write(Wall);
}
for (int i = 0; i < MapWidth; i++)
{
Console.SetCursorPosition(i, MapHeight);
Console.Write(Wall);
}
for (int i = 0; i < MapHeight; i++)
{
Console.SetCursorPosition(0, i);
Console.Write(Wall);
}
for (int i = 0; i < MapHeight; i++)
{
Console.SetCursorPosition(MapWidth, i);
Console.Write(Wall);
}
#endregion
Console.SetCursorPosition(XPositionCursor, YPositionCursor);
Console.CursorVisible = false;
Console.Beep(200, 100);
Console.Write(Character);
if (PlayerIsOnKeyPosition)
{
PlayerCarryingKey = true;
}
if (PlayerCarryingKey == true)
{
Console.SetCursorPosition((int)DoorCoordinate1.X, (int)DoorCoordinate1.Y);
Console.Write(' ');
}
else
{
Console.SetCursorPosition((int)KeyCoordinate.X, (int)KeyCoordinate.Y);
Console.Write(Key);
Console.SetCursorPosition((int)DoorCoordinate1.X, (int)DoorCoordinate1.Y);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(Wall);
Console.ResetColor();
}
#region CharacterMovement
consoleKey = Console.ReadKey(true);
Console.Clear();
switch (consoleKey.Key)
{
case ConsoleKey.UpArrow:
YPositionCursor--;
break;
case ConsoleKey.DownArrow:
YPositionCursor++;
break;
case ConsoleKey.LeftArrow:
XPositionCursor--;
break;
case ConsoleKey.RightArrow:
XPositionCursor++;
break;
}
if (YPositionCursor < 1) { YPositionCursor = 1; }
if (XPositionCursor < 1) { XPositionCursor = 1; }
if (YPositionCursor >= MapHeight - 1) { YPositionCursor = MapHeight - 1; };
if (XPositionCursor >= MapWidth - 1) { XPositionCursor = MapWidth - 1; };
#endregion
} while (GameOver == true);
}
}
As #doctorlove wrote, you are calculating whether player has a key before your main loop (do/while).
But you should do this inside main loop, every time player changes his position.
Replace line if (PlayerIsOnKeyPosition) with this if (XPositionCursor == KeyCoordinate.X && YPositionCursor == KeyCoordinate.Y).
P.S. Good idea is to use methods (functions) to split code into smaller chunks :)
I keep on receiving this CS0136 error and I'm unsure why?
using System;
namespace Lab2_1
{
class Program
{
static void Main(string[] args)
{
Action<string> cw = Console.WriteLine;
int[] numbers = new int[10];
int currentIndex = 0;
bool repeat = true;
do
{
cw("Please enter an interger: ");
string line = Console.ReadLine();
if (line == "exit")
{
repeat = false;
}
else
{
try
{
int number = int.Parse(line);
cw("The number you entered was: " + number);
numbers[currentIndex] = number;
currentIndex++;
}
catch (FormatException)
{
cw("That wasn't a number!");
}
}
} while (repeat);
Console.WriteLine("Press any key to exit.");
{
while (repeat) ;
for (int i = 0; i < currentIndex; i++)
{
Console.WriteLine(numbers[i]);
}
currentIndex++;
if (currentIndex == numbers.Length)
{
int expandedNumberOfCells = currentIndex + 10;
}
int expandedNumberOfCells = currentIndex + 10;
int[] expandedNumbers = new int[expandedNumberOfCells];
for (int i = 0; i < currentIndex; i++)
{
expandedNumbers[i] = numbers[i];
}
numbers = expandedNumbers;
}
}
}
}
From this page you can see what error CS0136 is.
You could not declare expandedNumberOfCells repeatedly, you can slightly modify your code:
int expandedNumberOfCells = currentIndex + 10;
int[] expandedNumbers = new int[expandedNumberOfCells];
if (currentIndex == numbers.Length)
{
expandedNumberOfCells = currentIndex + 10;
}
for (int i = 0; i < currentIndex; i++)
{
expandedNumbers[i] = numbers[i];
}
numbers = expandedNumbers;
I am new at programming and I'm trying to understand why the methods call inside a switch statement is not working. Basically I have a main menu and a submenu. Whem I press the Animal submenu , the switch statement is meant to call the methods for a CRUD (insert new, visualize by Id, update, etc) but none of these options are working. Is the method call/structure correct?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace menu_clinica_veterinaria
{
class Program
{
public static int id = 1;
enum animalHeader { id, name, client_name, type_animal };
enum clientHeader { id, name, client_surname, adrress };
static void Main(string[] args)
{
string[,] animal = new string[20, 4];
string[,] client = new string[20, 6];
do { MenuOptions(animal); } while (true);
}
static void MenuOptions(string[,] animal)
{
int userChoice;
do
{
Console.Clear();
Console.WriteLine("\nChoose one of the following options:\n");
Console.WriteLine("[ 1 ] Animals");
Console.WriteLine("[ 2 ] Clients");
Console.WriteLine("[ 0 ] Quit application\n");
} while (!int.TryParse(Console.ReadLine(), out userChoice) || userChoice < 0 || userChoice > 2);
Console.Clear();
switch (userChoice)
{
case 1:
menuAnimal(animal);
break;
case 2:
//menuClient(client);
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("Try again!!");
break;
}
}
static void menuAnimal(string[,] animal)
{
int optAnimal;
while (true)
{
do
{
Console.Clear();
Console.WriteLine("\nInsert one of the following options:\n");
Console.WriteLine("[ 1 ] Insert animal");
Console.WriteLine("[ 2 ] See animal");
Console.WriteLine("[ 3 ] Alter animal");
Console.WriteLine("[ 4 ] Erase animal");
Console.WriteLine("[ 5 ] List animals");
Console.WriteLine("[ 0 ] Return to main menu\n");
} while (!int.TryParse(Console.ReadLine(), out optAnimal) || optAnimal < 0 || optAnimal > 5);
Console.Clear();
bool goBack = false;
switch (optAnimal)
{
case 1:
insertData(animal);
break;
case 2:
visualizeByid(animal);
break;
case 3:
updateById(animal);
break;
case 4:
deleteByid(animal);
break;
case 5:
listData(animal);
break;
case 0:
goBack = true;
break;
}
if (goBack) return;
}
}
static void mainMenu()
{
Console.Clear();
Console.ReadKey();
}
static void menuReturn(string[,] animal)
{
Console.Clear();
do { menuAnimal(animal); } while (true);
}
static int generateId()
{
return id++;
}
static int getInsertIndex(string[,] matrix)
{
for (int j = 0; j < matrix.GetLength(0) - 1; j++)
{
if (string.IsNullOrEmpty(matrix[j, 0])) return j;
}
return -1;
}
static void insertData(string[,] matrix)
{
int id = generateId();
int n = getInsertIndex(matrix);
matrix[n, 0] = Convert.ToString(id);
for (int j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[n, j] = Console.ReadLine();
} while (String.IsNullOrEmpty(matrix[n, j]));
}
}
static int searchId(string[,] matrix)
{
int choosenId, index = -1;
do
{
Console.Write("Insert ID to continue: ");
} while (!int.TryParse(Console.ReadLine(), out choosenId));
for (int i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
}
}
return index;
}
static void visualizeByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"{matrix[i, j]}\t");
}
Console.WriteLine();
}
}
else { Console.WriteLine("Wrong Id"); }
}
static void updateById(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[i, j] = Console.ReadLine();
}
Console.WriteLine();
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void deleteByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = null;
}
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void listData(string[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"\t{matrix[i, j]}\t");
}
Console.WriteLine("\n\t");
}
}
}
}
It's a nifty little program for what it is.
However, you can't see an animal because:
searchId
for (var i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
// Though it's not the problem you could break here
// you could also just return from here
break;
}
}
Also, you'll need to Console.ReadKey() somewhere as your menu refreshes and overwrites the see animal routine.
menuAnimal
visualizeByid(animal);
// if you don't do something like this as the menu refreshes the animal away
Console.ReadKey();
The only other thing I'd suggest is to use lists and well-typed classes, instead of multidimensional arrays of strings; they are easier to work with, and you can use Linq.
Update
In regards to comments, given this:
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
You could do something like this:
static void updateById<T>(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {GetHeader<T>(j)}: ");
...
Usage:
updateById<animalHeader>(animal);
Basically this is some generics to reuse the updateById method and using your HeaderType.
Your program working Fine. You are using Console.Clear(). It will clear the screen which is displayed previously on the screen. Remove Console.Clear() in the program or Add Console.ReadKey() immediately after Switch block. I think it will work fine.
I am building an ascii version of TicTacToe as a class asigment and I ran into a problem.The cursor doverwrites the board and the signs.
while (pressed == false)
{
ConsoleKeyInfo cki;
cki = Console.ReadKey();
switch (cki.Key)
{
case ConsoleKey.RightArrow:
if(sides+1>Console.WindowWidth)
break;
if(sides+1==17||sides+1==8)
sides+=2;
else
sides += 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.LeftArrow:
if (sides - 1 < 0)
break;
if (sides -1 == 17 || sides -1 == 8)
sides -= 2;
else
sides -= 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.DownArrow:
if (ver + 1 > Console.WindowHeight)
break;
if (ver+1==8||ver+1==17)
ver += 2;
else
ver += 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.UpArrow:
if (ver - 1 < 0 )
break;
if (ver - 1 == 8 || ver - 1 == 17)
ver-=2;
else
ver -= 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.X:
case ConsoleKey.O:
br.PutSign(ver,sides,ch);
pressed = true;
break;
default:
break;
}
}
}
I fixed the problme that the cursor overwrites the board But I still cant find a way to protect the sings(the X and the O)
Thats the board class for refernce:
public char[,] board = new char[27, 27];
public Board()
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (i==8||i==17)
board[i, j] = '_';
if (j==8||j==17)
board[i, j] = '|';
}
}
}
public void PrintB()
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
Console.Write(board[i, j]);
}
Console.WriteLine("");
}
}
public void PutSign(int row, int col, char ch)
{
board[row, col] = ch;
}
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);
}