Week 11

Arrays.

Example 1

Words list

Basic setup for reading an array of words:

        package words;

        import java.io.IOException;
        import java.net.MalformedURLException;
        import java.net.URL;
        import java.util.Scanner;

        public class WordsMain {

            public static void main(String[] args) throws MalformedURLException, IOException {
                // List of words read from file
                String[] words = new String[500]; 
                // Read file from website
                URL wordsPage = new URL("http://ilzd.org/teaching/current/data/words3.txt");
                Scanner in = new Scanner(wordsPage.openStream());
                int i = 0;
                while (in.hasNext() && i < words.length) {
                    words[i] = in.nextLine();
                    i = i + 1;
                }
            }
        }

Example 2

Project source as a Maven project that you can open in NetBeans. It should automatically bring in the Processing library (might take several minutes to download everything when you first run).

 
        package org.ilzd.simplelife;

        import processing.core.PApplet;

        /**
         * Simple version of Conway's Game of Life.
         *
         */
        public class SimpleLife extends PApplet {

            // Defines game grid size
            public static final int ROWS = 50, COLS = 50;
            // Constants used to represent grid state
            public static final int DEAD = 0, ALIVE = 1;
            // Size of neighborhood to search when updating grid
            public static final int NSIZE = 1;

            // Note: all of the member variables and methods below (except main)
            // should NOT be static.  (Why?)

            // Toggle to pause updating of grid
            public boolean paused = false;

            // Grid of game states
            public int[][] board = new int[ROWS][COLS];

            @Override
            public void setup() {
                size(500, 500);
            }

            // Update and draw grid
            @Override
            public void draw() {
                if (!paused)
                    update();
                for (int r = 0; r < board.length; ++r) {
                    for (int c = 0; c < board.length; ++c) {
                        drawRect(r, c, board[r][c]);
                    }
                }
            }

            // Draw a single square in the grid
            public void drawRect(int r, int c, int value) {
                float w = width / COLS;
                float h = height / ROWS;
                fill(value == ALIVE ? 0 : 255);
                rect(c * w, r * h, w, h);
            }

            // Set squares to alive when mouse is pressed and dragged
            @Override
            public void mouseDragged() {
                setAlive(mouseX, mouseY);
            }

            // Set squares to alive when mouse is clicked
            @Override
            public void mouseClicked() {
                setAlive(mouseX, mouseY);
            }

            // Set square at pixel (x,y) to alive
            private void setAlive(int x, int y) {
                int r = (int)(ROWS * (float)mouseY / height);
                int c = (int)(COLS * (float)mouseX / width);
                if (r < 0 || r >= ROWS || c < 0 || c >= COLS)
                    return;
                board[r][c] = ALIVE;
            }

            @Override
            public void keyPressed() {
                // Toggle updating
                if (key == ' ')
                    paused = !paused;
            }


            // Update game grid according to the following rules:
            // If a square is alive and has less than 2 or more than 3 neighbors, it dies.
            // If a square is dead and has exactly 3 neighbors, it becomes alive.
            public void update() {
                int[][] board1 = copyBoard();
                for (int r = 0; r < board1.length; ++r) {
                    for (int c = 0; c < board1.length; ++c) {
                        int alive = countNeighborhood(r, c);
                        if (board[r][c] == ALIVE) {
                            if (alive < 2 || alive > 3)
                                board1[r][c] = DEAD;
                        } else if (alive == 3) {
                                board1[r][c] = ALIVE;
                        }
                    }
                }
                board = board1;
            }

            public int[][] copyBoard() {
                int[][] board1 = new int[ROWS][COLS];
                for (int r = 0; r < board1.length; ++r)
                    System.arraycopy(board[r], 0, board1[r], 0, board[r].length);
                return board1;
            }

            // Count the number of neighbors of square at position (r, c)
            public int countNeighborhood(int r, int c) {
                int alive = 0;
                for (int roff = -NSIZE; roff <= NSIZE; ++roff) {
                    for (int coff = -NSIZE; coff <= NSIZE; ++coff) {
                        if (roff == 0 && coff == 0)
                            continue;
                        int r1 = (ROWS + r + roff) % ROWS;
                        int c1 = (COLS + c + coff) % COLS;
                        if (board[r1][c1] == ALIVE)
                            alive = alive + 1;
                    }
                }
                return alive;
            }

            public static void main(String[] args) {
                PApplet.main(new String[] {"org.ilzd.simplelife.SimpleLife"});
            }

        }

Boring example from class


        package week11;

        public class Week11Main {

                // Return last value in array,
                // or 0 if array is empty.
                public static int last(int[] x) {
                        // last index: x.length - 1
                        if (x.length == 0)
                                return 0;
                        else
                                return x[x.length - 1];
                }

                // Fill array a with value x
                public static void fill(int[] a, int x) {
                        for (int i = 0; i < a.length; i = i + 1) {
                                a[i] = x;
                        }
                }

                public static void main(String[] args) {
                        int[] a = {1, 3, 5, 7}; // array literal
                        System.out.println(a);
                        for (int i = 0; i < a.length; i = i + 1) {
                                System.out.print(a[i] + " ");
                        }
                        // Alternate for loop syntax for iterating
                        // through an array
                        for (int x : a) {
                                System.out.print(x + " ");
                        }
                        int[] b = new int[0];
                        System.out.println(last(b));
                        fill(a, 3);  // now a = {3, 3, 3, 3}
                        for (int x : a) {
                                System.out.print(x + " ");
                        }
                }

        }

Reading

Java for Everyone, chapter 6 (again).

Homework

All numbered problems are from Java for Everyone. Due Wednesday, April 6.

Feel free to replace any of the book problems with others that look interesting – but if you do, try not to just pick all easy (1-star) ones.