0% found this document useful (0 votes)
26 views43 pages

ICS 4U1 - Unit #3 - Two Dimensional Arrays - Dec 7th

This document discusses multidimensional arrays and introduces two-dimensional arrays. It begins with a review of one-dimensional arrays and then explains that two-dimensional arrays allow storing data in a matrix format like a game board. It provides an example of implementing tic-tac-toe using a one-dimensional array and explains how to transition to a two-dimensional array implementation. Finally, it discusses when two-dimensional arrays are useful and how to declare and initialize them in Java.

Uploaded by

vexiox222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views43 pages

ICS 4U1 - Unit #3 - Two Dimensional Arrays - Dec 7th

This document discusses multidimensional arrays and introduces two-dimensional arrays. It begins with a review of one-dimensional arrays and then explains that two-dimensional arrays allow storing data in a matrix format like a game board. It provides an example of implementing tic-tac-toe using a one-dimensional array and explains how to transition to a two-dimensional array implementation. Finally, it discusses when two-dimensional arrays are useful and how to declare and initialize them in Java.

Uploaded by

vexiox222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Everyone wants a-raise J

Multidimensional Arrays
Revisiting One Dimensional Arrays
Two Dimensional Arrays Fixed Arrays
and
Dynamic One Dimensional and Two Dimensional Arrays
What are we doing now?
• Earlier this year (and late last year), you were introduced to the concept of one-dimensional arrays.
• We started with fixed size arrays and were not allowed to grow past that size. We then proceeded to create
methods that would permit the arrays to grow dynamically at run time. We will extend this further in this
unit!
• One dimensional arrays are great to store a list of numbers or objects, but what if we want to store a matrix
of numbers or objects ? What is a matrix you ask?
• A matrix is simply a representation of rows and columns of some objects or numeric values. Think of a
classroom that is organized with desks that are lined up in rows and columns. That is a matrix.
• Many problems lend themselves to storing data in a matrix rather than a one-dimensional array. Think of
some common board games – battleship, chess, tic-tac-toe, connect four. If you were to write a computer
program to store the state of the board and act upon it you would use a two-dimensional array in your
solutions.
• A rite of passage as a student learning to write computer programs is to code the game Tic-Tac-Toe. In this
unit, we will be doing so first with a one-dimensional implementation since you have not done so in the past
and will also infuse object-oriented programming techniques in our solution. Then we see how a two-
dimensional array solves the problem a bit more elegantly and naturally.
One Dimensional Implementation of Tic Tac Toe
• Let’s start with a one-dimensional String array:

• Using a flat one-dimensional representation of something that is clearly two-


dimensional requires some creativity in our coding techniques … any why it is a
necessary rite of passage J.
• The first three entries of the array are used to store the first row of the board, the next
three entries of the array to store the second row, and the last three entries to store the last
row.
• The code on the right can be used to setup the board that is shown on the right.
• We are now faced with a challenge – how do we need a transformational map that will
allow us to access the correct position in the array given a row and column, and back again.
But how? Think for a minute …
• It may be helpful to assign a row and column number to each position on the board starting
with row 0, then row 1, then row 2 (horizontally) and columns with column 0, column 1 and
column 2.
• The ”lonely” O in the bottom right corner is in row 2, column 2 while its friend is in row 0, column 1.
• Similarly the ”X” in the top right corner is in row 0, column 2.
• Integer division and our modulus operator base 3 come to the rescue here in our
transformational map allowing ups to convert row and column numbers to array entry
index, and index to row and column number.
• Let that ”simmer” for a moment how to go about accomplishing this transformational map.
Now what about Battleship ?
• Think for a moment how you would implement a Battleship game
board using a one-dimensional array.
• We would use integer division and modulus base ten to produce
our transformational map to represent this two-dimensional
entity with a one-dimensional array.
• Our solution of course will also involve OOP techniques.
• Square would contain all the pertinent info about that spot such as
occupied, whether a “shot” has been taken in that spot, and so forth.
• What is important is that the Square class wouldn’t have much more in its
implementation other than a few getters/setters for these instance
variables.
• Next, create a Ship class that could be used to keep track of which ships
are currently sunk, how many hits, the vertical or horizontal orientation,
and the size of the ship.
• Next, create a GameBoard class that uses the one-dimensional array of
type Square, and the Ship instances. It would provide functionality to
place the ships, check for hits etc.
• Next, you code your Main class with the mechanics of the game and
provides the I/O with the user.
• Now we make a second GameBoard for the other player J
• You have until the end of the period to get the game working. Kidding.
One-dimensional Array of Square
• Now that you coded the entire game of Battleship using an OOP approach (in
your mind), lets backtrack and go back to Tic-Tac-Toe since the game is much
easier to implement.
• Using a similar OOP approach that you used when coding your Battleship
game, we start by creating an array of type Square.
Class GameBoard

Class Square - gameboard: Array of Square


+GameBoard()
-isOccupied: Boolean -initializeBoard():void
-value: String
+clearBoard():void
+Square() +setMove(move: String, row int, col int): void
+setSquare(value:String):void +checkWinner(value:String):String
-initializeSquare():void -checkHorizontal(value:String):Boolean
+getSquare():String -checkVertical(value:String): Boolean
+isEmpty():Boolean -checkDiagonal(value:String):Boolean
+toString:String +toString():String
-setOccupied():void -checkValue(int value):boolean
Coded classes … first Square

If we were to create a Square class for the game


Battleship, it would be very similar.

The setSquare method would change slightly, as we


would probably need to add another field to
indicate whether a shot has been taken on this
square and possibility its result.

If you need a “project” to do on the side see if you


can implement Battleship using an OOP design.
Optional of course, but better than watching
countless hours of TV. J
Coded classes … now GameBoard
Now what?
• With those two classes in written, now all one needs to do is create a Main class
with your main() method.
• You would need to write the code to prompt the user which row and column to place their
mark, and code to “alternate” turns between two players.
• Alternatively you could have a computer play against you.
• Use your Utils class to help you ensure valid input when prompting the user for a row and
column number.
• Don’t forget, that before a move is recorded, you would check if the Square is occupied, and
change the state of the Square instance as needed.
• The game is ”over” when a winner emerges, or 9 moves have occurred.
• The game mechanics described above amount to under 100 lines of code at this
point if you properly use the classes provided.
• This is your homework … Copy and paste the classes from
https://onlinegdb.com/fb1FaVfKD into a new Eclipse project called Tic-Tac-Toe.
Play Tic-Tac-Toe ?
• Tic-Tac-Toe in action using our OOP implementation. Link here:
https://onlinegdb.com/nfUA602r6
I can almost taste the
victory cookie. I move to
row 1, column 1!
Ha ha. I win!
Two Dimensions anyone?
Sure! I will have … length and width?
NO wait … Rows and donuts …
NO … donuts and columns …
I got it … rows and columns!
Let’s leave that for a minute …
• Our game is functional at this point using a one-dimensional array
implementation. Shortly, we will revisit the game and update our code to use
a two-dimensional array!
• But first we need to learn how a two-dimensional array works …
• After that, our GameBoard class will need a few minor tweaks, and more
importantly, if you have coded your Main class (with the main() method)
correctly following the principles of encapsulation and abstraction the
transition to a fully encapsulated implementation of the GameBoard class will
be completely seamless!
• This is exciting! I can’t wait to show you. But not just yet ..
When do we use a two-dimensional Array?
• We use a two-dimensional array when the data to be stored lends itself to a
row and column organization.
• Like one-dimensional arrays, two-dimensional arrays in Java require that all
the entries are of the same type! In Python you most likely worked with
entries of a one-dimensional array consisting of mixed data types such as
[“Cookie Monster”, 12.4,”Elmo”,17,1]. This is not permitted in Java.
• If you need to have a combination of data types, then we simply create an
array of objects. Each entry in the array is an instance of that object, and
each instance has instance variables capable of storing String, int or double
(or even other Classes) as required.
How do we declare 2D arrays? How are they setup?
• Internally, Java stores two dimensional arrays as an array of arrays.
• Here is how you would syntactically create a two-dimensional array of
integers with five rows and four columns:

• This statement is equivalent to three separate


steps:

Super important:
Initializes to default values as in
previous unit. Check out the
following code here:
https://onlinegdb.com/XMc56FXhE
Special note …
• When you initially declare a 2D array using the keyword new
• You must always specify the first dimension!

• You do not need to specify the second dimension

• If you are creating a 3D array, you do not need to specify the second or third
dimension.
• If you know both dimensions that of course is ideal. Just specify them when
creating the array.
• Do NOT worry about the 2D array growing, as we will handle that with a
Dynamic Arrays class as it will get difficult to manage otherwise by hand but
think on how one would do that. Remember our resizing of the array code?
How do we print out the contents of an array?
• The Arrays class has a fancy built-in, but it is important to try and build
our own, as it will show us a few new tricks J.
• Let’s adjust our previous one-dimensional toString() method that acts on
a one-dimensional array. https://onlinegdb.com/kO7Ty9_DB )

• Take the time to trace the code.


• By writing the code ourselves, we
can see two new important things.
• Do you see them?
• Look harder …
Quest-que c’est ?
• What exactly are these values:
• myArray.length
• This will retrieve the number of ROWS in the two-dimensional array myArray.
• myArray[0].length
• This will return the number of COLUMNS in the two-dimensional array myArray assuming we have
implemented a rectangular array where each row has the same number of columns.
• The following code will initialize each of the entries in the two-dimensional array to
a random number between 1 and 10.

https://onlinegdb.com/AgFEW-OlP

Pay careful attention to line 8. We really should have


coded myNumbers[i].length instead.

This would better handle the situation where each row


may not have the same number of columns. For now this
is fine, but later we will use jagged arrays where this will
be important to code correctly.
Lettuce take A short cut …
• We now know how to iterate over our two-dimensional array one element at
a time using two nested for loops.
• We also know how to access the row count and column count of our two-
dimensional array.
• Earlier in the course, I showed you how to use the toString() method of the
Arrays class.

Output:

• Unfortunately, the toString() method cannot be used to display the contents


of a two-dimensional array.
deeeeeeeeepTooooooooStrrrrring
• Let me show you what happens …

• We must use the deepToString method to print out a two-dimensional array!


Replace the last line above with the following:

• Explore how a three-dimensional array is created, set to random values and


outputted to the console: https://onlinegdb.com/wMwJjIuAW Whut? Someone
wants to implement three dimensional Tic-Tac-Toe?
S’more fun … emmm s’mores
• Lettuce look at a few more examples … emmm … lettuce.

Yes yes. Lettuce eat


s’more lettuce cookies!
One last thought before continuing …
• This is how we can assign values to two dimensional arrays at compile
time (as well as one dimensional): https://onlinegdb.com/CgG1RIziX
Lettuce examine the following code:
• Examine the following code. What do you think is happening in the last line
of code on the right? There are quite the chain of toString() calls going on!

• The Arrays.deepToString method when applied to the myEmployees array


which is a two-dimensional array of type Employee calls the toString() of the
Employee class! Don’t believe me? Lettuce remove it and see what happens.
• You can run the code here: https://www.onlinegdb.com/fork/quPv9k1wT
Tic-Tac-Toe anyone ? …
• It is more natural to store the information for a Tic-Tac-Toe board in a two-
dimensional array where the index locations are rows AND columns. A 3x3
two-dimensional array could easily accommodate our game board J.
• When referencing a two-dimensional array, we always reference the row first
and then the column. Lettuce pretend (yes let us!) we have a two-
dimensional array of type String called myArray:
Tic-Tac-Toe …
• I am going to change the implementation of the board to be a two-
dimensional array. NONE of the other code would need to change!
• Only one change … you need to create an instance of GameBoardTwo J
Tic-Tac-Toe … continued …
• The last few methods …J
Wait just a second …
• You probably missed it in the Tic-Tac-Toe two-dimensional array implementation how we accessed
specific rows and columns.
• Let’s take a closer look. Assuming we have a rectangular array three rows and four columns. Let’s
examine some code here to make sure you really understand what is happening:
This will output to the console the first row.
Refactored to use a loop J

• What about the third row?


Don’t forget zero based index is still
used for referencing index values. J
Wait just a second minute …
• What about accessing all the entries in a particular column?

This will output to the console the first column


Refactored to use a loop J

• What about the third column?

Don’t forget zero based index is still


used for referencing index values. J
Tic-Tac-Toe Continued …
• Go back to the code you wrote the other day that used a one-dimensional
implementation. If you have done things correctly in your Main class, you
will only need to make a few minor changes in your Main class to use the
two-dimensional implementation.
• Here is the code for both classes: https://onlinegdb.com/UEJEhk_4z
• Does your code still run?
Tic-Tac-Toe
Completed
Here is the finished product …
https://onlinegdb.com/LWpafKQvs
Two-Dimensional Fun …
• Trace the following code …

Lettuce run the code:


https://onlinegdb.com/AIfXVMjjh
Mini-Problem
• Create a program that meets the following
specifications:
• Prompts the user for the number of
rows and columns in a two-dimensional
array.
• Fills the array with random entries.
• Displays the array.
• Calculates the sum, the average, highest
and lowest entries of the entire array.
• Calculates the sum, the average, the
highest and lowest entries of each row.
• Calculate the sum, the average, the
highest and lowest entries of each
column.
What just happened …
• Slick little trick …
What just happened …
• Slick little trick … what exactly happened there? Examine that for loop
definition carefully …

• Lettuce play around with this a wee bit …


What just happened …
• On the previous slide, we saw how to extract a row from a rectangular two-
dimensional array and assign the contents to a one-dimensional array.
• Can we do the same for a column? Well of course we can. Think about that for a
moment … write the code necessary to assign each of the entries within the first
column of the two-dimensional array to a one-dimensional array.
• Start with a two-dimensional int array with 4 rows and 3 columns.

https://onlinegdb.com/rbAQwoudTn
Solution …
• Here is my solution … take a moment to dissect it to see what new tricks you
can learn J
Solution …
• Here is my solution … take a moment to dissect it to see what new tricks you
can learn J
Solution …
• Take a moment to dissect it to see what new tricks you can learn J

Why do you think I would do


things this way?

https://onlinegdb.com/BupJqN0zP
Ragged or Jagged Arrays
• In each of the examples we have looked at so far, we have worked with
rectangular two-dimensional arrays.
• Java allows us to create and work with what are called ragged/jagged
arrays which are not rectangular and have different sized rows and
columns.
• Sample ragged or jagged arrays:
But how do we do this?
• Let me show you … lettuce go back and examine what happens when
you create a rectangular array using the code on the left and compare it
to what is its equivalent on the right:

• If you want, you can make each of numbers[0], numbers[1], and


numbers[2] a different length with the following code:

• Let’s play a bit with this ragged array and write s’more code to do
something.
Here is some simple code:

• What does this do … trace it … How does it work?

• The above code could be used to store the following ragged two-
dimensional matrix of integers:
We can also …
• Should we need to fill the array at compile time we can do so using the
following:

• Rather than using the Arrays.deepToString() method, we could write the


following code to output our array:

• Each row could represent say a student’s earnings for a week, with each of
the entries within that row representing week 1, week 2, and so on.
Obviously if we are going to talk about earnings, we should use double 😜.
• We won’t be doing any assignment with ragged/jagged arrays. Just be aware
that they can be defined and can solve a problem when you don’t want a
rectangular array. Besides, it may be easier to use dynamic arrays to
implement a ragged array.
Mini-Problem
• Write the code necessary to setup the following
Jagged array of type String.

• Go back and now extend your code so that


instead it is using a Jagged array consisting of
type String, it now defines a jagged array of type
SuperHero. Create a SuperHero class (String
name, int age fields) ..
• Extension is to prompt the user for the data
rather than having it setup at run time.
• Prompt for number of rows, then prompt for the
number of columns within each row.
• Then prompt for the data to fill the jagged array.

You might also like