Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Convert 1D array to 2D array C#


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
11 replies to this topic

#1 FantasyVII   Members   -  Reputation: 330

Like
0Likes
Like

Posted 20 September 2012 - 01:13 PM

Hello everyone.

I have the following file that looks like this:-
1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,
16,17,18,19,20,21,

now I'm reading it and I stored all the data into 1D string array. Then I parse that 1D string array to 1D Int array. However I need to copy the data to 2D array. I have been trying to do it but I can't seem to get my head around it.

Here is my code
class Program
	{
		static void Main(string[] args)
		{
			string buffer;
			string[] map = new string[100];
			int[] mapint = new int[100];
			buffer = File.ReadAllText("D:/123.txt");
			buffer = buffer.Replace("\r", string.Empty).Replace(" ", string.Empty);
			map = buffer.Split(',');
			for (int i = 0; i < 20; i++)
			{
				mapint[i] = Convert.ToInt32(map[i]);
				Console.Write(mapint[i] + " ");
			}
			Console.ReadKey();
		}
	}
so i want to do something like this

for(int x = 0; x < row; x++)
	 for(int y = 0; y < column; y++)
		  map[x, y] = mapint[x];

you know store the first row when y = 0; second row when y = 1; etc...

Sponsor:

#2 Telastyn   Crossbones+   -  Reputation: 3730

Like
0Likes
Like

Posted 20 September 2012 - 01:30 PM

Whichever variable you want to be a 2d array needs to be declared as such. I honestly don't remember the syntax; I never use arrays.

#3 Arthur Souza   Members   -  Reputation: 1419

Like
2Likes
Like

Posted 20 September 2012 - 01:33 PM

When doing this, I store the Width and Height of the 2D map together with the 1D array, so I have everything I need when parsing it back.

Converting from 2D to 1D is easy, since you just concatenate all values. Now, when parsing back, you must know how many columns a line has. Unless all of your maps are of a fixed size, lets say, 10x10. You will have to store this data.

After that, it's easy:

Map = new int[Height, Width];
for (int i = 0; i < Width; i++)
for (int j = 0; j < Height; j++)
  Map[j, i] = strArray[j * Width + i];


If you don't store this data and all of your values are of fixed size, its even easier, just replace the values on the above example for the fixed values.

example:

You have an array like this, which is composed of 100 items. All of your maps are 10x10, so you'll always have 100 items on the 1d array. To parse this back to 2D, all you gotta do is

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Map = new int[10, 10];
for (int x = 0; x < 10; x++)
	 for (int i = 0; y < 10; y++)
	   Map[y, x] = strArray[y * 10 + x];

Edited by Arthur Souza, 20 September 2012 - 01:37 PM.

A.

Lotus - Action RPG In development http://www.gamedev.n...die-rpg-engine/ |
Personal blog In Portuguese: lotuzgames.wordpress.com |


#4 yewbie   Members   -  Reputation: 665

Like
0Likes
Like

Posted 20 September 2012 - 01:35 PM

I always hated when someone replied to me like this, so please take this as a suggestion and not a criticism!
I think what your doing may not be the best way to save and load your map data.

But to create a 2d array you do the following:

int[,] MapData = new int[100, 100];


I would suggest saving your map cordinates along with the tile info, without over complicating things you could just parse the first int as X the second int as Y and the 3rd int as the tile number.

#5 FantasyVII   Members   -  Reputation: 330

Like
0Likes
Like

Posted 20 September 2012 - 01:37 PM

well I want mapint[i] to be 2d array.

Here how i want it. for example the first 9 numbers in mapint[] to be copied to int Map[0, 0], Map[1, 0], Map[2, 0]. etc...

then from element 9, 10 , 11, to 20 int mapint[] to be copied to Map[0, 1], Map[1, 1], Map[2, 1] etc...

#6 FantasyVII   Members   -  Reputation: 330

Like
1Likes
Like

Posted 20 September 2012 - 01:40 PM

I always hated when someone replied to me like this, so please take this as a suggestion and not a criticism!
I think what your doing may not be the best way to save and load your map data.
But to create a 2d array you do the following:

int[,] MapData = new int[100, 100];
I would suggest saving your map cordinates along with the tile info, without over complicating things you could just parse the first int as X the second int as Y and the 3rd int as the tile number.


I know how to create a 2D array. I know that i need to do this
int[,] MapData = new int[100, 100];

I know what you mean and I have tried your way long time ago and it was very messy and i didn't really like it. I thought my way was cleaner. I don't know. I Just prefer my way Posted Image

thank you anyways.

When doing this, I store the Width and Height of the 2D map together with the 1D array, so I have everything I need when parsing it back.

Converting from 2D to 1D is easy, since you just concatenate all values. Now, when parsing back, you must know how many columns a line has. Unless all of your maps are of a fixed size, lets say, 10x10. You will have to store this data.

After that, it's easy:

Map = new int[Height, Width];
for (int i = 0; i < Width; i++)
for (int j = 0; j < Height; j++)
  Map[j, i] = strArray[j * Width + i];


If you don't store this data and all of your values are of fixed size, its even easier, just replace the values on the above example for the fixed values.

example:

You have an array like this, which is composed of 100 items. All of your maps are 10x10, so you'll always have 100 items on the 1d array. To parse this back to 2D, all you gotta do is

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,

Map = new int[10, 10];
for (int x = 0; x < 10; x++)
	 for (int i = 0; y < 10; y++)
	   Map[y, x] = strArray[y * 10 + x];


that looks like what i want. i'll give it a try. thx

Edited by FantasyVII, 20 September 2012 - 02:00 PM.


#7 FantasyVII   Members   -  Reputation: 330

Like
1Likes
Like

Posted 20 September 2012 - 01:53 PM


thank you very much it worked perfectly.

but can I ask you one more favor.

can you explain this line of code?

Map[y, x] = strArray[y * 10 + x];

I can't understand it. Why did you do [y * 10 + x] ?!!!


Here is the full code if anyone is interested.

File
1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,16,17,18,
19,20,21,22,23,24,25,26,27,
28,29,30,31,32,33,34,35,36,

class Program
	{
		static void Main(string[] args)
		{
			string buffer;


			string[] map = new string[100];

			int[] mapint = new int[100];

			int[,] Map = new int[10, 10];

			buffer = File.ReadAllText("D:/123.txt");


			buffer = buffer.Replace("\r", string.Empty).Replace(" ", string.Empty);

			map = buffer.Split(',');

			for (int i = 0; i < 36; i++)
				mapint[i] = Convert.ToInt32(map[i]);
		  
			for (int x = 0; x < 10; x++)
				for (int y = 0; y < 10; y++)
					Map[y, x] = mapint[y * 10 + x];

			for (int x = 0; x < 10; x++)
			{
				Console.WriteLine();
				for (int y = 0; y < 10; y++)
				{
					Console.Write(Map[x, y] + " ");
				}
			}
			Console.ReadKey();
		}
	}

Edited by FantasyVII, 20 September 2012 - 01:54 PM.


#8 Arthur Souza   Members   -  Reputation: 1419

Like
2Likes
Like

Posted 20 September 2012 - 02:00 PM

Sure thing!

Lets review the process of getting stuff back from the 1d array to the 2d array.

Each line has 10 items. So, for the first line [index 0] you just get the first 10 items. For the second line [index 1], you will get the second group of 10 items after the first 10 items on the 1d array.

Do you follow? This translates to, the items you want to get from the 1d array, start at LineIndex * ValuesPerLine, which means Y * 10.

Ok, so, the second line starts at LineIndex * ValuesPerLine, now to get the exact column you want, you just add its index. LineIndex * ValuesPerLine + ColumnIndex

After that, you add X, the current column index. Understood?

[X, X, X, X, X, X, X, X, X, X] Becomes [X, X, X, X, X, X, X, X, X, X][X, X, X, X, X, X, X, X, X, X]
[X, X, X, X, X, X, X, X, X, X]

Edited by Arthur Souza, 20 September 2012 - 02:03 PM.

A.

Lotus - Action RPG In development http://www.gamedev.n...die-rpg-engine/ |
Personal blog In Portuguese: lotuzgames.wordpress.com |


#9 FantasyVII   Members   -  Reputation: 330

Like
1Likes
Like

Posted 20 September 2012 - 02:06 PM

Sure thing!

Lets review the process of getting stuff back from the 1d array to the 2d array.

Each line has 10 items. So, for the first line [index 0] you just get the first 10 items. For the second line [index 1], you will get the second group of 10 items after the first 10 items on the 1d array.

Do you follow? This translates to, the items you want to get from the 1d array, start at LineIndex * ValuesPerLine, which means Y * 10.

Ok, so, the second line starts at LineIndex * ValuesPerLine, now to get the exact column you want, you just add its index. LineIndex * ValuesPerLine + ColumnIndex

After that, you add X, the current column index. Understood?

[X, X, X, X, X, X, X, X, X, X] Becomes [X, X, X, X, X, X, X, X, X, X][X, X, X, X, X, X, X, X, X, X]
[X, X, X, X, X, X, X, X, X, X]


oooh ok now I get it.

thank you very much :D

I really appreciate it.

#10 MarkS   Prime Members   -  Reputation: 884

Like
0Likes
Like

Posted 20 September 2012 - 04:15 PM

...snip...


In fact, using this method removes the need to use 2D arrays. You can view a 2D array as being arranged in memory as as contiguous sequence of 1D arrays.

#11 yewbie   Members   -  Reputation: 665

Like
1Likes
Like

Posted 20 September 2012 - 04:48 PM

Feel free to play around with this and learn how it works but this is a very basic example of writing and reading your map data from a file written in binary, I also wouldn't call myself an amazing programmer but this works.

    public class MapLocation
	{
		public int TileNumber = 0;
		public bool Blocked = false; //if the tile itself is blocked
	}
	public class MapManager
	{
		MapLocation[,] MapData = new MapLocation[100, 100]; //create a 2d Array with our map class
	  
		// ////////////////////////////////////////////////////////////////////////////////////////////////////////
		public int GetTileAtLocation(int X, int Y)
		{
			//check bounds
			if (X < 0 || X > 100 || Y < 0 || Y > 100)
			{
				return 0;
			}
			else //its in bounds of our array
			{
				return MapData[X, Y].TileNumber;
			}
		}
		// ////////////////////////////////////////////////////////////////////////////////////////////////////////
		public void SaveMap()
		{
			using (FileStream stream = new FileStream("Map.dat", FileMode.Create))  //create our file
			{
				using (BinaryWriter writer1 = new BinaryWriter(stream)) //create writer
				{
					//write header
					writer1.Write(1000); //File Version increment this anytime you change data below
				  
					for (int x = 0; x < 100; x++) //loop through all of our tiles
					{
						for (int y = 0; y < 100; y++)
						{
							writer1.Write(MapData[x,y].TileNumber); //write tile number
							writer1.Write(MapData[x,y].Blocked); //write blocked flag
						}
					}
				}
			 }
		}//End SaveMap()
		// ////////////////////////////////////////////////////////////////////////////////////////////////////////
		public void LoadMap()
		{
			if (!File.Exists("Map.dat"))
			{
				//file does not exist return
				Console.Write("File Does not Exist\n");
				return;
			}

			using (FileStream stream = new FileStream("Map.dat", FileMode.Open))
			{
				using (BinaryReader reader = new BinaryReader(stream))
				{///------------------------------------------------------------------------------------------------------------------------
					//Read Header
					int ThisFileVersion = reader.ReadInt32(); //pull our version from the file and make sure it matches what we think we are reading
					//Check our file version
					if (ThisFileVersion != 1000)
					{
						Console.Write("Exp File Version Mismatch\n");
						return;
					}
					for (int x = 0; x < 100; x++) //loop through all of our tiles
					{
						for (int y = 0; y < 100; y++)
						{
							MapData[x,y].TileNumber = reader.ReadInt32();
							MapData[x,y].Blocked = reader.ReadBoolean();
						}
					}
				}
			}
		}//end LoadMap()

	}//end MapManager


#12 FantasyVII   Members   -  Reputation: 330

Like
1Likes
Like

Posted 21 September 2012 - 12:33 AM

Feel free to play around with this and learn how it works but this is a very basic example of writing and reading your map data from a file written in binary, I also wouldn't call myself an amazing programmer but this works.

	public class MapLocation
	{
		public int TileNumber = 0;
		public bool Blocked = false; //if the tile itself is blocked
	}
	public class MapManager
	{
		MapLocation[,] MapData = new MapLocation[100, 100]; //create a 2d Array with our map class
	  
		// ////////////////////////////////////////////////////////////////////////////////////////////////////////
		public int GetTileAtLocation(int X, int Y)
		{
			//check bounds
			if (X < 0 || X > 100 || Y < 0 || Y > 100)
			{
				return 0;
			}
			else //its in bounds of our array
			{
				return MapData[X, Y].TileNumber;
			}
		}
		// ////////////////////////////////////////////////////////////////////////////////////////////////////////
		public void SaveMap()
		{
			using (FileStream stream = new FileStream("Map.dat", FileMode.Create))  //create our file
			{
				using (BinaryWriter writer1 = new BinaryWriter(stream)) //create writer
				{
					//write header
					writer1.Write(1000); //File Version increment this anytime you change data below
				  
					for (int x = 0; x < 100; x++) //loop through all of our tiles
					{
						for (int y = 0; y < 100; y++)
						{
							writer1.Write(MapData[x,y].TileNumber); //write tile number
							writer1.Write(MapData[x,y].Blocked); //write blocked flag
						}
					}
				}
			 }
		}//End SaveMap()
		// ////////////////////////////////////////////////////////////////////////////////////////////////////////
		public void LoadMap()
		{
			if (!File.Exists("Map.dat"))
			{
				//file does not exist return
				Console.Write("File Does not Exist\n");
				return;
			}

			using (FileStream stream = new FileStream("Map.dat", FileMode.Open))
			{
				using (BinaryReader reader = new BinaryReader(stream))
				{///------------------------------------------------------------------------------------------------------------------------
					//Read Header
					int ThisFileVersion = reader.ReadInt32(); //pull our version from the file and make sure it matches what we think we are reading
					//Check our file version
					if (ThisFileVersion != 1000)
					{
						Console.Write("Exp File Version Mismatch\n");
						return;
					}
					for (int x = 0; x < 100; x++) //loop through all of our tiles
					{
						for (int y = 0; y < 100; y++)
						{
							MapData[x,y].TileNumber = reader.ReadInt32();
							MapData[x,y].Blocked = reader.ReadBoolean();
						}
					}
				}
			}
		}//end LoadMap()

	}//end MapManager


I assume the save method will produce this file in binary:
0false 1false 2true 3false 2true
etc...
right?

anyways your code looks really good and believe it or not I learned 2 thing by looking at your good.

1- what and how and when to use "using" statement.
2- garbage collection. Posted Image

The reason I want my Map File to look like this is because it easier to place tiles according to the file:-

1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,2,1,1,1,1,1,
1,1,1,1,1,2,1,1,1,1,1,
1,1,1,1,1,2,1,1,1,1,1,
1,1,1,1,1,2,2,2,2,2,2,
1,1,1,1,1,1,1,1,1,1,2,
1,1,1,1,1,1,1,1,1,1,2,
1,1,1,1,1,1,1,1,1,1,2,
2,2,2,2,2,2,2,2,2,2,2,


so I would do something like this

MapX = 100, MapY = 100;
TileX = 32, TileY = 32;

int[,] map = new int[100, 100];

GrassID = 1;
StoneID = 2;

			for (int x = 0; x < MapX; x++)
			{
				for (int y = 0; y < MapY; y++)
				{
					TilePosition.X = (float)x * TileX;
					TilePosition.Y = (float)y * TileY;

					if (map[y, x] == this.GrassID)
					{
						spriteBatch.Draw(this.GrassTile, TilePosition + ScreenScroll.ScreenOffset, Color.White);
					}

					if (map[y, x] == this.StoneID)
					{
						spriteBatch.Draw(this.StoneTile, TilePosition + ScreenScroll.ScreenOffset, Color.White);
					}


so if there is number 1 in the array it will take it position which lets say will be at map[1, 2]. so 1*32 = 32 and 2*32 = 64. So the tile will be placed at position(32, 64).

anyways I like your code and I'll actually use some parts of it to put in my code.

Thank you very much :)

Edited by FantasyVII, 21 September 2012 - 12:34 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS