4 ms·
Out of curiosity, here's a bit of C# to do it. This randomly populates a 10x10 grid then looks for a random target in a randomly located 3x3 sub-grid. As per
by kcartlidge 2y ago
Out of curiosity, here's a bit of C# to do it. This randomly populates a 10x10 grid then looks for a random target in a randomly located 3x3 sub-grid.
As per the question I've ignored error conditions, but using the simple expedient in this case of positioning the 3x3's top left within the first 8x8 not the full 10x10.
Example output is underneath.
// Make and fill the grid.
var r = new Random();
var grid = new int[10, 10];
for (var y = 0; y < 10; y++)
for (var x = 0; x < 10; x++)
grid[x, y] = r.Next(10);
// Draw the grid for reference.
Console.WriteLine();
Console.WriteLine(" 0 1 2 3 4 5 6 7 8 9");
Console.WriteLine();
for (var y = 0; y < 10; y++)
{
Console.Write($"{y} ");
for (var x = 0; x < 10; x++)
Console.Write(grid[x, y] + " ");
Console.WriteLine();
}
Console.WriteLine();
// Random starting point and target.
var tlx = r.Next(8);
var tly = r.Next(8);
var target = r.Next(10);
// Extract the 3x3 sub-grid and "[ ]" any matches.
Console.WriteLine($"Looking for {target} in 3x3 grid at {tlx},{tly}");
Console.WriteLine();
for (var dy = 0; dy < 3; dy++)
{
for (var dx = 0; dx < 3; dx++)
{
var ax = tlx + dx;
var ay = tly + dy;
var v = grid[ax, ay];
if (v == target) Console.Write($"[{v}]");
else Console.Write($" {v} ");
}
Console.WriteLine();
}
Console.WriteLine();
Example output:
0 1 2 3 4 5 6 7 8 9
0 1 2 5 4 1 8 0 2 8 5
1 4 2 2 5 8 4 4 0 4 8
2 7 1 8 2 5 6 3 6 3 6
3 8 7 3 2 4 6 5 9 6 2
4 6 3 4 2 9 7 4 7 6 1
5 1 4 2 3 8 3 2 4 3 3
6 0 6 6 5 1 4 7 3 4 9
7 2 0 6 9 9 9 3 9 1 7
8 1 6 5 8 3 8 9 8 3 4
9 0 8 7 9 5 4 0 7 0 3
Looking for 5 in 3x3 grid at 2,6
6 [5] 1
6 9 9
[5] 8 3
As others have said elsewhere this could use a one-dimensional array but as we know upfront what the constraints are I've gone for the clarity of the two-dimensional. This is said to be the very first mistake everyone makes in graphics programming - but nothing in the question says it is for use in graphics, so being an interview question I went for clarity.
Similarly there's the possible use of a ternary, less memory allocation, and tighter code, but again in this situation I'd go for readability.
There may also be edge cases not covered; this was a 10 minute hack (as it looked fun) and isn't exhaustively tested.