Wednesday, February 9, 2011

02/08/2011

Today's Do Now:
Give an array of ints length 3, return a new array with the elements in reverse, order, so {1, 2, 3} becomes {3, 2, 1}

reverse3({1, 2, 3}) --> {3, 2, 1}
reverse3({5, 11, 9}) --> {9, 11, 5}
reverse3({7, 0, 0}) --> {0,0,7}

public int[] reverse3(int[] nums) {
int[] reversed = new int[3];
for ( int i = 0; i < nums.length; i++) {
reversed[i] = nums[2-i];
}

OR

reversed[0] = nums[2];
reversed[1] = nums[1];
reversed[2] = nums[0];


Then we went over to the Final exam, the last question before the bonus (#15)
(refer to mj2x-05-reviewFinal.pdf )

solution:

public static void printInvite( String name, String gift) {
System.out.println("Dear" + name);
System.out.println("Thanks for the" +gift+ "you...");
System.out.println("I really hope...");
System.out.println("Love, me.");
}
public static void printInvitations() {
printInvitation("Abuelita", "socks");
printInvitation("Uncle George", "rocks");
}

Bonus Question:
int pow;
for (int pow = 0; Math.pow(2,pow) < n; pow++)
{}
pow--; //*at this point is the largest power of 2 while less than n
String results = "1";


Then we went over the previous homework assignment: mj2x-03-arrayLists-p9.pdf
(The answers should be posted on the website)

R8.16
(a) do a "for" loop. You can return false when they do not match but you can't return true until the very end
(b) a "for" loop in which you send the values of one array to the other.
(c) go to every single element and send it equal to 0
(d) use list.clear OR while list.length > 0, remove all elements

R.17 True or false?
1- True
2- True
3- False *subscripts and indices mean the same thing*
4- True
5- True
6- false
7- True
8- False

http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Brief introduction to Two-Dimensional Arrays (refer to Today's SMARTboard notes)

Why do we want to use them? Let's say we wanted to make a program to play a tic-tac toe game
Computer scientists would visualize this as being an array in two directions: rows and columns
You would start at 0 on both sides. It's like playing that 80s game Battleship
If you wanted to talk about a specific spot, you would say (0,1)
-->board[0][1]
How would you actually DECLARE these things?

Declaring a 2D Array

int[][] board = new int [3 which is the size of the rows][3 which is the size of the columns];
To know what's an X and O
final int X = 1;
final int O = 2;
final int EMPTY = 0;

You'll need 2 loops for this dimension, going row by row. Similar to what we did for the TimesTables assignment

for(int row = 0; row < 3; row++){
(int col = 0; col <3; col++){
if(board[row][col]==EMPTY)
System.out.print(" ");
else if (board[row][col]==X)
System.out.print("O")
}
}

System.out.println();
}

The HW is due on Thursday. Refer to website. It's going to be about Tic-Tac-Toe
We'll have time in class to do them Wednesday as well.
Bye!

1 comment:

  1. I emailed this to Mr. Jacoby but didn't post it. Here it is! sorry.

    ReplyDelete