Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have 35 Tile objects and I'm trying to put them into a 2D array (and list) but I keep getting an IndexOutofRange error when populating the array. The code I'm using is:
private Tile[,] AllTiles = new Tile[5,7];
private List<Tile> EmptyTiles = new List<Tile>();
// Use this for initialization
void Start () {
Tile[] AllTilesOneDim = GameObject.FindObjectsOfType<Tile> ();
foreach (Tile t in AllTilesOneDim) {
// Fill 2D Array AllTiles
AllTiles [t.indRow, t.indCol] = t;
// Fill List with all tiles
EmptyTiles.Add (t);
}
}
I should note that each Tile object contains an int for indRow between 0-4 and an int for indCol between 0-6.
Try adding some defensive code to check the range before adding the tile to the 2D array. Like:
int rows = AllTiles.GetLength(0);
int cols = AllTiles.GetLength(1);
int indRow = 0;
int indCol = 0;
foreach (Tile t in AllTilesOneDim) {
indRow = t.indRow;
indCol = t.indCol;
if (indRow >= 0 && indRow < rows
&& indCol >= 0 && indCol < cols)
{
// Fill 2D Array AllTiles
AllTiles[indRow, indCol] = t;
}
}
Use the debugger to step into this path and see what you find. The indRow and indCol values must sometimes be outside of your specified ranges of 5 (0 to 4) and 7 (0 to 6). Remember indexes are zero based and the Length returns the total number of items so we must subtract one to find the correct index (or use "index less than rows or cols" like I did in the if statement).
GetLength() Method:
https://msdn.microsoft.com/en-us/library/system.array.getlength.aspx
https://stackoverflow.com/a/4260228/8094831
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to make a Sudoku game in Unity3D but I'm currently stuck on the logic behind the game. (checking if all the numbers in the same subgrid, row and column are different)
I have been able to get a script that generates the whole grid running, both for a 2x2, 2x3 and a 3x3 level. The part that I am stuck on is making the 2D Array to hold the selected values for all subgrids. I can also provide the full GenerateGrid script if it's needed, but any help apart from that would be of help.
(Note: I have tried my best to research as much as I can about this, but none of the stuff I found online was about a Unity3D version of the game, only 2D ones)
Thanks!
Something like this? The board is a 9x9 grid. Skip the multidimensional syntax as it just complicates things (in my opinion).
(Pseudocode - I haven't tried compiling this.)
int[] board = new int[9*9];
/// note that coordinates are zero-based. So, rows, columns. etc. go from 0..8, not 1..9
int getCell(int x, int y)
{
return board[y * 9 + x];
}
bool colIsValid(int x)
{
var digitsFound = new bool[9];
for(int y=0; y < 9; ++y)
{
var cellValue = getCell(x,y);
if (cellValue > 0)
{
if (digitsFound[cellValue])
return false;
digits[cellValue] = true;
}
}
return true;
}
bool rowIsValid(int y)
{
var digitsFound = new bool[9];
for(int x=0; x < 9; ++x)
{
var cellValue = getCell(x,y);
if (cellValue > 0)
{
if (digitsFound[cellValue])
return false;
digits[cellValue] = true;
}
}
return true;
}
// determine if the 3x3 subgrid containing cell (x,y) is valid.
bool subGridIsValid(int cellX, int cellY)
{
var minX = (cellX / 3) * 3;
var maxX = minX + 3;
var minY = (cellY / 3) * 3;
var maxY = minY + 3;
var digitsFound = new bool[9];
for(var j=minY; j < maxY; ++j)
{
for(var i = minX; i < maxX; ++i)
{
var cellValue = getCell(i,j);
if (cellValue > 0)
{
if (digitsFound[cellValue])
return false;
digitsFound[cellValue] = true;
}
}
}
return true;
}
You can represent yourself a Sudoku as a grid (with rows and columns). Each grid cell is itself a subgrid (with sub-rows and sub-columns)
To check if the user solved the Sudoku you have 3 conditions
there is no duplicate number in a subgrid itself
there is no duplicate number in a same sub-row for every cell on the same row
there is no duplicate number in a same sub-column for every cell on the same column
From there we can begin to work. I would recommend to use two sets of bidimensionnal arrays. One for the main grid and a second for each sub-grids
So basically...your grid declaration may looks like this int[,][,] sudoku and sudoku[1,2][3,4] will access the row 1, column 2, sub-row 3, sub-column 4 if that makes sense
So to check game conditions:
test every sub-cells of sudoku[1,2][i,j] to make sure there is no duplicated numbers in the grid cell [1,2]
test every sub-cells for sudoku[1,i][2,j] to make sure there is no duplicated number in the sub-column 2 of the column 1
test every sub-cells for sudoku[i,1][j,2] to make sure there is no duplicated number in the sub-row 2 of the row 1
You should find a better optimisation to check the grid rather than brute force it sub-cell by sub-cell but I leave it up to you.
Hope that helped ;)
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 1 year ago.
I am trying to assign values to a 2D array using 2 for loops. Here is my code:
void Test()
{
int[,] grid = { { 0 } };
for (int x = 0; x <= 7; x++)
{
for (int y = 0; y <= 7; y++)
{
grid[x, y] = x * y;
}
}
}
However, I get a System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' after the for loops. What is causing this and how can I fix it?
As stated in the comments: you are initializing the array as a 1x1 array but you are trying to access its elements from 0-7 in both dimensions. You can simply initialize the array as int[,] grid = new int[8,8]; and then access the elements the way you are doing it right now.
In case you need it: C# initializes int arrays with the value 0 (since you are explicitly intializing it with 0).
For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have challenge to solve Sales by Match problem using c# without use List collection ?
*Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are N =7 socks with colors ar=[1,2,1,2,1,3,2] There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2 .*
you can try this code
static int sockMerchant(int n, int[] ar) {
int matchingPairsCount= 0 ;
int[] arr =new int[n];
var ix=0;
for (int i = 0 ; i< ar.Length ; i++)
{
int countPairs = 0 ;
for(int j = 0 ;j< ar.Length ;j++)
{
if(ar[i] == ar[j] && i<j&& (!arr.Contains(i)|| i==0))
{
arr[ix]=j;
ix++;
matchingPairs = matchingPairs + 1 ;
break;
}
}
}
return matchingPairsCount;
}
You can use it using the following code
var ar = new int[] { 1,2,1,2,1,3,2 };
ar.GroupBy( g => g ).Sum( g => Math.Floor( g.Count() / 2.0 ) );
It groups all the items in the array first, and then sums up all pairs. You can try it here
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a clump of data pulled from an SQL database and stored inside a list:
as you can see in the image there are a few data columns. What I'm trying to do is out of the 69 items I want to find the one whose Rate_Price is closest to 0. It can be a negative or a positive.
Current Code:
var data = _rateManager.Get30Year("30-Year Fixed Rate");
Here's a console app that adds a load of -ive and +ive integers randomly to a list and then sorts the list producing the one that's closest to 0:
class Program
{
static void Main(string[] args)
{
var random = new Random(DateTime.Now.Millisecond);
var values = new List<int>();
for (int i = 0; i < 100; i++)
{
values.Add(random.Next(-1000, 1000));
}
foreach (var item in values.OrderBy(i => Math.Abs(i)))
{
Console.WriteLine($"{item}, ");
}
Console.WriteLine("The closest to 0 therefore is:");
Console.WriteLine(values.OrderBy(i => Math.Abs(i)).First());
Console.Read();
}
}
The key bit here is:
values.OrderBy(i => Math.Abs(i)).First()
Or in case of your example:
data.OrderBy(i => Math.Abs(i.Rate_Price)).First();
Or
data.First(i => Math.Abs(i.Rate_Price));
That said in your example i am guessing all Rate_Price will be a positive number so to get the first all you need is:
data.OrderBy(i => i.Rate_Price).First();
in sql (if you can)
select * from thingies order by (abs(rate)) asc limit 1
If you can use SQL, try select * from thingies where RATE_PRICE = (select MIN(RATE_PRICE) from thingies where RATE_PRICE > 0
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have this code :
for(int i=0;i<???;i++)
{
...
}
tb.SetWidths(new int[] { 50, 50, 50,.... });
The problem is:
The amout of array elemens must be equal to "i"
I also want to set the value to all these elements to 50
How can i do that?
Tb is an object from itextsharp, i'm using it to draw tables on pdf files
I guess something like that would work for you? (https://stackoverflow.com/a/34379619/986160)
if count is random you can do:
Random rand = new Random();
int count = rand.Next(1, 101); // creates a number between 1 and 100
( 50 is the fixed value for all 'count' elements)
int[] array = Enumerable
.Repeat(50, count)
.ToArray();
then you can do:
tb.SetWidths(array);
It seems like you've put little to no effort into this exercise.
By simply Googling "c# define array of size" I found the following code:
int i = random number;
int[] myArray = new int [i];
Next, in order to populate the array with a certain integer, you simply loop through it:
for(int x = 0; x < myArray.Length; x++){
myArray[x] = 50;
}