Fundamentals of Programming: Two-Dimensional Arrays

From Wikibooks, open books for an open world
Jump to: navigation, search

UNIT 1 - ⇑ Fundamentals of Programming ⇑

← Global and Local Variables Two-Dimensional Arrays User-defined data types →

You have already learnt how to use one dimensional arrays in your computer programs. You should be familiar with code such as:

Dim friends(6) As String
 
friends(0) = "Barry"
friends(1) = "Monica"
friends(2) = "Xiao"

This is great for storing lists of things, but what about if we want to simulate something more complex such as a game board or a map? Wouldn't it be great if we could use a two-dimensional array?

Most major programming languages allow you to use two-dimensional arrays. They work in much the same way as a one-dimensional array but allow you to specify a column index and a row index.

Treat a 2D array like a grid, the location of a cell is shown above

We can create the two-dimensional array shown above and assign values by doing the following:

Dim grid(4,4) As String
 
grid(0,3) = "A"
grid(3,2) = "B"
grid(1,4) = "C"
Console.Writeline("The content of 3,2 is:" & grid(3,2))
The code would also output the value B
Example: Two-Dimensional Arrays

Two-dimensional arrays are very useful and a good place to get started is to create your own version of the game Battleships with a 4 cell by 4 cell grid. See if you can win, or even break it!

We are modelling the following board using the two dimensional board variable:

0 1 2 3
0 x o o o
1 o o x o
2 o o o o
3 o o o o
Dim x, y As Integer
Dim board(3, 3) As Char
 
board(0, 0) = "x"
board(0, 1) = "o"
board(0, 2) = "o"
board(1, 0) = "o"
board(1, 1) = "o"
board(1, 2) = "x"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
board(2, 0) = "o"
board(2, 1) = "o"
board(2, 2) = "o"
 
For z = 1 To 3
	Console.WriteLine("This is guess number " & z)
 
	Console.Write("please insert you x location:")
	x = Console.ReadLine()
	Console.Write("please insert you y location:")
	y = Console.ReadLine()
	If board(x, y) = "x" Then
		Console.WriteLine("you win!")
	End If
Next
Exercise: Two-Dimensional Arrays
Declare an array to make a small checkers board of type char, 3 squares by 3 squares

Answer :

dim checkBoard(3,3) as char 'also checkBoard(2,2)
create a chequered pattern using b for black and w for white

Answer :

 checkBoard(1, 1) = "b"
 checkBoard(1, 2) = "w"
 checkBoard(1, 3) = "b"
 checkBoard(2, 1) = "w"
 checkBoard(2, 2) = "b"
 checkBoard(2, 3) = "w"
 checkBoard(3, 1) = "b"
 checkBoard(3, 2) = "w"
 checkBoard(3, 3) = "b"

A much smarter way is to use a loop, this will allow for you to quickly create an board of any size you wish. There is a question coming up that will want you to build this!

Write a sub routine to display this board (HINT: you need loops), that takes checkBoard as a parameter

Answer :

sub display(checkBoard())
for x = 1 to 3
   for y = 1 to 3
      console.write(checkBoard(x,y))
   Next
   console.writeline()
Next
Declare a chessBoard (8*8 squares), programmatically colour it in with b for black and w. You might want to look for a pattern in the colour assignments for the checker board above and make friends with the MOD function You might also go a little loopy trying to answer this question

Answer :

dim chessBoard(8,8) as char 'also chessBoard(7,7)
 
for x = 1 to 8
   for y = 1 to 8
      if (x + y) MOD 2 = 1 then
         chessBoard(x,y) = "w"
      else
         chessBoard(x,y) = "b"
      end if
   next
next
 
display(chessBoard()) ' using a slightly updated version of the subroutine display()

If you've done this you might want to get the program to print some massive boards, whatever floats your boat.

Using the following two-dimensional array, grid(4,4):
  • Write code to output the name CRAIG
  • Insert MARY on row 2 (the third row)
  • Overwite STEVE with SAM

CPT-arrays-2d-names.svg

Answer :

Console.Writeline(grid(3,0) & grid(3,1) & grid(3,2) & grid(3,3) & grid(3,4))
grid(2,0) = "M"
grid(2,1) = "A"
grid(2,2) = "R"
grid(2,3) = "Y"
 
grid(1,0) = "S"
grid(1,1) = "A" ' you could skip this
grid(1,2) = "M"
grid(1,3) = ""
grid(1,4) = ""

Noughts and Crosses[edit]

Another game you might play on a 2D grid is the popular game of noughts and crosses:

Game of tic-tac-toe, won by X

To do this we need to build a 3 by 3 grid:

Sub main()
    Dim board(3, 3) As Char
 
    board(1, 1) = "-"
    board(1, 2) = "-"
    board(1, 3) = "-"
    board(2, 1) = "-"
    board(2, 2) = "-"
    board(2, 3) = "-"
    board(3, 1) = "-"
    board(3, 2) = "-"
    board(3, 3) = "-"
 
  'main game function call to go here
end sub

Next we need a subroutine to display the grid, passing the board as a parameter

Sub display(ByVal b(,) As Char)
	For i = 0 To 3
		For j = 0 To 3
			Console.Write(b(i, j))
		Next
 
		Console.WriteLine()
	Next
End Sub

We need the ability to check whether the game has been won and who has won it. We'll do this by building a win check that returns true if the specified player has won, or false otherwise. We need to pass it some values to check, namely the board - b() and the player you are checking for - p. Both are passed byVal as we don't need to change them:

Function win(ByVal b(,) As Char, ByVal p As Char)
	If b(1, 1) = p And b(1, 2) = p And b(1, 3) = p Then 'first row check
		Console.WriteLine(p + " WINS!")
		Return True
	ElseIf b(2, 0) = p And b(2, 1) = p And b(2, 2) = p Then 'second row check
		Console.WriteLine(p + " WINS!")
		Return True
	Else
		Return False 'if the game hasn't been won
	End If
	' this needs more rules, it only has 2 at the moment and one of them doesn't work!  Could you use a loop instead?
End Function

It's a bit of a rubbish game so far, so we better let someone move:need the ability for players to play a move:

Sub move(ByRef b(,) As Char, ByVal p As Char)
	Dim x, y As Integer
	Dim move As String
	Console.WriteLine(p + " - make your move in the format: x,y")
	move = Console.ReadLine()
	x = move.Substring(0, 1)
	y = move.Substring(2, 1)
	If b(x, y) = "-" Then
		b(x, y) = p
		display(b)
	Else
		Console.WriteLine("Invalid move!  Miss a turn")
	End If
End Sub

We need to end the game in a draw if all the spaces have been taken

Function drawn(ByVal b(,) As Char)
	Dim c As Integer = 0 ' set a counter to keep track of how many spaces there are
	For i = 0 To 3
		For j = 0 To 3
			If b(i, j) = "-" Then
				c = c + 1
			End If
		Next
	Next
 
	If c = 9 Then
		Console.WriteLine("Draw, game over!")
		Return True
	Else
		Return False
	End If
End Function

Finally we'll bring everything together

Sub Main()
	'array declaration from earlier...   
 
	game(board)
	console.readline()
End Sub
 
Sub game(ByVal b(,) As Char)
	Dim togo As Char
	Do
		If togo = "x" Then
			togo = "o"
		Else
			togo = "x"
		End If
 
		move(b, togo)
		display(b)
	Loop While Not (win(b, togo)) And Not (drawn(b))
End Sub
Exercise: More Two-Dimensional arrays
Fix the program above so that an incorrect move allows the user to try again:
  Blank.svg Code Output
Down arrow Hexagonal Icon.svg

xxo
o--
---
x - make your move in the format: x,y
1,2
x - make your move in the format: x,y
1,2
x - make your move in the format: x,y

Answer :

sub move(byRef b() As Char, byVal p As Char)
  dim x,y as integer
  dim move as string
  Do 
     console.writeline(p + " - make your move in the format: x,y")
     move = console.readline()
     x = move.Substring(0, 1)
     y = move.Substring(2, 1)
  While  b(x + 1,y + 1) <> "-"
  b(x + 1,y + 1) = p
  display(byVal b())
end sub
Fix the program above so that is checks rows, columns and diagonals for a winning position. Try to keep your answer below 19 lines and 550 characters.

Answer :

function win(ByVal b(,) As Char, byVal p As Char)
  for x = 0 to 2
    if b(x,0) = p AND b(x,1) = p AND b(x,2) = p then 'check columns
     console.writeline(p + " WINS!")
     return true
  next
  for y = 0 to 2
    if b(0,y) = p AND b(1,y) = p AND b(2,y) = p then 'check rows
     console.writeline(p + " WINS!")
     return true
  next
  if b(0,0) = p AND b(1,1) = p AND b(2,2) = p then 'second row check
     console.writeline(p + " WINS!")
     return true
  end if
  if b(0,2) = p AND b(1,1) = p AND b(2,0) = p then 'second row check
     console.writeline(p + " WINS!")
     return true
  end if
  return false 'if the game hasn't been won
end function
Extension: Many more dimensional arrays

You have met one and two dimensional arrays so far, but this isn't the limit to the number of dimensions that you can use. For example you might want to model a three dimensional world by using a 3D array

Dim space(2, 2, 2) As integer ' 3 dimensional array