/// <summary> /// Reads a array. /// </summary> /// <returns> /// The array. /// </returns> /// <param name='address'> /// Address. /// </param> /// <param name='size'> /// Size of the array. /// </param> /// <typeparam name='T'> /// The type of the array values. /// </typeparam> public T[] ReadArray <T>(ulong address, int size) where T : struct { int typeSize = Marshal.SizeOf(typeof(T)); int dataSize = typeSize * size; IntPtr dataPointer = Read(address, (ulong)dataSize); try { switch (Type.GetTypeCode(typeof(T))) { case TypeCode.Byte: var bytes = new byte[size]; Marshal.Copy(dataPointer, bytes, 0, size); return(bytes.Cast <T>().ToArray()); case TypeCode.Char: var chars = new char[size]; Marshal.Copy(dataPointer, chars, 0, size); return(chars.Cast <T>().ToArray()); case TypeCode.Int16: var shorts = new short[size]; Marshal.Copy(dataPointer, shorts, 0, size); return(shorts.Cast <T>().ToArray()); case TypeCode.Int32: var ints = new int[size]; Marshal.Copy(dataPointer, ints, 0, size); return(ints.Cast <T>().ToArray()); case TypeCode.Int64: var longs = new long[size]; Marshal.Copy(dataPointer, longs, 0, size); return(longs.Cast <T>().ToArray()); case TypeCode.Single: var floats = new float[size]; Marshal.Copy(dataPointer, floats, 0, size); return(floats.Cast <T>().ToArray()); case TypeCode.Double: var doubles = new double[size]; Marshal.Copy(dataPointer, doubles, 0, size); return(doubles.Cast <T>().ToArray()); default: var objects = new T[size]; IntPtr currentObjectPointer = dataPointer; for (int i = 0; i < size; i++) { objects[i] = (T)Marshal.PtrToStructure(currentObjectPointer, typeof(T)); currentObjectPointer = new IntPtr(currentObjectPointer.ToInt64() + typeSize); } return(objects); } } finally { Marshal.FreeHGlobal(dataPointer); } }
public static void Part1() { var inputs = File.ReadAllLines("day11-input.txt"); var rows = inputs.Length; var columns = inputs.First().Length; char[,] preiousSeats; char[,] seats = new char[rows, columns]; for (var row = 0; row < rows; row++) { for (var column = 0; column < columns; column++) { seats[row, column] = inputs.ElementAt(row).ElementAt(column); } } do { preiousSeats = (char[, ])seats.Clone(); for (var row = 0; row < rows; row++) { for (var column = 0; column < columns; column++) { var previousSeat = preiousSeats[row, column]; var countAdjacentOccupied = CountAdjacentOccupied(preiousSeats, row, column); if (previousSeat == 'L' && countAdjacentOccupied == 0) { seats[row, column] = '#'; } else if (previousSeat == '#' && countAdjacentOccupied >= 4) { seats[row, column] = 'L'; } else { seats[row, column] = preiousSeats[row, column]; } } } } while (!seats.Cast <char>().SequenceEqual(preiousSeats.Cast <char>())); var occupied = seats.Cast <char>().Count(seat => seat == '#'); Console.WriteLine(occupied); }
public void TestPart1_WithSampleInput_ShouldStabilizeAt37() { string sampleInput = @" L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL"; string[] seats = sampleInput.Split(Environment.NewLine, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries ); char[,] seatMap = new char[seats.Length, seats[0].Length]; for (int i = 0; i < seats.Length; i++) { for (int j = 0; j < seats[0].Length; j++) { seatMap[i, j] = seats[i][j]; } } RuleSet rules = new RuleSet(); rules.GetOccupiedThreshold = rules.GetPart1OccupiedThreshold; rules.GetNumOccupiedSeats = rules.CountAdjacentOccupiedSeats; GameOfChairs chairs = new GameOfChairs(seatMap, rules); char[,] lastMap = new char[seatMap.GetLength(0), seatMap.GetLength(1)]; bool equal = false; do { Array.Copy(chairs.CurrentMap, 0, lastMap, 0, chairs.CurrentMap.Length); chairs.RunRound(); equal = chairs.CurrentMap.Rank == lastMap.Rank && Enumerable.Range(0, chairs.CurrentMap.Rank).All(dimension => chairs.CurrentMap.GetLength(dimension) == lastMap.GetLength(dimension)) && chairs.CurrentMap.Cast <char>().SequenceEqual(lastMap.Cast <char>()); } while (!equal); Assert.Equal(37, chairs.CountAllOccupiedSeats()); }
public static int GetPart1(string[] p_strRiddleSource) { var arrLeds = new char[LCD_SCREEN_HEIGHT, LCD_SCREEN_WIDTH]; InitLCD(arrLeds); foreach (var strSingleCommand in p_strRiddleSource) { RunSingleCommand(arrLeds, strSingleCommand); // DEBUG: DisplayLCDContent(arrLeds); } // DEBUG: DisplayLCDContent(arrLeds); var intTotalLedsOn = arrLeds.Cast <char>().Count(chrLed => chrLed == LCD_FULL_CELL); return(intTotalLedsOn); }
/// <summary> /// Read an array of integral types (int, float, byte, etc) from unmanaged memory. /// </summary> /// <typeparam name="T">Integral type to read. Must be struct, but not all structs are supported (only those supported by Marshal.Copy</typeparam> /// <param name="addr">Address to read array from</param> /// <param name="size">Size of the array to read (number of elements)</param> /// <returns></returns> public static T[] ReadArray <T>(this IntPtr addr, int size) where T : struct { switch (Type.GetTypeCode(typeof(T))) { case TypeCode.Byte: var bytes = new byte[size]; Marshal.Copy(addr, bytes, 0, size); return(bytes.Cast <T>().ToArray()); case TypeCode.Char: var chars = new char[size]; Marshal.Copy(addr, chars, 0, size); return(chars.Cast <T>().ToArray()); case TypeCode.Int16: var shorts = new short[size]; Marshal.Copy(addr, shorts, 0, size); return(shorts.Cast <T>().ToArray()); case TypeCode.Int32: var ints = new int[size]; Marshal.Copy(addr, ints, 0, size); return(ints.Cast <T>().ToArray()); case TypeCode.Int64: var longs = new long[size]; Marshal.Copy(addr, longs, 0, size); return(longs.Cast <T>().ToArray()); case TypeCode.Single: var floats = new float[size]; Marshal.Copy(addr, floats, 0, size); return(floats.Cast <T>().ToArray()); case TypeCode.Double: var doubles = new double[size]; Marshal.Copy(addr, doubles, 0, size); return(doubles.Cast <T>().ToArray()); default: throw new ArgumentException(string.Format("Unsupported type argument supplied: {0}", typeof(T).Name)); } }
public static bool CheckTerm <T>(Card card, T term) { List <T> checkList = new List <T>(); if (term is string) { // There may an issue with the types in these string arrays string[] checkParts = new string[] { card.name, card.suit, card.value, card.abbrev }; checkParts = Array.ConvertAll(checkParts, t => t.ToLower()); string castedTerm = (string)(object)term; castedTerm = castedTerm.ToLower(); term = (T)Convert.ChangeType(castedTerm, typeof(T)); checkList = checkParts.Cast <T>().ToList(); } else if (term is char) { char[] checkParts = new char[] { card.suit[0], card.value[0] }; checkParts = Array.ConvertAll(checkParts, t => char.ToLower(t)); char castedTerm = (char)(object)term; castedTerm = char.ToLower(castedTerm); term = (T)Convert.ChangeType(castedTerm, typeof(T)); checkList = checkParts.Cast <T>().ToList(); } else { return(false); } foreach (T t in checkList) { if (t.Equals(term)) { return(true); } } return(false); }
private int Run(int numIter) { var input = Input(); AddDuplicates(input); char[,] initial = new char[3, 3] { { '.', '#', '.' }, { '.', '.', '#' }, { '#', '#', '#' }, }; for (int i = 0; i < numIter; ++i) { Decorate(ref initial, input); } return(initial.Cast <char>().ToArray().Where(i => i == '#').Count()); }
public static int Part1(string path, int iterations) { var start = new char[3, 3] { { '.', '#', '.' }, { '.', '.', '#' }, { '#', '#', '#' } }; var input = File.ReadLines(path).ToList(); var rules = ParseInput(input); for (int i = 0; i < iterations; i++) { var squares = Split(start); var endSquares = new List <char[, ]>(); foreach (var square in squares) { endSquares.Add(Grow(rules, square)); } start = Combine(endSquares); Console.WriteLine(i); } return(start.Cast <char>().Count(c => c == '#')); }
static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); var matrix = new char[n, n]; for (int row = 0; row < matrix.GetLength(0); row++) { string colelements = Console.ReadLine(); for (int col = 0; col < matrix.GetLength(1); col++) { matrix[row, col] += colelements[col]; } } string symbol = Console.ReadLine(); int x = 0; int y = 0; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { if (matrix[row, col] == char.Parse(symbol)) { x = row; y = col; break; } } } if (matrix.Cast <char>().Contains(char.Parse(symbol))) { Console.WriteLine($"({x}, {y})"); } else { Console.WriteLine($"{symbol} does not occur in the matrix"); } }
static void Main(string[] args) { var board = new char[, ] { { 'o', 'a', 'a', 'n' }, { 'e', 't', 'a', 'e' }, { 'i', 'h', 'k', 'r' }, { 'i', 'f', 'l', 'v' } }; var words = new string[] { "oath", "pea", "eat", "rain" }; // var cfg = new GFG(words, board); // var result = cfg.findWords().ToArray(); // Console.WriteLine(String.Join("\n", result)); char[] baData = new char[board.Length]; baData = board.Cast <char>().ToArray(); // Buffer.BlockCopy(board, 0, baData, 0, board.Length); Trie.FindWords(words, baData); Console.ReadLine(); }
static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string[] moves = Console.ReadLine().Split(" ").ToArray(); char[,] matrix = new char[n, n]; int minerRow = 0; int minerCol = 0; for (int row = 0; row < n; row++) { char[] rowData = Console .ReadLine() .Split(" ") .Select(char.Parse) .ToArray(); for (int col = 0; col < n; col++) { matrix[row, col] = rowData[col]; if (matrix[row, col] == 's') { minerRow = row; minerCol = col; } } } bool IsInRange = false; int countCoal = 0; int rowIndex = 0; int colIndex = 0; char letter = ' '; foreach (var move in moves) { switch (move) { case "up": if (IsInside(matrix, minerRow - 1, minerCol)) { IsInRange = true; letter = matrix[minerRow - 1, minerCol]; rowIndex = minerRow - 1; colIndex = minerCol; minerRow -= 1; } break; case "down": if (IsInside(matrix, minerRow + 1, minerCol)) { IsInRange = true; letter = matrix[minerRow + 1, minerCol]; rowIndex = minerRow + 1; colIndex = minerCol; minerRow += 1; } break; case "right": if (IsInside(matrix, minerRow, minerCol + 1)) { IsInRange = true; letter = matrix[minerRow, minerCol + 1]; rowIndex = minerRow; colIndex = minerCol + 1; minerCol += 1; } break; case "left": if (IsInside(matrix, minerRow, minerCol - 1)) { IsInRange = true; letter = matrix[minerRow, minerCol - 1]; rowIndex = minerRow; colIndex = minerCol - 1; minerCol -= 1; } break; } if (IsInRange) { if (letter == 'c') { matrix[minerRow, minerCol] = '*'; } if (letter == 'e') { Console.WriteLine($"Game over! ({rowIndex}, {colIndex})"); return; } } } int countCoalsLeft = matrix.Cast <char>().Count(symbol => symbol == 'c'); Console.WriteLine(countCoalsLeft == 0 ? $"You collected all coals! ({rowIndex}, {colIndex})" : $"{countCoalsLeft} coals left. ({rowIndex}, {colIndex})"); }
/// <summary> /// Tableau : Permet d'ecrire le tableau principal ou le joueur va se déplacer et le tableau ou il peut voir ce que il doit encore completer /// Succès : Oui /// Optimisation : peut faire mieux /// </summary> private static void Tableau(byte byteUser) { // variables locales char charTbl = ' '; byte byteX = 0; byte byteY = 0; // création du tableau answer avec l'input user char[,] Tab_charCavalierAnswer = new char[byteUser, byteUser]; // création tableau user avec l'input user G_Tab_charCavalier = new char[byteUser, byteUser]; // début boucle for Y, pour ecrire verticallement les cavalies for (byteY = 0; byteY != byteUser; byteY++) { // début boucle for Y, pour ecrire honrizontallement les cavalies for (byteX = 0; byteX != byteUser; byteX++) { // si byteX ou byteY = a 0 ou a sbyteUser -1, donc c'est une bordure if (byteX == 0 || byteY == 0 || byteX == byteUser - 1 || byteY == byteUser - 1) { // regarde si la position actuelle de la boucle for est autre que la bordure tout en haut et tout en bas if (byteX == 0 && byteY != 0 && byteY != byteUser - 1 || byteX == byteUser - 1 && byteY != 0 && byteY != byteUser - 1) { charTbl = '║'; } // regarde si la position actuelle de la boucle for est autre que la bordure à gauche ou a droite else if (byteY == 0 && byteX != 0 && byteX != byteUser - 1 || byteY == byteUser - 1 && byteX != 0 && byteX != byteUser - 1) { charTbl = '═'; } // regarde si c'est le coin en haut a droite else if (byteX == 0 && byteY == 0) { charTbl = '╔'; } // regarde si c'est le coin en haut a gauche else if (byteX == byteUser - 1 && byteY == 0) { charTbl = '╗'; } // regarde si c'est le coin en bas a droite else if (byteX == 0 && byteY == byteUser - 1) { charTbl = '╚'; } // regarde si c'est le coin en bas a gauche else if (byteX == byteUser - 1 && byteY == byteUser - 1) { charTbl = '╝'; } // met la bordure en bleu vu que c'est une bordure Console.ForegroundColor = ConsoleColor.Blue; } // si non alors c'est le millieu du tableau else { // met la couleur des caratères a ecrire en rouge, car c'est une croix Console.ForegroundColor = ConsoleColor.Red; // change le caratère actuelle en croix charTbl = 'x'; } // ecrit le caratère actuelle dans le tableau principale G_Tab_charCavalier[byteY, byteX] = charTbl; // ecrit le caratère actuelle dans le tableau secondaire Tab_charCavalierAnswer[byteY, byteX] = charTbl; // si le caratère actuelle est un X, alors va ecrire dans le tableau de réponse un O, vu que on doit remplire le tableau user avec des O if (charTbl == 'x') { // ecrit un O dans le tableau de réponse Tab_charCavalierAnswer[byteY, byteX] = 'O'; } // set le curseur pour ecrire le tableau principal Console.SetCursorPosition(byteX, byteY); // ecrit le caractère séléctionné par l'algoritme Console.Write(charTbl); // set le curseur pour ecrire le tableau secondaire Console.SetCursorPosition(byteX + byteUser + 1, byteY); // ecrit le caractère séléctionné par l'algoritme Console.Write(charTbl); } // fin boucle for X } // fin boucle for Y // initialisation tableau réponse answer G_Tab_charCavalierAnswer = Tab_charCavalierAnswer.Cast <char>().ToArray(); // initalisation pion G_Tab_charCavalier[1, 1] = 'O'; // change la couleur en gris Console.ForegroundColor = ConsoleColor.Gray; // met le curseur en dehor du tableau Console.SetCursorPosition(5, G_sbyteYUser + byteUser); // ecrit comment leave le jeu Console.Write("Appuyze sur Escape pour quitter le jeu"); // met le curseur en dehor du tableau avec y + 1 Console.SetCursorPosition(5, G_sbyteYUser + byteUser + 1); // ecrit comment reset le jeu Console.Write("Appuyze sur 'r' pour reset le cavalier"); } // fin void static Tableau()
public (string, string) Solve(string[] input) { // Parse the tiles var tiles = input.Split("").Select(g => new Tile(g.ToArray())).ToArray(); // The image is a square, so calculate how many tiles wide/high var gridSize = (int)Math.Sqrt(tiles.Length); // Find the corners var corners = tiles.Where(t => t.Matches(tiles) == 2).ToList(); // We can also find the edges and middle, but it isn't needed //var edges = tiles.Where(t => t.Matches(tiles) == 3); //var middle = tiles.Where(t => t.Matches(tiles) == 4); // For part 1, multiply the corner IDs var part1 = corners.Aggregate(1L, (i, v) => i * v.ID).ToString(); // Generate a lookup by side values so we don't have to regenerate them every time var sides = new Dictionary <int, List <Tile> >( tiles.SelectMany(t => t.Sides.Select(s => new { s, t })) .GroupBy(s => s.s) .Where(s => s.Count() > 1) .Select(s => new KeyValuePair <int, List <Tile> >(s.Key, s.Select(i => i.t).ToList())) ); // Assemble the pieces starting with the top left corner var assembled = new Tile[gridSize, gridSize]; //Console.WriteLine("{0} {1}", topLeft.GetSide(Tile.SideName.Left), topLeft.GetSide(Tile.SideName.Right)); for (int c = 0; c < gridSize; c++) { for (int r = 0; r < gridSize; r++) { Tile nextTile; if (c == 0 && r == 0) // Find the corner and orient { nextTile = corners.First(); while (!sides.ContainsKey(nextTile.GetSide(Tile.SideName.Right)) || !sides.ContainsKey(nextTile.GetSide(Tile.SideName.Bottom))) { nextTile.Rotate(); } } else if (r == 0) // top row: find the tile that fits to the right of the last one { var lastRight = assembled[r, c - 1].GetSide(Tile.SideName.Right); nextTile = sides[lastRight].Single(e => !e.IsPlaced); // Rotate until the right side is on the left while (nextTile.GetSide(Tile.SideName.Left) != lastRight && nextTile.GetSide(Tile.SideName.LeftReverse) != lastRight) { nextTile.Rotate(); } // Flip if necessary if (nextTile.GetSide(Tile.SideName.Left) != lastRight) { nextTile.FlipVertically(); } } else // find the tile that fits the one above { var lastBottom = assembled[r - 1, c].GetSide(Tile.SideName.Bottom); nextTile = sides[lastBottom].Single(e => !e.IsPlaced); while (nextTile.GetSide(Tile.SideName.Top) != lastBottom && nextTile.GetSide(Tile.SideName.TopReverse) != lastBottom) { nextTile.Rotate(); } if (nextTile.GetSide(Tile.SideName.Top) != lastBottom) { nextTile.FlipHorizontally(); } } assembled[r, c] = nextTile; nextTile.IsPlaced = true; } } // Extract the final image var grid = new char[96, 96]; for (int c = 0; c < gridSize; c++) { for (int i = 1; i < 9; i++) { for (int r = 0; r < gridSize; r++) { for (int j = 1; j < 9; j++) { grid[c * 8 + i - 1, r * 8 + j - 1] = assembled[r, c].Data[j, i]; } } } } // Count the total water, including potential monsters var waterCount = grid.Cast <char>().Count(c => c == '#'); // Go through each orientation and see if we find monsters for (int i = 0; i < 8; i++) { var count = CountMonsters(grid); // Spotted! Subtract 15 for each monster from the total if (count > 0) { return(part1.ToString(), (waterCount - count * 15).ToString()); } // After the first 4 rotations, do a flip if (i == 4) { grid = Helpers.FlipH(grid); } else { grid = Helpers.RotateCW(grid); } } throw new InvalidOperationException("Not found"); }
static void Main() { List <string> InputList = GetInputList(); int[] wkArr = InputList[0].Split(' ').Select(X => int.Parse(X)).ToArray(); int H = wkArr[0]; int W = wkArr[1]; char[,] InputBanArr = new char[W, H]; UB_X = W - 1; UB_Y = H - 1; for (int Y = 1; Y <= InputList.Count - 1; Y++) { for (int X = 0; X <= InputList[Y].Length - 1; X++) { InputBanArr[X, Y - 1] = InputList[Y][X]; } } //Console.WriteLine(BanToStr(BeforeBanArr)); //???????? //????8??????????????????????? char[,] AnswerBanArr = new char[W, H]; for (int X = 0; X <= UB_X; X++) { for (int Y = 0; Y <= UB_Y; Y++) { if (Is8KinbouAllBlack(InputBanArr, X, Y)) { AnswerBanArr[X, Y] = '#'; } else { AnswerBanArr[X, Y] = '.'; } } } //???????? //??????????????????????????? char[,] AfterBanArr = new char[W, H]; for (int X = 0; X <= UB_X; X++) { for (int Y = 0; Y <= UB_Y; Y++) { if (Is8KinbouAnyBlack(AnswerBanArr, X, Y)) { AfterBanArr[X, Y] = '#'; } else { AfterBanArr[X, Y] = '.'; } } } if (InputBanArr.Cast <char>().SequenceEqual(AfterBanArr.Cast <char>())) { Console.WriteLine("possible"); Console.Write(BanToStr(AnswerBanArr)); } else { Console.WriteLine("impossible"); } }
public static int SolveProblem2() { var lines = ProblemInput.SplitToLines().ToList(); var width = lines[0].Length + 2; var height = lines.Count + 2; var area = new char[width, height]; var numberOfMinutesToCount = 1000000000; var areasByTime = new Dictionary <int, char[, ]>(); for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { if (x == 0 || x == width - 1 || y == 0 || y == height - 1) { area[x, y] = 'Q'; } else { area[x, y] = lines[y - 1][x - 1]; } } } var defaultPair = new KeyValuePair <int, char[, ]>(); var loopStartTime = -1; var loopEndTime = -1; for (var t = 0; t < numberOfMinutesToCount; t++) { if (t % 10000 == 0) { Console.WriteLine("t = " + t); } var match = areasByTime.SingleOrDefault(kv => kv.Value.Cast <char>().SequenceEqual(area.Cast <char>())); if (!match.Equals(defaultPair)) { loopStartTime = match.Key; loopEndTime = t; break; } areasByTime[t] = area; var newArea = new char[width, height]; for (var y = 0; y < height; y++) { newArea[0, y] = 'Q'; newArea[width - 1, y] = 'Q'; } for (var x = 0; x < width; x++) { newArea[x, 0] = 'Q'; newArea[x, height - 1] = 'Q'; } //PrintArea(area); for (var y = 1; y < height - 1; y++) { for (var x = 1; x < width - 1; x++) { switch (area[x, y]) { case '.': if (CountSurrounding(area, '|', x, y) >= 3) { newArea[x, y] = '|'; } else { newArea[x, y] = '.'; } break; case '|': if (CountSurrounding(area, '#', x, y) >= 3) { newArea[x, y] = '#'; } else { newArea[x, y] = '|'; } break; case '#': if (CountSurrounding(area, '#', x, y) >= 1 && CountSurrounding(area, '|', x, y) >= 1) { newArea[x, y] = '#'; } else { newArea[x, y] = '.'; } break; default: throw new Exception("What's this? " + area[x, y]); } } } //PrintArea(newArea); area = newArea; } Console.WriteLine("Loop start: " + loopStartTime); Console.WriteLine("Loop end: " + loopEndTime); // 0123456789 // abcdecdecd var loopLength = loopEndTime - loopStartTime; // 5 - 2 = 3 var loopIndexAtEnd = (numberOfMinutesToCount - loopStartTime) % loopLength; // (9 - 2) % 3 = 1 var areaAtEnd = areasByTime[loopStartTime + loopIndexAtEnd]; var treeCount = 0; var yardCount = 0; for (var y = 1; y < height - 1; y++) { for (var x = 1; x < width - 1; x++) { if (areaAtEnd[x, y] == '|') { treeCount++; } if (areaAtEnd[x, y] == '#') { yardCount++; } } } return(treeCount * yardCount); }
static void Main(string[] args) { int size = int.Parse(Console.ReadLine()); string[] commands = Console .ReadLine() .Split(" ") .ToArray(); char[,] matrix = new char[size, size]; ReadInput(matrix); bool IsInRange = false; int rowIndex = 0; int colIndex = 0; char letter = ' '; foreach (var command in commands) { switch (command) { case "up": if (IsInside(matrix, Srow - 1, Scol)) { IsInRange = true; letter = matrix[Srow - 1, Scol]; rowIndex = Srow - 1; colIndex = Scol; Srow -= 1; } break; case "down": if (IsInside(matrix, Srow + 1, Scol)) { IsInRange = true; letter = matrix[Srow + 1, Scol]; rowIndex = Srow + 1; colIndex = Scol; Srow += 1; } break; case "right": if (IsInside(matrix, Srow, Scol + 1)) { IsInRange = true; letter = matrix[Srow, Scol + 1]; rowIndex = Srow; colIndex = Scol + 1; Scol += 1; } break; case "left": if (IsInside(matrix, Srow, Scol - 1)) { IsInRange = true; letter = matrix[Srow, Scol - 1]; rowIndex = Srow; colIndex = Scol - 1; Scol -= 1; } break; } if (IsInRange) { if (letter == 'c') { matrix[rowIndex, colIndex] = '*'; } if (letter == 'e') { Console.WriteLine($"Game over! ({rowIndex}, {colIndex})"); return; } } } int countCoalsLeft = matrix.Cast <char>().Count(symbol => symbol == 'c'); Console.WriteLine(countCoalsLeft == 0 ? $"You collected all coals! ({rowIndex}, {colIndex})" : $"{countCoalsLeft} coals left. ({rowIndex}, {colIndex})"); }
static string Encode(string text) { int counter = 0; char[,] matrix = new char[grid.GetLength(0), grid.GetLength(1)]; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { if (grid[i, j]) { matrix[i, j] = counter >= text.Length ? '\0' : text[counter]; counter++; } } } displayProgress(matrix); Console.WriteLine(text[counter]); for (int i = matrix.GetLength(0) - 1; i >= 0; i--) { for (int j = matrix.GetLength(1) - 1; j >= 0; j--) { if (grid[i, j]) { matrix[matrix.GetLength(0) - 1 - i, matrix.GetLength(1) - 1 - j] = counter >= text.Length ? '\0' : text[counter]; counter++; } } } displayProgress(matrix); for (int i = matrix.GetLength(0) - 1; i >= 0; i--) { for (int j = 0; j < matrix.GetLength(1); j++) { if (grid[i, j]) { matrix[matrix.GetLength(0) - 1 - i, j] = counter >= text.Length ? '\0' : text[counter]; counter++; } } } displayProgress(matrix); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = matrix.GetLength(1) - 1; j >= 0; j--) { if (grid[i, j]) { matrix[i, matrix.GetLength(1) - 1 - j] = counter >= text.Length ? '\0' : text[counter]; counter++; } } } displayProgress(matrix); return(string.Join("", matrix.Cast <char>())); }
static void Main(string[] args) { int rows = int.Parse(Console.ReadLine()); int cols = rows; string[] commandArray = Console.ReadLine().Split().ToArray(); char[,] matrix = new char[rows, cols]; int rowStart = 0; int colStart = 0; for (int row = 0; row < rows; row++) { char[] currentLine = Console.ReadLine().Split().Select(char.Parse).ToArray(); for (int col = 0; col < cols; col++) { matrix[row, col] = currentLine[col]; if (matrix[row, col] == 's') { rowStart = row; colStart = col; } } } foreach (string command in commandArray) { int currentRow = rowStart; int currentCol = colStart; switch (command) { case "up": currentRow--; break; case "down": currentRow++; break; case "left": currentCol--; break; case "right": currentCol++; break; } if (IsValidCoordinates(matrix, currentRow, currentCol)) { rowStart = currentRow; colStart = currentCol; switch (matrix[rowStart, colStart]) { case 'e': Console.WriteLine($"Game over! ({rowStart}, {colStart})"); return; case 'c': matrix[rowStart, colStart] = '*'; break; } } } int countCoalsLeft = matrix.Cast <char>().Count(symbol => symbol == 'c'); Console.WriteLine(countCoalsLeft == 0 ? $"You collected all coals! ({rowStart}, {colStart})" : $"{countCoalsLeft} coals left. ({rowStart}, {colStart})"); }
public static T[] ReadArray <T>(this Process proc, IntPtr addr, int count) where T : struct { var dataSize = Marshal.SizeOf(typeof(T)) * count; int bytesRead; var pBytes = Marshal.AllocHGlobal(dataSize); try { if (!Imports.ReadProcessMemory(proc.GetHandle(), addr, pBytes, (uint)dataSize, out bytesRead)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } if (bytesRead != dataSize) { throw new Exception(string.Format("Unable to read {0} bytes for array of type {1} with {2} elements", dataSize, typeof(T).Name, count)); } switch (Type.GetTypeCode(typeof(T))) { case TypeCode.Byte: var bytes = new byte[count]; Marshal.Copy(pBytes, bytes, 0, count); return(bytes.Cast <T>().ToArray()); case TypeCode.Char: var chars = new char[count]; Marshal.Copy(pBytes, chars, 0, count); return(chars.Cast <T>().ToArray()); case TypeCode.Int16: var shorts = new short[count]; Marshal.Copy(pBytes, shorts, 0, count); return(shorts.Cast <T>().ToArray()); case TypeCode.Int32: var ints = new int[count]; Marshal.Copy(pBytes, ints, 0, count); return(ints.Cast <T>().ToArray()); case TypeCode.Int64: var longs = new long[count]; Marshal.Copy(pBytes, longs, 0, count); return(longs.Cast <T>().ToArray()); case TypeCode.Single: var floats = new float[count]; Marshal.Copy(pBytes, floats, 0, count); return(floats.Cast <T>().ToArray()); case TypeCode.Double: var doubles = new double[count]; Marshal.Copy(pBytes, doubles, 0, count); return(doubles.Cast <T>().ToArray()); default: throw new ArgumentException(string.Format("Unsupported type argument supplied: {0}", typeof(T).Name)); } } finally { if (pBytes != IntPtr.Zero) { Marshal.FreeHGlobal(pBytes); } } }
static void Main(string[] args) { var inputPrefix = "inputs\\inp"; var outputPrefix = "inputs\\out"; for (var i = 0; i < 2; i++) { try { var inpArr = new char[10, 10]; var words = new List <string>(); var outArr = new char[10, 10]; using (StreamReader sr = new StreamReader(inputPrefix + i + ".txt")) { for (int j = 0; j < 10; j++) { var line = sr.ReadLine().ToCharArray(); for (int k = 0; k < line.Length; k++) { inpArr[j, k] = line[k]; } } foreach (var word in sr.ReadLine().Split(';')) { words.Add(word); } } using (StreamReader sr = new StreamReader(outputPrefix + i + ".txt")) { for (int j = 0; j < 10; j++) { var line = sr.ReadLine().ToCharArray(); for (int k = 0; k < line.Length; k++) { outArr[j, k] = line[k]; } } } var places = FindPlaces(inpArr, words); //Console.WriteLine("Places:"); //foreach (var place in places) // Console.WriteLine(place.Item1 + " " + place.Item2 + " " + place.Item3 + " " + place.Item4); var res = Solve(inpArr, words, places); if (!res.Item2) { Console.WriteLine("We couldn't find solution"); } var resArr = res.Item1; var equal = resArr.Rank == outArr.Rank && Enumerable.Range(0, resArr.Rank).All(dimension => resArr.GetLength(dimension) == outArr.GetLength(dimension)) && resArr.Cast <char>().SequenceEqual(outArr.Cast <char>()); Console.WriteLine("Test " + i); if (equal) { Console.WriteLine("OK"); } else { Console.WriteLine("Fail"); Console.WriteLine("Yours Proper"); PrintArray(resArr, outArr); } } catch (IOException e) { Console.WriteLine(e.Message); } } }