Determine the winner on a 3x3 TicTacToe game - c#

I have to find the winner of a 3x3 TicTacToe game player vs player. Firsty, I have to user input N (number of moves) and then N moves like (1 2) (0 1) etc. each on new line, X has the first move, 0 second move and so on. First number from bracket is representing the row index and second number representing column index. The program needs to return the winner X or 0, or draw if there is not a winner.
For example for the following input:
7
1 1
2 1
2 0
0 2
1 0
1 2
0 0
The output is : X
I've tried this code, but nothing is shown in console. Any hint would be really apreciated.
using System;
​
namespace ConsoleApp20
{
public class Program
{
public static string Tictactoe(int[,] moves)
{
int[] rowsValues = new int[3];
int[] columnsValues = new int[3];
int diagonalSum = 0;
int antiDiagonalSum = 0;
const int c1 = 3;
bool isFirstPlayer = true;
for (int i = 0; i < c1; i++)
{
int rowIndex = moves[i, 0];
int columnIndex = moves[i, 1];
int value = isFirstPlayer ? 1 : -1;
​
if (rowIndex == columnIndex)
{
diagonalSum += value;
}
​
if (columnIndex == c1 - rowIndex - 1)
{
antiDiagonalSum += value;
}
​
rowsValues[rowIndex] += value;
columnsValues[columnIndex] += value;
if (Math.Abs(diagonalSum) == c1 ||
Math.Abs(antiDiagonalSum) == c1 ||
Math.Abs(rowsValues[rowIndex]) == c1 ||
Math.Abs(columnsValues[columnIndex]) == c1)
{
return isFirstPlayer ? "X" : "0";
}
​
isFirstPlayer = !isFirstPlayer;
}
​
return "Draw";
}
​
public static void Main()
{
Tictactoe(ReadValues());
}
​
public static int[,] ReadValues()
{
int n = Convert.ToInt32(Console.ReadLine());
int[,] movesArr = new int[n, 2];
for (int i = 0; i < n; i++)
{
string[] moves = Console.ReadLine().Split();
int a = int.Parse(moves[0]);
int b = int.Parse(moves[1]);
movesArr[i, 0] = a;
movesArr[i, 1] = b;
}
​
return movesArr;
}
}
}

Related

Simple console lotto game c# match arrays

I'm trying to make a simple lotto/bingo game in c#.
Trying to make something like this:
Game where user types in 10 numbers which gets stored to an array.
Then the game makes a "lotto card" which is a 2 dimensional array with random numbers, like this:
10 | 13 | 14 | 17 | 16
18 | 24 | 21 | 23 | 8
1 | 3 | 6 | 25 | 9
7 | 22 | 15 | 12 | 2
4 | 5 | 11 | 19 | 20
Now i want to compare the contents of both arrays. I cant seem to find a way to do this with both 1 and 2 dimensionall arrays? Right now i've only managed to check if one of the numbers match.
Have tried using Linq and enumerabl and different loops in a couple of ways but with no success.
I want the game to register bingo if i match the numbers horizontally, vertically and diagonally.
This is my code so far:
static void Main(string[] args)
{
// Greet and explain the rules
Console.WriteLine("Welcome to bingo!");
string input; // Variabel for input by user
int inputnmr; // Variabel for nmrinput by user
int low = 1;
int high = 25;
int[] userNmr = new int[7]; // Creates a new array for the player
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
for (int i = 0; i < userNmr.Length; i++)
{
Console.Write("Type in a number between {0} - {1}:", low, high);
input = Console.ReadLine();
inputnmr = int.Parse(input);
userNmr[i] = inputnmr;
}
//Prints your lotto numbers:
Console.Write("These are your numbers :");
foreach (int i in userNmr)
{
Console.Write(i);
Console.Write(", ");
}
//Asks if continue:
Console.WriteLine("Are you sure about your numbers?");
Console.WriteLine("Do you want a bingo card?");
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] lottoCard = new int[x, y];
//Create random
Random randomnmr = new Random();
//Prints the lotto cards x-axis
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" |------------------------|");
Console.Write(" | ");
//Prints the lotto card y-axis
for (int j = 0; j < 5; j++)
{
//Fills lotto card with random ints:
lottoCard[i, j] = randomnmr.Next(1, 26);
Console.Write(lottoCard[i, j] + " | ");
}
Console.WriteLine(" ");
}
Console.WriteLine(" |------------------------|");
// --- This is where im stuck ---
bool oneMatch = false;
while (oneMatch == false)
{
foreach (var numberA in userNmr)
{
foreach (var numberB in lottoCard)
{
if (numberA == numberB)
{
oneMatch = true;
}
}
}
}
if (oneMatch == true)
{
Console.WriteLine("BINGO!");
}
else
{
Console.WriteLine("No win . . .");
}
Things i've tried:
1:
bool equal = lottoCard.Rank == userNmr.Rank && Enumerable.Range(0, lottoCard.Rank).All(dimension => lottoCard.GetLength(dimension) == lottoCard.GetLength(dimension)) && lottoCard.Cast<double>().SequenceEqual(lottoCard.Cast<double>());
if (equal == true)
{
Console.WriteLine("Bingo");
}
else
{
Console.WriteLine("no win");
}
2:
bool IsContain(int[][] lottoCard, int[] userNmr)
{
foreach (int[] row in lottoCard)
{
int curlIndex = 0;
foreach (int item in row)
{
if (item == userNmr[curlIndex])
{
if (curlIndex == userNmr.Length - 1)
{
return true;
}
curlIndex++;
}
else
{
curlIndex = 0;
}
return false;
}
}
}
if (IsContain(lottoCard, userNmr))
{
Console.WriteLine("BINGO");
}
else
{
Console.WriteLine("No win");
}
Above does not work, would really appreciate some help!
Here's how I would have done it:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to Bingo!");
int[] userNmr = getUserInput();
int[,] bingoCard = genBingoCard();
Console.WriteLine();
Console.WriteLine("Your number selections are:");
Console.WriteLine(String.Join(", ", userNmr));
Console.WriteLine();
Console.WriteLine("Here is your Bingo Card!");
displayBingoCard(bingoCard);
bool bingo = checkForBingo(userNmr, bingoCard);
if (bingo)
{
Console.WriteLine("Congratulations! You had a Bingo!");
}
else
{
Console.WriteLine("Sorry, no Bingos. Better luck next time!");
}
Console.WriteLine();
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
public static int[] getUserInput()
{
int low = 1;
int high = 25;
string input;
int inputnmr;
int[] userNmr = new int[7];
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
bool valid;
for (int i = 0; i < userNmr.Length; i++)
{
valid = false;
while (!valid)
{
Console.WriteLine();
Console.WriteLine("User Selection #" + (i + 1));
Console.Write("Select a number between {0} - {1}: ", low, high);
input = Console.ReadLine();
if (int.TryParse(input, out inputnmr))
{
if (inputnmr >= low && inputnmr <= high)
{
if (!userNmr.Contains(inputnmr))
{
userNmr[i] = inputnmr;
valid = true;
}
else
{
Console.WriteLine("You already picked that number!");
}
}
else
{
Console.WriteLine("Number must be between {0} and {1}!", low, high);
}
}
else
{
Console.WriteLine("Invalid Number.");
}
}
}
return userNmr;
}
public static int[,] genBingoCard()
{
Random randomnmr = new Random();
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] bingoCard = new int[y, x];
List<int> numbers = Enumerable.Range(1, x * y).ToList();
numbers = numbers.OrderBy(z => randomnmr.Next()).ToList();
int counter = 0;
for (int r = 0; r < y; r++)
{
for (int c = 0; c < x; c++)
{
bingoCard[r, c] = numbers[counter++];
}
}
return bingoCard;
}
public static void displayBingoCard(int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
string line = "";
for (int c = 0; c < x; c++)
{
line = line + "+----";
}
line = line + "+";
Console.WriteLine(line);
for (int r = 0; r < y; r++)
{
Console.Write("|");
for (int c = 0; c < x; c++)
{
Console.Write(" " + bingoCard[r, c].ToString("00") + " |");
}
Console.WriteLine();
Console.WriteLine(line);
}
}
public static bool checkForBingo(int[] userNmr, int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
bool bingo;
// check each row
for (int r = 0; r < y; r++)
{
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Horizontal Bingo at Row: " + (r+1));
return true;
}
}
// check each column
for (int c = 0; c < x; c++)
{
bingo = true; // until proven otherwise
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Vertical Bingo at Column: " + (c+1));
return true;
}
}
// check diagonals
// top left to bottom right
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Left to Bottom Right.");
return true;
}
// top right to bottom left
bingo = true; // until proven otherwise
for (int c = (x-1); c >= 0 && bingo; c--)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Right to Bottom Left.");
return true;
}
// no bingos were found!
return false;
}
}

count number of 0 with floodfill algorithm

I wanted to count number of 0 and 1 from a 2d array with floodfill algorithm....But unfortunetly...it's showing the wrong result.
I have a matrix like this
0,1,1,0,1
1,0,1,1,0
1,0,1,1,0
1,0,1,1,0
1,0,1,1,0
It supposed to show number of 0 = 10 and 1 =15
but it showing number of 0 = 4 and 1 = 21
here is my code
int[][] input;
public static int[,] reult;
public static int count = 0,col,row;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path;
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
input = File.ReadLines(file.FileName)
.Skip(0)
.Select(l => l.Split(',')
.Select(n => int.Parse(n))
.ToArray())
.ToArray();
}
reult = JaggedToMultidimensional(input);
int p = reult.GetLength(0);
int q = reult.GetLength(1);
row = p-1;
col = q - 1;
int one = p * q;
int zero = apply(row, col);
label1.Text = "" + zero;
label2.Text = "" + (one - zero);
}
public T[,] JaggedToMultidimensional<T>(T[][] jaggedArray)
{
int rows = jaggedArray.Length;
int cols = jaggedArray.Max(subArray => subArray.Length);
T[,] array = new T[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i, j] = jaggedArray[i][j];
}
}
return array;
}
private static int apply(int x, int y)
{
int currentColor = getValueAt(x, y);
if (currentColor == 0)
{
visit(x, y);
count++;
if (x < row) apply(x + 1, y);
if(y<col) apply(x, y + 1);
if(x>0) apply(x - 1, y);
if (y>0) apply(x, y - 1);
}
return count;
}
private static int getValueAt(int x, int y)
{
if (x < 0 || y < 0 || x > row || y > col)
{
return -1;
}
else
{
return reult[x,y];
}
}
private static void visit(int x, int y)
{
reult[x,y] = 1;
}
int zero = apply(row, col);
In your flood fill algorithm, you are only going in four direction and cover the area which match your criteria. And fortunately [row,col] index has 0 and it count all four 0 from [row, col]. Now think what if apply(row,col) have 1 on that row, col index.
To get this thing right, you need to loop through whole matrix and call apply(i,j) where ever you find an array[i,j]==0
Change this line
int zero = apply(row, col);
to
int zero = 0;
for(int i=0; i<=row; i++)
{
for(int j=0; j<=col; j++)
{
if(array[i][j]==0)
{
count =0;
zero+= apply(row, col);
}
}
}
Hope this helps.
Given the requirements you should change the search criteria to search for 0's and 1's.
What you need to do is to search within the rectangle so the border of the rectangle is limit for searching.
i.e.
int[] count = {0,0};
private static int apply(int x, int y)
{
int currentColor = getValueAt(x, y);
if (currentColor != -1)
{
visit(x, y);
count[currentColor]++;
if (x < row) apply(x + 1, y);
if(y<col) apply(x, y + 1);
if(x>0) apply(x - 1, y);
if (y>0) apply(x, y - 1);
}
return count;
}
and then change your visit function to set the cell to -1 instead to avoid visiting it twice.
You can also use linq if you want (I actually prefer):
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadLines(fileDialog.FileName);
var splittedValues = lines.Where(l => !string.IsNullOrEmpty(l)).Select(l => l.Split(',')).SelectMany(l => l).ToList();
var valCount = splittedValues.GroupBy(s => s).Select(s => new { val = s.Key, count = s.Count() }).ToList();
}
It will give you following result:
[0] { val= "0", count=10} [1] { val= "1", count=15}

Implementing and using MinMax with four in row (connect4) game

I'm trying to implement the MinMax algorithm for four in a row (or connect4 or connect four) game.
I think I got the idea of it, it should build a tree of possible boards up to a certain depth, evaluate them and return their score, then we just take the max of those scores.
So, aiChooseCol() checks the score of every possible column by calling MinMax() and returns the column with the max score.
Now I wasn't sure, is this the right way to call MinMax()?
Is it right to check temp = Math.Max(temp, 1000);?
I still haven't made the heuristic function but this should at least recognize a winning column and choose it, but currently it just choose the first free column from the left... I can't figure out what am I doing wrong.
private int AiChooseCol()
{
int best = -1000;
int col=0;
for (int i = 0; i < m_Board.Cols; i++)
{
if (m_Board.CheckIfColHasRoom(i))
{
m_Board.FillSignInBoardAccordingToCol(i, m_Sign);
int t = MinMax(5, m_Board, board.GetOtherPlayerSign(m_Sign));
if (t > best)
{
best = t;
col = i;
}
m_Board.RemoveTopCoinFromCol(i);
}
}
return col;
}
private int MinMax(int Depth, board Board, char PlayerSign)
{
int temp=0;
if (Depth <= 0)
{
// return from heurisitic function
return temp;
}
char otherPlayerSign = board.GetOtherPlayerSign(PlayerSign);
char checkBoard = Board.CheckBoardForWin();
if (checkBoard == PlayerSign)
{
return 1000;
}
else if (checkBoard == otherPlayerSign)
{
return -1000;
}
else if (!Board.CheckIfBoardIsNotFull())
{
return 0; // tie
}
if (PlayerSign == m_Sign) // maximizing Player is myself
{
temp = -1000;
for (int i = 0; i < Board.Cols; i++)
{
if (Board.FillSignInBoardAccordingToCol(i, PlayerSign)) // so we don't open another branch in a full column
{
var v = MinMax(Depth - 1, Board, otherPlayerSign);
temp = Math.Max(temp, v);
Board.RemoveTopCoinFromCol(i);
}
}
}
else
{
temp = 1000;
for (int i = 0; i < Board.Cols; i++)
{
if (Board.FillSignInBoardAccordingToCol(i, PlayerSign)) // so we don't open another branch in a full column
{
var v = MinMax(Depth - 1, Board, otherPlayerSign);
temp = Math.Min(temp, v);
Board.RemoveTopCoinFromCol(i);
}
}
}
return temp;
}
Some notes:
FillSignInBoardAccordingToCol() returns a boolean if it was successful.
The board type has a char[,] array with the actual board and signs of the players.
This code is in the AI Player class.
So I decided to write my own MinMax Connect 4. I used the depth to determine the value of a win or loss so that a move that gets you closer to winning or blocking a loss will take precedence. I also decide that I will randomly pick the move if more than one has the same heuristic. Finally I stretched out the depth to 6 as that's how many moves are required to find possible win paths from the start.
private static void Main(string[] args)
{
var board = new Board(8,7);
var random = new Random();
while (true)
{
Console.WriteLine("Pick a column 1 -8");
int move;
if (!int.TryParse(Console.ReadLine(), out move) || move < 1 || move > 8)
{
Console.WriteLine("Must enter a number 1-8.");
continue;
}
if (!board.DropCoin(1, move-1))
{
Console.WriteLine("That column is full, pick another one");
continue;
}
if (board.Winner == 1)
{
Console.WriteLine(board);
Console.WriteLine("You win!");
break;
}
if (board.IsFull)
{
Console.WriteLine(board);
Console.WriteLine("Tie!");
break;
}
var moves = new List<Tuple<int, int>>();
for (int i = 0; i < board.Columns; i++)
{
if (!board.DropCoin(2, i))
continue;
moves.Add(Tuple.Create(i, MinMax(6, board, false)));
board.RemoveTopCoin(i);
}
int maxMoveScore = moves.Max(t => t.Item2);
var bestMoves = moves.Where(t => t.Item2 == maxMoveScore).ToList();
board.DropCoin(2, bestMoves[random.Next(0,bestMoves.Count)].Item1);
Console.WriteLine(board);
if (board.Winner == 2)
{
Console.WriteLine("You lost!");
break;
}
if (board.IsFull)
{
Console.WriteLine("Tie!");
break;
}
}
Console.WriteLine("DONE");
Console.ReadKey();
}
private static int MinMax(int depth, Board board, bool maximizingPlayer)
{
if (depth <= 0)
return 0;
var winner = board.Winner;
if (winner == 2)
return depth;
if (winner == 1)
return -depth;
if (board.IsFull)
return 0;
int bestValue = maximizingPlayer ? -1 : 1;
for (int i = 0; i < board.Columns; i++)
{
if (!board.DropCoin(maximizingPlayer ? 2 : 1, i))
continue;
int v = MinMax(depth - 1, board, !maximizingPlayer);
bestValue = maximizingPlayer ? Math.Max(bestValue, v) : Math.Min(bestValue, v);
board.RemoveTopCoin(i);
}
return bestValue;
}
public class Board
{
private readonly int?[,] _board;
private int? _winner;
private bool _changed;
public Board(int cols, int rows)
{
Columns = cols;
Rows = rows;
_board = new int?[cols, rows];
}
public int Columns { get; }
public int Rows { get; }
public bool ColumnFree(int column)
{
return !_board[column, 0].HasValue;
}
public bool DropCoin(int playerId, int column)
{
int row = 0;
while (row < Rows && !_board[column,row].HasValue)
{
row++;
}
if (row == 0)
return false;
_board[column, row - 1] = playerId;
_changed = true;
return true;
}
public bool RemoveTopCoin(int column)
{
int row = 0;
while (row < Rows && !_board[column, row].HasValue)
{
row++;
}
if (row == Rows)
return false;
_board[column, row] = null;
_changed = true;
return true;
}
public int? Winner
{
get
{
if (!_changed)
return _winner;
_changed = false;
for (int i = 0; i < Columns; i++)
{
for (int j = 0; j < Rows; j++)
{
if (!_board[i, j].HasValue)
continue;
bool horizontal = i + 3 < Columns;
bool vertical = j + 3 < Rows;
if (!horizontal && !vertical)
continue;
bool forwardDiagonal = horizontal && vertical;
bool backwardDiagonal = vertical && i - 3 >= 0;
for (int k = 1; k < 4; k++)
{
horizontal = horizontal && _board[i, j] == _board[i + k, j];
vertical = vertical && _board[i, j] == _board[i, j + k];
forwardDiagonal = forwardDiagonal && _board[i, j] == _board[i + k, j + k];
backwardDiagonal = backwardDiagonal && _board[i, j] == _board[i - k, j + k];
if (!horizontal && !vertical && !forwardDiagonal && !backwardDiagonal)
break;
}
if (horizontal || vertical || forwardDiagonal || backwardDiagonal)
{
_winner = _board[i, j];
return _winner;
}
}
}
_winner = null;
return _winner;
}
}
public bool IsFull
{
get
{
for (int i = 0; i < Columns; i++)
{
if (!_board[i, 0].HasValue)
return false;
}
return true;
}
}
public override string ToString()
{
var builder = new StringBuilder();
for (int j = 0; j < Rows; j++)
{
builder.Append('|');
for (int i = 0; i < Columns; i++)
{
builder.Append(_board[i, j].HasValue ? _board[i,j].Value.ToString() : " ").Append('|');
}
builder.AppendLine();
}
return builder.ToString();
}
}

Creating a Score Method for an Array

My goal is to create a score method for a simple game based in an array. The game consists of putting 'R's or 'B's in one of 11 positions in an array. Once the array is full, the score method will execute as follows:
Any single 'R' or 'B' is worth 0 points
Any pair of 'R's or 'B's is worth 4 points
Any triple of 'R's or 'B's is worth 6 points
... and so on.
I'm having trouble calculating the score and I feel like I am missing something obvious so I'm coming here. The code I have looks for pairs and adds 2 to the score, but I end up missing 2 points (since the first pair is worth 4 and each additional "pair" is worth another 2).
public int score(char color)
{
int score = 0;
for (int i = 0; i < gameBoard.Length - 1; i++)
{
if (gameBoard[i] == color && gameBoard[i + 1] == color)
score += 2;
else
score += 0;
}
return score;
}
Your problem can be solved by regular expressions.
public int CalculateScore(char color)
{
var boardStr = String.Join("", gameBoard);
return GetCharacterSequences(color, boardStr)
.Sum(str => str.Length * 2);
}
//Returns same character sequences of length more than two.
private IEnumerable<string> GetCharacterSequences(char color, string boardStr)
{
return Regex.Matches(boardStr, $#"({color})\1+").OfType<Match>()
.SelectMany(match => match.Groups.OfType<Group>())
.Select(#group => #group.Value)
.Where(str => str.Length > 1);
}
Idea of sum function: Each pair costs 4 points, each triple costs 6 points hence each single char costs 2 points.
GetCharacterSequences looks little bit complex but it makes CalculateScore method very simple.
Well you could create a boolean variable and use that to determine the number of points added.
Note: This code doesn't account for triple matches as you've mentioned in your question.
public int score(char color)
{
int score = 0;
bool firstMatch = true;
for (int i = 0; i < gameBoard.Length - 1; i++)
{
if (gameBoard[i] == color && gameBoard[i + 1] == color) {
if (firstMatch == true) {
score += 4;
firstMatch = false;
} else {
score += 2;
}
}
else
{
score += 0;
}
}
return score;
}
Here's another approach, based on a pair being 4 points, 3 being 6 points, and assuming 4 being 8 points and so forth (basically number of adjacent colors * 2 if there is at least a pair).
public int score(char color)
{
int adj = 0;
int score = 0;
for (int i = 0; i < gameBoard.Length; i++)
{
if (gameBoard[i] == color)
{
adj++;
}
else
{
if (adj > 1)
{
score += adj * 2;
}
adj = 0;
}
}
}
This code loops through the array, and keeps a count of the number of adjacent spots marked by the specified color. When it comes to an element of the array that is not the right color, it checks to see how many adjacent elements had the correct color.
If it's greater than 1, then it multiplies the number of adjacent elements by 2 and resets the adjacent elements counter to 0 and continues through the array.
Given an array of 'R', 'R', 'B', 'B', 'B', 'R', 'R', 'R', 'B', 'R', 'B', it produces a score of 10 for 'R' (4 + 6) and 6 for 'B' (6), as follows:
'R', 'R' = 4
'R', 'R', 'R' = 6
'R' = 0
'B', 'B', 'B' = 6
'B' = 0
Here is what i came up with
namespace TestApp1
{
class Program
{
static void Main(string[] args)
{
string[] test = GetValues();
string testView = String.Join(String.Empty, test);
string score = GetScore(test).ToString();
Console.WriteLine(testView);
Console.WriteLine(score);
Console.ReadLine();
}
public static int GetScore(string[] test)
{
int score = 0;
int occurence = 0;
string LastChar = string.Empty;
for (int i = 0; i < test.Length; i++)
{
if(LastChar == string.Empty)
{
LastChar = test[i];
occurence += 1;
continue;
}
if(LastChar == test[i])
{
occurence += 1;
if(i == test.Length - 1)
{
if (occurence > 1)
{
score += occurence * 2;
}
}
}
else
{
if(occurence > 1)
{
score += occurence * 2;
}
LastChar = test[i];
occurence = 1;
}
}
return score;
}
public static string[] GetValues()
{
List<string> values = new List<string>();
for (int i = 0; i < 12; i++)
{
var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 2);
values.Add(ticks == 1 ? "R" : "B");
System.Threading.Thread.Sleep(2);
}
return values.ToArray();
}
}
}
To calculate each score independently
namespace TestApp1
{
class Program
{
static void Main(string[] args)
{
string[] test = GetValues();
string testView = String.Join(String.Empty, test);
int rScore = 0;
int bScore = 0;
GetScore(test,out rScore, out bScore);
string score = "R: " + rScore.ToString() + " B: " + bScore.ToString();
Console.WriteLine(testView);
Console.WriteLine(score);
Console.ReadLine();
}
public static void GetScore(string[] test, out int rScore, out int bScore)
{
int occurence = 0;
string LastChar = string.Empty;
rScore = 0;
bScore = 0;
for (int i = 0; i < test.Length; i++)
{
if(LastChar == string.Empty)
{
LastChar = test[i];
occurence += 1;
continue;
}
if(LastChar == test[i])
{
occurence += 1;
if(i == test.Length - 1)
{
if (occurence > 1)
{
if(LastChar == "R")
{
rScore += occurence * 2;
}
else
{
bScore += occurence * 2;
}
}
}
}
else
{
if(occurence > 1)
{
if (LastChar == "R")
{
rScore += occurence * 2;
}
else
{
bScore += occurence * 2;
}
}
LastChar = test[i];
occurence = 1;
}
}
}
public static string[] GetValues()
{
List<string> values = new List<string>();
for (int i = 0; i < 12; i++)
{
var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 2);
values.Add(ticks == 1 ? "R" : "B");
System.Threading.Thread.Sleep(2);
}
return values.ToArray();
}
}
}

The knights tour for 8x8 infinite recurssion

here will be my code for famous Knights Tour for 8x8 deck. So, the main idea of my code is: we will choose from Turns our destination, check it with isPossible and then go recursevly to it, marked this cell to '1'. So, check every cell, and if we will be in 64's cell - return true.
But my code goes to infinite recurssion, and I can't debug it, any recommendation will be greatly appreciated.
class Class1
{
static void Main(string[] args)
{
int x = 0;
int y = 0;
Console.WriteLine("Enter X and press enter");
x = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter Y and press enter");
y = Int32.Parse(Console.ReadLine());
TurnVariation Turns = new TurnVariation();
EmptyBoard Board = new EmptyBoard();
if (TryPut.Put(Board, x, y, Turns, 1, false))
{
Console.WriteLine("МОЖНА!!!!");
}
else
{
Console.WriteLine("NET!!");
}
}
}
public class TryPut : EmptyBoard
{
public static bool Put(EmptyBoard Board, int x, int y, TurnVariation Turns, int count, bool flag)
{
int tempX = 0;
int tempY = 0;
if (count >= 64)
{
Console.WriteLine("yeab");
return true;
}
for (int i = 0; i <= 7; i++)
{
tempX = x + Turns.Turns[i,0];
tempY = y + Turns.Turns[i,1];
//Console.WriteLine(count);
if (IsPossible(Board, tempX, tempY))
{
Board.Array[tempX, tempY] = 1;
flag = Put(Board, tempX, tempY, Turns, count+1, flag);
if (flag)
{
break;
}
Board.Array[tempX, tempY] = 0;
}
}
if (flag)
return true;
else
return false;
}
public static bool IsPossible(EmptyBoard Board, int x, int y)
{
if ((x < 0) || (x > 7) || (y < 0) || (y > 7))
return false;
if (Board.Array[x, y] == 1)
return false;
return true;
}
}
public class TurnVariation
{
public int[,] Turns = new int[8, 2];
public TurnVariation()
{
Turns[0, 0] = -2; Turns[0, 1] = 1;
Turns[1,0] = -2; Turns[1,1] = -1;
Turns[2,0] = -1; Turns[2,1] = 2;
Turns[3,0] = 1; Turns[3,1] = 2;
Turns[4,0] = 2; Turns[4,1] = 1;
Turns[5,0] = 2; Turns[5,1] = -1;
Turns[6,0] = 1; Turns[6,1] = -2;
Turns[7,0] = -1; Turns[7,1] = -2;
}
}
public class EmptyBoard
{
public const int N = 8;
public int[,] Array = new int[N, N];
public EmptyBoard()
{
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
Array[i, j] = 0;
}
}
I think your problem is that your testing for count<64, but you never assign to count. You just pass (by value!) 'Count + 1' to the put method. You are probably thinking that this will bewritten back to the count variable. But that is not the case...
Do note that debugging is the first skill you need to learn!

Categories