/// <summary> /// The minimax function considers all the possible paths of the game. /// </summary> /// <param name="Board">The game-board to be checked.</param> /// <param name="Depth">The depth of the game-board.</param> /// <param name="IsMaximizing">Whether to maximize or not.</param> /// <returns>The value of the board.</returns> private static int MiniMax(char[,] Board, int Depth, bool IsMaximizing) { // If the opponent has won the game. if (GridControll.CheckWinner(Board) == 10) { return(10); } else if (GridControll.CheckWinner(Board) == -10) { return(-10); } // If there is any possible moves left. if (GridControll.IsMovePossible(Board) == false) { return(0); } if (IsMaximizing) { int Best = -1000; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (Board[i, j] == '-') { char[,] TestBoard = Board.Clone() as char[, ]; // Try the move TestBoard[i, j] = 'O'; Best = Math.Max(Best, MiniMax(TestBoard, Depth + 1, false)); } } } return(Best); } else { int Best = 1000; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (Board[i, j] == '-') { char[,] TestBoard = Board.Clone() as char[, ]; // Try the move TestBoard[i, j] = 'X'; Best = Math.Min(Best, MiniMax(TestBoard, Depth + 1, true)); } } } return(Best); } }
public GameBoard() { //The first section is the section for the hangman, we'll make this 10x10 hangingArea.startX = hangingArea.startY = 0; hangingArea.stopX = hangingArea.stopY = 9; hangingArea.totalArea = new char[10, 10]; //The next section on top right is for the rules rulesArea.startX = 10; rulesArea.startY = 0; rulesArea.stopX = 19; rulesArea.stopY = 3; rulesArea.totalArea = new char[4, 10]; //Below the rules is the area for the game outcome. guessesArea.startX = 10; guessesArea.startY = 4; guessesArea.stopX = 19; guessesArea.stopY = 9; guessesArea.totalArea = new char[6, 10]; //Below all of that should be the phrase to be guessed. phraseArea.startX = 0; phraseArea.startY = 10; phraseArea.stopX = 19; phraseArea.stopY = 14; phraseArea.totalArea = new char[5, 20]; //At the bottom is the area for input inputArea.startX = 0; inputArea.startY = 15; inputArea.stopX = 19; inputArea.stopY = 19; inputArea.totalArea = new char[5, 20]; //The place where all input will be taken from inputStart.y = 16; inputStart.x = 2; //where in the hanging area the hangman starts hangmanStart.x = 4; hangmanStart.y = 3; phraseToGuess = new char[3, 18]; guessesMade = new char[4, 8]; hangman = new char[4, 3]; SetDefaults(); hangingArea.totalArea = (char[, ])defaultHangingArea.Clone(); rulesArea.totalArea = (char[, ])defaultRulesArea.Clone(); phraseArea.totalArea = (char[, ])defaultPhraseArea.Clone(); guessesArea.totalArea = (char[, ])defaultGuessesArea.Clone(); inputArea.totalArea = (char[, ])defaultInputArea.Clone(); }
public static int Solve() { var text = File.ReadAllLines(@"Input\Day11.txt"); _seats = new char[text[0].Length, text.Length]; for (int y = 0; y < text.Length; y++) { for (int x = 0; x < text[y].Length; x++) { _seats[x, y] = text[y][x]; } } var nextSeats = (char[, ])_seats.Clone(); _occupiedSeats = 0; var hasChanged = false; do { nextSeats = (char[, ])_seats.Clone(); hasChanged = false; for (int x = 0; x < _seats.GetLength(0); x++) { for (int y = 0; y < _seats.GetLength(1); y++) { if (_seats[x, y] != '.') { var occupied = GetNeighbors(x, y); if (_seats[x, y] == 'L' && occupied == 0) { nextSeats[x, y] = '#'; _occupiedSeats++; hasChanged = true; } else if (_seats[x, y] == '#' && occupied >= 5) { nextSeats[x, y] = 'L'; _occupiedSeats--; hasChanged = true; } } } } _seats = nextSeats; } while (hasChanged); return(_occupiedSeats); }
//public static void ChangeMap() //{ // for (int i = 0; i < Map.GetLength(0); i++) // { // for (int j = 0; j < Map.GetLength(1); j++) // { // if(Map[i,j] != MapBefore[i,j]) // { // } // } // } //} public static void PrintMap() { for (int i = 0; i < Map.GetLength(0); i++) { for (int j = 0; j < Map.GetLength(1); j++) { Console.Write(Map[i, j]); } Console.WriteLine(); } Console.SetCursorPosition(0, 0); MapBefore = (char[, ])Map.Clone(); }
public override string SolvePart1() { char[,] map = (char[, ])_map.Clone(); bool changed = true; while (changed) { map = AdvanceMap(map, out changed); } int result = CountOccupiedSeats(map); return(result.ToString()); }
private static IEnumerable <(char[, ] position, char direction)> GetNextPositionsByMovingOneRectangle(RectangleDimension rectangleDimension, char[,] grid) { var NextPositions = new List <(char[, ] position, char direction)>(); if (CanGoLeft(rectangleDimension, grid)) { var nextGrid = (char[, ])grid.Clone(); for (var y = rectangleDimension.YMin; y <= rectangleDimension.YMax; y++) { nextGrid[y, rectangleDimension.XMin - 1] = nextGrid[y, rectangleDimension.XMin]; nextGrid[y, rectangleDimension.XMax] = 'A'; NextPositions.Add((nextGrid, 'L')); } } if (CanGoRight(rectangleDimension, grid)) { var nextGrid = (char[, ])grid.Clone(); for (var y = rectangleDimension.YMin; y <= rectangleDimension.YMax; y++) { nextGrid[y, rectangleDimension.XMax + 1] = nextGrid[y, rectangleDimension.XMax]; nextGrid[y, rectangleDimension.XMin] = 'A'; NextPositions.Add((nextGrid, 'R')); } } if (CanGoUp(rectangleDimension, grid)) { var nextGrid = (char[, ])grid.Clone(); for (var x = rectangleDimension.XMin; x <= rectangleDimension.XMax; x++) { nextGrid[rectangleDimension.YMin - 1, x] = nextGrid[rectangleDimension.YMin, x]; nextGrid[rectangleDimension.YMax, x] = 'A'; NextPositions.Add((nextGrid, 'U')); } } if (CanGoDown(rectangleDimension, grid)) { var nextGrid = (char[, ])grid.Clone(); for (var x = rectangleDimension.XMin; x <= rectangleDimension.XMax; x++) { nextGrid[rectangleDimension.YMax + 1, x] = nextGrid[rectangleDimension.YMax, x]; nextGrid[rectangleDimension.YMin, x] = 'A'; NextPositions.Add((nextGrid, 'D')); } } return(NextPositions); }
/* 배치했을 경우의 평균높이를 계산. */ public void Evaluate_Height(int Order) { Heuristic_Height = new double[Width]; Average_Height = new double[Width]; int[,] Detector; char[,] temp; int x = 0, y; double height_Average1 = 0; double height_Average2 = 0; //bool check_detection = false; temp = (char[, ])Matrix.Clone();// 깊은 복사 수행 while (x < Width) { y = Height - Height_info[x] - 1;//실제 높이. while (!Check_Height(x, y, Order, temp, Minimum_Rotation[x]) && y > 0) { y--; } if (y <= 0) { Heuristic_Height[x] = Disenable; x++; continue; } Detector = form.Block_Rotate(Order, x, y, Minimum_Rotation[x]); for (int i = 0; i < 4; i++) { height_Average1 += Detector[i, 0]; height_Average2 += Height_info[Detector[i, 1]]; } height_Average1 /= 4; height_Average2 /= 4; for (int j = 0; j < 4; j++) { temp[Detector[j, 0], Detector[j, 1]] = Empty; } Heuristic_Height[x] = Height - height_Average1; Average_Height[x] = height_Average2; height_Average1 = 0; height_Average2 = 0; x++; } }
static void PutNew(int turnNo, char[,] board) { if (turnNo == 10) { string sfinal = GetString(board); scores[sfinal] = GetScore(board); return; } int imax = -1, jmax = -1; int max = -1; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i, j] == '.') { char[,] bn = (char[, ])board.Clone(); if (turnNo % 2 == 1) { bn[i, j] = '+'; } else { bn[i, j] = '*'; } string str = GetString(bn); if (!scores.ContainsKey(str)) { PutNew(turnNo + 1, bn); } int[] score0 = scores[str]; int score = turnNo % 2 == 1 ? score0[0] : score0[1]; if (score > max) { imax = i; jmax = j; max = score; } } } } char[,] bm = (char[, ])board.Clone(); bm[imax, jmax] = turnNo % 2 == 1 ? '+' : '*'; string saft = GetString(bm); string sbfr = GetString(board); scores[sbfr] = scores[saft]; }
public void Solve() { char[,] newLayout = (char[, ])layout.Clone(); do { layout = (char[, ])newLayout.Clone(); for (int i = 0; i < layout.GetLength(0); i++) { for (int j = 0; j < layout.GetLength(1); j++) { int occupiedAdjacentSeatsCount = seatCountBehaviour(i, j); if (layout[i, j] == 'L' && occupiedAdjacentSeatsCount == 0) { newLayout[i, j] = '#'; } else if (layout[i, j] == '#' && occupiedAdjacentSeatsCount >= occupiedSeatsThreeshold) { newLayout[i, j] = 'L'; } } } }while ( ( Enumerable.Range(0, layout.Rank).All(dimension => layout.GetLength(dimension) == newLayout.GetLength(dimension)) && layout.Cast <char>().SequenceEqual(newLayout.Cast <char>()) ) == false); }
static char[,] CharactersFall(char[,] matrix) { char[,] changedMatrix = (char[, ])matrix.Clone(); for (int column = 0; column < matrix.GetLength(1); column++) { Stack <char> currentColumnSymbols = new Stack <char>(); for (int row = 0; row < matrix.GetLength(0); row++) { if (changedMatrix[row, column] != ' ') { currentColumnSymbols.Push(changedMatrix[row, column]); } } for (int row = matrix.GetLength(0) - 1; row >= 0; row--) { if (currentColumnSymbols.Count > 0) { changedMatrix[row, column] = currentColumnSymbols.Pop(); } else { changedMatrix[row, column] = ' '; } } } return(changedMatrix); }
void Gen(int pos) { if (pos >= _wordsToInsert.Count || (DateTime.Now - initialTime).Minutes > 1) { return; } for (int i = pos; i < _wordsToInsert.Count; i++) { var posi = BestPosition(_wordsToInsert[i]); if (posi != null) { var word = _wordsToInsert[i]; var value = posi.Item3 == 0 ? _hCount : _vCount; PutWord(word, posi.Item1, posi.Item2, posi.Item3, value); Gen(pos + 1); RemoveWord(word, posi.Item1, posi.Item2, posi.Item3); } else { Gen(pos + 1); } } var c = FreeSpaces(); if (c >= _bestSolution) { return; } _bestSolution = c; _tempBoard = _board.Clone() as char[, ]; }
private static string CombatAreaToString(char[,] combatArea, List <Unit> units, int turn) { var sb = new StringBuilder(); sb.Append(Environment.NewLine); var dupArea = (char[, ])combatArea.Clone(); foreach (var c in units) { dupArea[c.Position.Y, c.Position.X] = c.UnitType; } for (int i = 0; i < dupArea.GetLength(0); ++i) { for (int j = 0; j < dupArea.GetLength(1); ++j) { sb.Append(dupArea[i, j]); } sb.Append(Environment.NewLine); } sb.Append(Environment.NewLine); sb.Append($"Turn: {turn} {Environment.NewLine}"); sb.Append($"Elf HP remaining: {units.Where(u => u.UnitType == 'E').Sum(u => u.HP)}{Environment.NewLine}"); sb.Append($"Goblin HP remaining: {units.Where(u => u.UnitType == 'G').Sum(u => u.HP)}{Environment.NewLine}"); return(sb.ToString()); }
static char[,] BunniesSpead(char[,] matrix, int n, int m) { char[,] copyMatrix = (char[, ])matrix.Clone(); for (int row = 0; row < n; row++) { for (int col = 0; col < m; col++) { if (matrix[row, col] == 'B') { if (col - 1 >= 0) { copyMatrix[row, col - 1] = 'B'; } if (col + 1 < m) { copyMatrix[row, col + 1] = 'B'; } if (row - 1 >= 0) { copyMatrix[row - 1, col] = 'B'; } if (row + 1 < n) { copyMatrix[row + 1, col] = 'B'; } } } } matrix = (char[, ])copyMatrix.Clone(); return(matrix); }
static Tuple <char[, ], bool> Solve(char[,] input, List <string> words, List <WordPlace> places) { var word = words[0]; foreach (var place in places.Where(x => x.length == word.Length)) { if (CheckWord(input, place, word)) { char[,] arrCopy = (char[, ])input.Clone(); SaveWord(arrCopy, place, word); if (words.Count() == 1) { return(Tuple.Create(arrCopy, true)); } var wordsCopy = new List <string>(words.Skip(1)); var placesCopy = new List <WordPlace>(places.Where(x => x != place)); var res = Solve(arrCopy, wordsCopy, placesCopy); if (res.Item2) { return(res); } } } return(Tuple.Create(input, false)); }
static void PlayAndPrint(Entity entity, char[,] table, int numberOfMoves, int generation) { char[,] table2 = (char[, ])table.Clone(); int playerPosition = 5; for (int i = 0; i < entity.Moves.Count; i++) { //table2[i, playerPosition] = '-'; try { playerPosition += entity.Moves[i] == Side.left ? -1 : 1; if (table2[i, playerPosition] == '#') { break; } table2[i, playerPosition] = '@'; } catch { break; } //Console.WriteLine("*******************************************"); //PrintMap(ref table); } //Console.WriteLine("*******************************************"); using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Aleksa\source\repos\flappyBird\results\map_" + localDate.ToString("yyyy-dd-M--HH-mm-ss") + ".txt", true)) { file.Write("*****************\n result: " + numberOfMoves + " generation: " + generation + "\n\n"); } PrintMap(ref table2); }
char[,] AdvanceMap(char[,] map, out bool changed) { changed = false; char[,] result = (char[, ])map.Clone(); for (int i = 0; i < map.GetLength(0); i++) { for (int j = 0; j < map.GetLength(1); j++) { int occupiedNeighborsCount = CountOccupiedNeighbors(map, i, j); switch (map[i, j]) { case 'L': if (occupiedNeighborsCount == 0) { changed = true; result[i, j] = '#'; } break; case '#': if (occupiedNeighborsCount >= 4) { result[i, j] = 'L'; changed = true; } break; } } } return(result); }
static char[,] RunGameOfSeats(char[,] seats, Func <char[, ], int, int, int> evaluateNeighbors, int decayFrom) { var next = (char[, ])seats.Clone(); for (; ;) { for (int y = 0; seats.GetLength(0) > y; ++y) { for (int x = 0; seats.GetLength(1) > x; ++x) { if ('L' == seats[y, x] && 0 == evaluateNeighbors(seats, y, x)) { next[y, x] = '#'; } else if ('#' == seats[y, x] && decayFrom <= evaluateNeighbors(seats, y, x)) { next[y, x] = 'L'; } else { next[y, x] = seats[y, x]; } } } if (next.Cast <char>().SequenceEqual(seats.Cast <char>())) { return(seats); } var temp = next; next = seats; seats = temp; } }
static void PrintMap(char[,] map, List <Unit> units) { char[,] printMap = (char[, ])map.Clone(); foreach (Unit u in units) { if (u.points > 0) { printMap[u.pos.x, u.pos.y] = u.isElf ? 'E' : 'G'; } } int width = printMap.GetLength(0); int height = printMap.GetLength(1); for (int y = 0; y < height; y++) { StringBuilder sb = new StringBuilder(); for (int x = 0; x < width; x++) { sb.Append(printMap[x, y]); } Console.Write(sb.ToString()); List <Unit> rowUnits = units.Where(u => (u.pos.y == y) && (u.points > 0)).ToList(); if (rowUnits.Count > 0) { Console.Write(" "); foreach (Unit u in rowUnits) { Console.Write((u.isElf ? "E" : "G") + "(" + u.points + ") "); } } Console.WriteLine(); } Console.WriteLine(); }
int NumberOfMethods;//except main method public Compiler(char[,] main, Dictionary <char, char[, ]> methodsSourceWithNames) { MainSource = (char[, ])(main.Clone()); MethodsSource = methodsSourceWithNames; Names = methodsSourceWithNames.Keys.ToList(); Names.Sort(); }
public static (int occupied, int free) Simulate(char[,] seatMap, int simulationSteps = 100) { var mapToSimulate = (char[, ])seatMap.Clone(); char[,] simulatedMap; var simSeats = CountSeats(seatMap); for (int iSim = 0; iSim < simulationSteps; iSim++) { simSeats = CountSeats(mapToSimulate); simulatedMap = SimulateOneStep(mapToSimulate); // Continue simulation as long as seats change Console.WriteLine("Simseats: " + simSeats); if (CountSeats(simulatedMap) != simSeats) { simSeats = CountSeats(simulatedMap); mapToSimulate = simulatedMap; } else { break; } } return(simSeats); }
public CBuffer(int height, int width) { this.height = height; this.width = width; cBuffer = new char[this.height, this.width]; newBuffer = (char[, ])cBuffer.Clone(); }
protected void GenerateObjectsRainShared(MapObject o, char[,] restrictedMap) { char[,] supportMap = restrictedMap.Clone() as char[, ]; // Restrict again if there are object that need a further restriction. if (!o.placeAnywhere && objectToWallDistance > 1) { for (int i = 1; i < objectToWallDistance; i++) { MapEdit.ErodeMap(supportMap, wallChar); } } List <Coord> roomTiles = MapInfo.GetFreeTiles(supportMap, roomChar); for (int i = 0; i < o.numObjPerMap; i++) { if (roomTiles.Count > 0) { int selected = pseudoRandomGen.Next(0, roomTiles.Count); map[roomTiles[selected].tileX, roomTiles[selected].tileY] = o.objectChar; MapEdit.DrawCircle(roomTiles[selected].tileX, roomTiles[selected].tileY, (o.placeAnywhere) ? 1 : objectToObjectDistance, supportMap, wallChar); roomTiles = MapInfo.GetFreeTiles(supportMap, roomChar); } else { ManageError(Error.SOFT_ERROR, "Error while populating the map, no more free " + "tiles are availabe."); return; } } }
static int PlaySetOfMoves(Entity entity, char[,] table) { char[,] table2 = (char[, ])table.Clone(); int playerPosition = 5; for (int i = 0; i < entity.Moves.Count; i++) { //table2[i, playerPosition] = '-'; try { playerPosition += entity.Moves[i] == Side.left ? -1 : 1; if (table2[i, playerPosition] == '#') { return(i); } table2[i, playerPosition] = '@'; } catch { return(i); } //Console.WriteLine("*******************************************"); //PrintMap(ref table); } return(0); }
/// <summary> /// This method will take in a 2 dimensional char array and return /// a char array maze that is flipped along the diagonal, or in mathematical /// terms, transposed. /// ie. if the array looks like 1, 2, 3 /// 4, 5, 6 /// 7, 8, 9 /// The returned result will be: /// 1, 4, 7 /// 2, 5, 8 /// 3, 6, 9 /// The current return statement is just a placeholder so the program /// doesn't complain about no return value. /// </summary> /// <param name="mazeToTranspose"></param> /// <returns>transposedMaze</returns> static char[,] transposeMaze(char[,] mazeToTranspose) { //declares two variables to store the width, and length of the incoming array. int rowCount = mazeToTranspose.GetLength(0); int colCount = mazeToTranspose.GetLength(1); //an array is made using the row and column as bounds. char[,] transposed = new char[colCount, rowCount]; //assuming the the array is square.... if (rowCount == colCount) { //...transpose is a clone of the incoming maze. transposed = (char[, ])mazeToTranspose.Clone(); //i starts at 1 to iterate half the array. //while the counter 'i' is less than the row bound... for (int i = 1; i < rowCount; i++) { //...while the counter 'j' is less than i... for (int j = 0; j < i; j++) { //...create the char var temp to hold the transposed coordinates. char temp = transposed[i, j]; //store the the transposed coordinates. transposed[i, j] = transposed[j, i]; transposed[j, i] = temp; } } } //return the transposed array. return(transposed); }
private static void TraverseAllPossiblePaths(char[,] matrix, Tuple <int, int> cell) { var row = cell.Item1; var col = cell.Item2; if (matrix[row, col] == DestinationCell) { PrintMatrix(matrix); Console.WriteLine(); return; } matrix[row, col] = TraversedCell; var availableMoves = GetAvailableMoves(matrix, cell); if (availableMoves.Count <= 0) { return; } foreach (var move in availableMoves) { TraverseAllPossiblePaths((char[, ])matrix.Clone(), move); } }
static void IterateMap() { char[,] nextMap = (char[, ])map.Clone(); int width = map.GetLength(0); int height = map.GetLength(1); Position p = new Position(); for (p.y = 0; p.y < height; p.y++) { for (p.x = 0; p.x < width; p.x++) { Inhabitants n = CalculateNeighbors(p); if (map[p.x, p.y] == open) { nextMap[p.x, p.y] = (n.tree >= 3) ? tree : open; } else if (map[p.x, p.y] == tree) { nextMap[p.x, p.y] = (n.lumber >= 3) ? lumber : tree; } else if (map[p.x, p.y] == lumber) { nextMap[p.x, p.y] = ((n.lumber >= 1) && (n.tree >= 1)) ? lumber : open; } } } map = nextMap; }
static char[,] BecomeKing(char[,] state, int player) { char[,] newstate = (char[, ])state.Clone(); if (player == -1) { for (int j = 1; j < newstate.GetLength(1); j += 2) { if (newstate[0, j] == InputFromPlayer(player)) { newstate[0, j] = 'W'; } } } else { for (int j = 0; j < newstate.GetLength(1); j += 2) { if (newstate[7, j] == InputFromPlayer(player)) { newstate[7, j] = 'B'; } } } return(newstate); }
private bool iterate2(char[,] grid) { var prev = (char[, ])grid.Clone(); var changed = false; for (int y = 0; y < grid.GetLength(1); y++) { for (int x = 0; x < grid.GetLength(0); x++) { var occupied = longNeighbours(prev, x, y).Count(c => c == '#'); if (prev[x, y] == 'L' && occupied == 0) { grid[x, y] = '#'; changed = true; } else if (prev[x, y] == '#' && occupied >= 5) { grid[x, y] = 'L'; changed = true; } } } //Utils.describe(grid); return(changed); }
static (char[, ], bool) ApplyRules(char[,] input, Func <char[, ], int, int, IEnumerable <char> > getSeats, int minOccupied) { var next = (char[, ])input.Clone(); var changed = false; for (var y = 0; y < input.GetLength(1); y++) { for (var x = 0; x < input.GetLength(0); x++) { if (input[x, y] == '#') { var neighbours = getSeats(input, x, y); if (neighbours.Count(n => n == '#') >= minOccupied) { next[x, y] = 'L'; changed = true; } } if (input[x, y] == 'L') { var neighbours = getSeats(input, x, y); if (neighbours.All(n => n != '#')) { next[x, y] = '#'; changed = true; } } } } return(next, changed); }
public long SolvePart2() { matrix = CreateMatrix(); int numChangesOfState; do { var clone = matrix.Clone() as char[, ]; numChangesOfState = 0; for (var r = 1; r < rows - 1; r++) { for (var c = 1; c < columns - 1; c++) { var seat = matrix[r, c]; var occupiedNeighbors = NumberOfOccupiedVisibleSeats(r, c); if (seat == EMPTY_SEAT && occupiedNeighbors == 0) { numChangesOfState++; clone[r, c] = OCCUPIED_SEAT; } else if (seat == OCCUPIED_SEAT && occupiedNeighbors >= 5) { numChangesOfState++; clone[r, c] = EMPTY_SEAT; } } } matrix = clone; } while (numChangesOfState > 0); return(CountNumberOfOccupiedSeats()); }